import { Head, Link } from "@inertiajs/react";
import { router } from "@inertiajs/react";
import { useState, useEffect } from "react";
import {
    PageContainer,
    Card,
    SectionTitle,
    StatusBadge,
    formatDate,
    ConfirmModal,
    useRole,
    ViewViolationModal,
} from "../Violations/ViolationUI";
import { PaymentModal, PaymentSummaryModal } from "../Violations/PaymentModal";

const styles = `
  @keyframes fadeIn {
    from { opacity: 0; }
    to   { opacity: 1; }
  }
  @keyframes fadeInDown {
    from { opacity: 0; transform: translateY(-16px); }
    to   { opacity: 1; transform: translateY(0); }
  }
  @keyframes fadeInUp {
    from { opacity: 0; transform: translateY(20px); }
    to   { opacity: 1; transform: translateY(0); }
  }
  .page-enter       { animation: fadeIn 0.4s ease both; }
  .filter-bar-enter { animation: fadeInDown 0.4s ease both; }
  .row-enter        { animation: fadeInUp 0.35s ease both; }
  .row-hover        { transition: background 0.15s ease, transform 0.15s ease, box-shadow 0.15s ease; }
  .row-hover:hover  { background: #f1f5f9; transform: translateX(2px); box-shadow: -3px 0 0 0 #3b82f6; }
`;

export default function Show({ violator }) {
    const [confirmId, setConfirmId] = useState(null);
    const [viewTarget, setViewTarget] = useState(null);
    const [mounted, setMounted] = useState(false);
    const [paymentTarget, setPaymentTarget] = useState(null);
    const [paidResult, setPaidResult] = useState(null);
    const [paymentToast, setPaymentToast] = useState(null);
    const { isAdminOrAbove, isSuperadmin } = useRole();

    const currentAge = violator.birthday
        ? Math.floor(
              (new Date() - new Date(violator.birthday)) /
                  (365.25 * 24 * 60 * 60 * 1000),
          )
        : null;

    const isMinor = currentAge !== null && currentAge < 16;

    function getAgeAtOffense(dateOfViolation) {
        if (!violator.birthday || !dateOfViolation) return null;
        return Math.floor(
            (new Date(dateOfViolation) - new Date(violator.birthday)) /
                (365.25 * 24 * 60 * 60 * 1000),
        );
    }

    function handlePaid(result) {
        setPaymentTarget(null);
        setPaidResult(result);
    }

    function handleFinishPayment() {
        const message = paidResult
            ? `Payment recorded successfully. Receipt #${paidResult.receiptNumber}.`
            : null;

        setPaidResult(null);
        router.reload({ only: ["violator"] });

        if (message) {
            setPaymentToast(message);
            setTimeout(() => setPaymentToast(null), 3000);
        }
    }

    useEffect(() => {
        const t = setTimeout(() => setMounted(true), 10);
        return () => clearTimeout(t);
    }, []);

    function handleDelete() {
        router.delete(
            `/violations/${confirmId}?source=violator&violator_id=${violator.id}`,
        );
        setConfirmId(null);
    }

    return (
        <div className="min-h-screen bg-slate-50">
            <style>{styles}</style>
            <Head title={`${violator.first_name} ${violator.last_name}`} />
            <PageContainer>
                <ConfirmModal
                    open={!!confirmId}
                    title="Delete Violation"
                    message="Are you sure you want to delete this violation? This action cannot be undone."
                    onConfirm={handleDelete}
                    onCancel={() => setConfirmId(null)}
                />
                <ViewViolationModal
                    open={!!viewTarget}
                    violation={viewTarget}
                    onClose={() => setViewTarget(null)}
                />
                <PaymentModal
                    violator={paymentTarget}
                    open={!!paymentTarget}
                    onClose={() => setPaymentTarget(null)}
                    onPaid={handlePaid}
                />
                <PaymentSummaryModal
                    open={!!paidResult}
                    payment={paidResult}
                    onFinish={handleFinishPayment}
                />

                <div className={`mb-8 ${mounted ? "page-enter" : "opacity-0"}`}>
                    <Link
                        href={route("violators.index")}
                        className="text-sm text-blue-600 hover:underline"
                    >
                        ← Back to Violators
                    </Link>
                    <div className="flex justify-between items-start mt-3">
                        <div>
                            <h1 className="text-3xl font-bold text-slate-900">
                                {violator.first_name} {violator.last_name}
                            </h1>
                            <p className="text-slate-500 mt-1">
                                Violator Profile
                            </p>
                            {isMinor && (
                                <div className="mt-2 inline-block px-3 py-1.5 bg-red-50 border border-red-200 rounded-md text-xs text-red-700 font-semibold">
                                    ⚠ This violator is a minor
                                </div>
                            )}
                        </div>
                        <Link
                            href={route("violations.create", {
                                violator_id: violator.id,
                                from: "violators.show",
                            })}
                            className="px-5 py-2.5 bg-blue-50 rounded-lg text-blue-500 border border-blue-200 hover:bg-blue-100 rounded- xlg transition font-bold"
                        >
                            File Violation
                        </Link>
                    </div>
                </div>

                <div className={mounted ? "filter-bar-enter" : "opacity-0"}>
                    <Card>
                        <div className="flex justify-between items-center mb-4">
                            <SectionTitle>Personal Information</SectionTitle>
                            {isAdminOrAbove && (
                                <Link
                                    href={route("violators.edit", violator.id)}
                                    className="flex items-center gap-1.5 px-3 py-1.5 text-sm bg-blue-50 text-blue-600 rounded-md hover:bg-blue-100 transition"
                                >
                                    <svg
                                        xmlns="http://www.w3.org/2000/svg"
                                        className="w-4 h-4"
                                        viewBox="0 0 24 24"
                                        fill="none"
                                        stroke="currentColor"
                                        strokeWidth="2"
                                        strokeLinecap="round"
                                        strokeLinejoin="round"
                                    >
                                        <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
                                        <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
                                    </svg>
                                    Edit
                                </Link>
                            )}
                        </div>
                        <div className="grid md:grid-cols-2 gap-4 text-sm">
                            <div>
                                <p className="text-slate-500 mb-1">Full Name</p>
                                <p className="font-medium text-slate-800">
                                    {violator.first_name} {violator.last_name}
                                </p>
                            </div>
                            <div>
                                <p className="text-slate-500 mb-1">Gender</p>
                                <p className="font-medium text-slate-800">
                                    {violator.gender}
                                </p>
                            </div>
                            <div>
                                <p className="text-slate-500 mb-1">Birthday</p>
                                <p className="font-medium text-slate-800">
                                    {formatDate(violator.birthday)}
                                </p>
                            </div>
                            <div>
                                <p className="text-slate-500 mb-1">Age</p>
                                <p className="font-medium text-slate-800 flex items-center gap-2">
                                    {currentAge !== null
                                        ? `${currentAge} years old`
                                        : "—"}
                                    {isMinor && (
                                        <span className="px-2 py-0.5 bg-red-50 text-red-700 border border-red-200 rounded-md text-xs font-semibold">
                                            ⚠ Minor
                                        </span>
                                    )}
                                </p>
                            </div>
                            <div>
                                <p className="text-slate-500 mb-1">
                                    Contact Number
                                </p>
                                <p className="font-medium text-slate-800">
                                    {violator.contact_number}
                                </p>
                            </div>
                            <div className="md:col-span-2">
                                <p className="text-slate-500 mb-1">Address</p>
                                <p className="font-medium text-slate-800">
                                    {violator.address}
                                </p>
                            </div>
                        </div>
                    </Card>

                    <Card className="mt-5">
                        <SectionTitle>Violation Records</SectionTitle>
                        {violator.violations.length === 0 ? (
                            <p className="text-center text-slate-400 py-10">
                                No violations recorded for this person.
                            </p>
                        ) : (
                            <div className="overflow-x-auto">
                                <table className="w-full text-sm">
                                    <thead className="sticky top-0 z-10 bg-slate-100 dark:bg-slate-700">
                                        <tr className="border-b border-slate-200">
                                            {[
                                                "Ticket No.",
                                                "Violation Type",
                                                "Offense #",
                                                "Fine",
                                                "Status",
                                                "Date",
                                                "Age at Offense",
                                                "Location",
                                                "View",
                                                isAdminOrAbove && "Actions",
                                            ]
                                                .filter(Boolean)
                                                .map((h) => (
                                                    <th
                                                        key={h}
                                                        className="text-left px-4 py-3 text-slate-500 font-medium"
                                                    >
                                                        {h}
                                                    </th>
                                                ))}
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {violator.violations.map(
                                            (violation, i) => (
                                                <tr
                                                    key={violation.id}
                                                    className="border-b border-slate-100 row-enter row-hover"
                                                    style={{
                                                        animationDelay: `${i * 40}ms`,
                                                    }}
                                                >
                                                    <td className="px-4 py-3 font-mono text-slate-800 whitespace-nowrap">
                                                        {violation.violation_number ??
                                                            "—"}
                                                    </td>
                                                    <td className="px-4 py-3 font-medium text-slate-800">
                                                        {
                                                            violation
                                                                .violation_type
                                                                .name
                                                        }
                                                    </td>
                                                    <td className="px-4 py-3">
                                                        <span
                                                            className={`px-2 py-1 rounded-md font-medium text-sm ${
                                                                violation.offense_number ===
                                                                1
                                                                    ? "bg-green-50 text-green-700"
                                                                    : violation.offense_number ===
                                                                        2
                                                                      ? "bg-orange-50 text-orange-700"
                                                                      : "bg-red-50 text-red-700"
                                                            }`}
                                                        >
                                                            #
                                                            {
                                                                violation.offense_number
                                                            }
                                                        </span>
                                                    </td>
                                                    <td className="px-4 py-3 text-slate-600">
                                                        ₱
                                                        {Number(
                                                            violation.fine_amount,
                                                        ).toLocaleString()}
                                                    </td>
                                                    <td className="px-4 py-3">
                                                        <StatusBadge
                                                            violationId={
                                                                violation.id
                                                            }
                                                            currentStatus={
                                                                violation.status
                                                            }
                                                        />
                                                    </td>
                                                    <td className="px-4 py-3 text-slate-600">
                                                        {formatDate(
                                                            violation.date_of_violation,
                                                        )}
                                                    </td>
                                                    <td className="px-4 py-3">
                                                        {(() => {
                                                            const ageAtOffense =
                                                                getAgeAtOffense(
                                                                    violation.date_of_violation,
                                                                );
                                                            const wasMinor =
                                                                ageAtOffense !==
                                                                    null &&
                                                                ageAtOffense <
                                                                    16;
                                                            return (
                                                                <span
                                                                    className={`flex items-center gap-1.5 ${
                                                                        wasMinor
                                                                            ? "text-red-700 font-semibold"
                                                                            : "text-slate-600"
                                                                    }`}
                                                                >
                                                                    {ageAtOffense !==
                                                                    null
                                                                        ? ageAtOffense
                                                                        : "—"}
                                                                    {wasMinor && (
                                                                        <span className="px-1.5 py-0.5 bg-red-50 border border-red-200 rounded text-xs">
                                                                            Minor
                                                                        </span>
                                                                    )}
                                                                </span>
                                                            );
                                                        })()}
                                                    </td>
                                                    <td className="px-4 py-3 text-slate-600">
                                                        {violation.location}
                                                    </td>
                                                    <td className="px-4 py-3">
                                                        <button
                                                            onClick={() =>
                                                                setViewTarget(
                                                                    violation,
                                                                )
                                                            }
                                                            className="px-3 py-1 text-sm bg-blue-50 text-blue-600 rounded-md hover:bg-blue-100 transition"
                                                        >
                                                            View
                                                        </button>
                                                    </td>
                                                    {isAdminOrAbove && (
                                                        <td className="px-4 py-3">
                                                            <div className="flex gap-2">
                                                                {violation.status ===
                                                                "paid" ? (
                                                                    <button
                                                                        disabled
                                                                        className="px-3 py-2 text-sm bg-slate-100 text-slate-400 rounded-md cursor-not-allowed"
                                                                    >
                                                                        Paid
                                                                    </button>
                                                                ) : (
                                                                    <button
                                                                        onClick={() =>
                                                                            setPaymentTarget(
                                                                                violator,
                                                                            )
                                                                        }
                                                                        className="px-3 py-2 text-sm bg-green-50 text-green-600 rounded-md hover:bg-green-100 transition"
                                                                    >
                                                                        Pay
                                                                    </button>
                                                                )}
                                                                {isAdminOrAbove &&
                                                                    (violation.status ===
                                                                    "paid" ? (
                                                                        <button
                                                                            disabled
                                                                            className="px-3 py-2 text-sm rounded-lg border border-slate-200 text-slate-400 cursor-not-allowed"
                                                                        >
                                                                            Edit
                                                                            Violation
                                                                        </button>
                                                                    ) : (
                                                                        <Link
                                                                            href={route(
                                                                                "violations.edit",
                                                                                {
                                                                                    violation:
                                                                                        violation.id,
                                                                                    from: "violators.show",
                                                                                    violator_id:
                                                                                        violator.id,
                                                                                },
                                                                            )}
                                                                            className="px-3 py-2 text-sm rounded-lg border border-slate-300 text-slate-550"
                                                                        >
                                                                            Edit
                                                                            Violation
                                                                        </Link>
                                                                    ))}
                                                                {isSuperadmin &&
                                                                    (violation.status ===
                                                                    "paid" ? (
                                                                        <button
                                                                            disabled
                                                                            className="px-3 py-2 text-sm bg-slate-100 text-slate-400 rounded-md cursor-not-allowed"
                                                                        >
                                                                            Delete
                                                                        </button>
                                                                    ) : (
                                                                        <button
                                                                            onClick={() =>
                                                                                setConfirmId(
                                                                                    violation.id,
                                                                                )
                                                                            }
                                                                            className="px-3 py-2 text-sm bg-red-50 text-red-600 rounded-md hover:bg-red-100 transition"
                                                                        >
                                                                            Delete
                                                                        </button>
                                                                    ))}
                                                            </div>
                                                        </td>
                                                    )}
                                                </tr>
                                            ),
                                        )}
                                    </tbody>
                                </table>
                            </div>
                        )}
                    </Card>
                </div>
            </PageContainer>
            {paymentToast && (
                <div className="fixed bottom-6 right-6 z-50">
                    <div className="flex items-center gap-3 bg-white border border-slate-200 pl-3 pr-5 py-3 rounded-2xl shadow-xl shadow-slate-900/10">
                        <div className="w-8 h-8 rounded-full bg-green-50 flex items-center justify-center shrink-0">
                            <span className="text-green-500 text-base leading-none">
                                ✓
                            </span>
                        </div>
                        <p className="text-sm font-semibold text-slate-800">
                            {paymentToast}
                        </p>
                    </div>
                </div>
            )}
        </div>
    );
}
