import { Head, Link, router, useForm } from '@inertiajs/react';
import { useEffect, useState } from 'react';
import { FileText, Search, ShieldCheck } from 'lucide-react';

type VerificationDocument = {
    id: number;
    type: string;
    mime_type: string | null;
    status: string;
    uploaded_at: string | null;
    preview_url: string | null;
};

type VerificationMessage = {
    id: number;
    kind: string;
    body: string;
    sender: string;
    sender_role: string;
    created_at: string | null;
};

type VerificationRequest = {
    id: number;
    status: string;
    created_at: string | null;
    profile: {
        id: number;
        name: string;
        type: 'rider' | 'driver';
        slug: string;
    };
    event: { title: string; slug: string; organizer: string } | null;
    documents: VerificationDocument[];
    messages: VerificationMessage[];
};

type PaginatedRequests = {
    data: VerificationRequest[];
    current_page: number;
    last_page: number;
    total: number;
    links: { url: string | null; label: string; active: boolean }[];
};

type Props = {
    requests: PaginatedRequests;
    filters: { status: string; q: string };
    counts: { pending: number; needs_information: number };
};

const documentLabels: Record<string, string> = {
    fmssl_licence: 'FMSSL racing licence',
    nic: 'NIC',
    birth_certificate: 'Birth document',
    vehicle_permit: 'Vehicle permit',
    licence: 'Previously submitted licence',
    identity: 'Previously submitted identity document',
};

function formatDate(date: string | null): string {
    return date
        ? new Date(date).toLocaleString('en-LK', {
              dateStyle: 'medium',
              timeStyle: 'short',
          })
        : 'Date not available';
}

export default function OrganizerVerification({
    requests,
    filters,
    counts,
}: Props) {
    const [selectedId, setSelectedId] = useState<number | null>(
        requests.data[0]?.id ?? null,
    );
    const [query, setQuery] = useState(filters.q);
    const selected =
        requests.data.find((item) => item.id === selectedId) ??
        requests.data[0] ??
        null;
    const reply = useForm({ message: '' });

    useEffect(() => {
        if (!requests.data.some((item) => item.id === selectedId)) {
            setSelectedId(requests.data[0]?.id ?? null);
        }
    }, [requests.data, selectedId]);

    function applyFilters(next: Partial<Props['filters']> = {}) {
        router.get(
            '/organizer/verification',
            { ...filters, ...next, q: next.q ?? query },
            {
                preserveScroll: true,
                preserveState: true,
                replace: true,
            },
        );
    }

    function requestInformation(event: React.FormEvent<HTMLFormElement>) {
        event.preventDefault();
        if (!selected) return;
        reply.post(
            `/organizer/verification/${selected.id}/request-information`,
            {
                preserveScroll: true,
                onSuccess: () => reply.reset('message'),
            },
        );
    }

    return (
        <>
            <Head title="Racer verification queue" />
            <main className="min-h-full bg-slate-50 px-4 py-4 text-slate-900 sm:px-6 lg:px-7">
                <div className="mx-auto w-full max-w-[1500px]">
                    <header className="mb-4 flex flex-wrap items-end justify-between gap-4">
                        <div>
                            <p className="text-xs font-semibold text-slate-500">
                                Racing.lk / Organizer workspace
                            </p>
                            <h1 className="mt-1 text-2xl font-bold tracking-tight text-slate-900">
                                Racer verification
                            </h1>
                            <p className="mt-1 max-w-2xl text-sm text-slate-600">
                                Review documents for racers who selected one of
                                your events. You can request more information;
                                Racing.lk staff make the final verification
                                decision.
                            </p>
                        </div>
                        <div className="flex gap-3">
                            <div className="rounded-xl border border-[#d9d5ca] bg-white px-4 py-3">
                                <span className="block text-[10px] font-bold tracking-wide text-[#737a74] uppercase">
                                    Awaiting review
                                </span>
                                <strong className="mt-1 block text-xl font-black">
                                    {counts.pending}
                                </strong>
                            </div>
                            <div className="rounded-xl border border-[#d9d5ca] bg-white px-4 py-3">
                                <span className="block text-[10px] font-bold tracking-wide text-[#737a74] uppercase">
                                    Racer response
                                </span>
                                <strong className="mt-1 block text-xl font-black">
                                    {counts.needs_information}
                                </strong>
                            </div>
                        </div>
                    </header>

                    <section className="grid min-h-[620px] overflow-hidden rounded-2xl border border-[#d9d5ca] bg-white shadow-sm lg:grid-cols-[minmax(280px,370px)_minmax(0,1fr)]">
                        <aside className="flex min-h-[320px] flex-col border-b border-[#d9d5ca] lg:border-r lg:border-b-0">
                            <div className="space-y-3 border-b border-[#e7e3da] bg-[#f8f6f0] p-4">
                                <form
                                    onSubmit={(event) => {
                                        event.preventDefault();
                                        applyFilters({ q: query });
                                    }}
                                    className="relative"
                                >
                                    <Search
                                        size={16}
                                        className="absolute top-1/2 left-3 -translate-y-1/2 text-[#777d77]"
                                    />
                                    <input
                                        value={query}
                                        onChange={(event) =>
                                            setQuery(event.target.value)
                                        }
                                        placeholder="Search racer"
                                        className="h-11 w-full rounded-lg border border-[#d9d5ca] bg-white pr-3 pl-9 text-sm outline-none focus:border-[#c83221] focus:ring-2 focus:ring-[#c83221]/10"
                                    />
                                </form>
                                <div className="flex gap-2">
                                    {(
                                        [
                                            'pending',
                                            'needs_information',
                                            'all',
                                        ] as const
                                    ).map((status) => (
                                        <button
                                            key={status}
                                            type="button"
                                            onClick={() =>
                                                applyFilters({ status })
                                            }
                                            className={`min-h-9 rounded-lg px-3 text-xs font-bold transition ${filters.status === status ? 'bg-[#17191b] text-white' : 'bg-white text-[#59605b] ring-1 ring-[#d9d5ca] hover:bg-[#efede6]'}`}
                                        >
                                            {status === 'needs_information'
                                                ? 'Racer response'
                                                : status === 'all'
                                                  ? 'All'
                                                  : 'Pending'}
                                        </button>
                                    ))}
                                </div>
                            </div>
                            <div className="flex-1 divide-y divide-[#eeece6]">
                                {requests.data.length ? (
                                    requests.data.map((item) => (
                                        <button
                                            key={item.id}
                                            type="button"
                                            onClick={() =>
                                                setSelectedId(item.id)
                                            }
                                            aria-current={
                                                selected?.id === item.id
                                            }
                                            className={`block w-full border-l-[3px] px-4 py-4 text-left transition hover:bg-[#f8f6f0] ${selected?.id === item.id ? 'border-[#e8422b] bg-[#fbf5ed]' : 'border-transparent'}`}
                                        >
                                            <span className="flex items-start justify-between gap-3">
                                                <strong className="text-sm font-extrabold text-[#17191b]">
                                                    {item.profile.name}
                                                </strong>
                                                <span
                                                    className={`rounded-full px-2 py-1 text-[9px] font-black uppercase ${item.status === 'needs_information' ? 'bg-[#fff0c5] text-[#795810]' : 'bg-[#e8eee9] text-[#45634e]'}`}
                                                >
                                                    {item.status ===
                                                    'needs_information'
                                                        ? 'Awaiting racer'
                                                        : item.status}
                                                </span>
                                            </span>
                                            <span className="mt-1 block text-xs text-[#6f766f]">
                                                {item.profile.type} ·{' '}
                                                {item.event?.title ??
                                                    'Staff review'}
                                            </span>
                                            <span className="mt-1 block text-[10px] text-[#92978f]">
                                                Submitted{' '}
                                                {formatDate(item.created_at)}
                                            </span>
                                        </button>
                                    ))
                                ) : (
                                    <div className="p-8 text-center">
                                        <ShieldCheck
                                            className="mx-auto text-[#6b8b72]"
                                            size={30}
                                        />
                                        <p className="mt-3 font-bold text-[#17191b]">
                                            No requests in this view
                                        </p>
                                        <p className="mt-1 text-xs text-[#737a74]">
                                            Requests appear here when a racer
                                            selects one of your published
                                            events.
                                        </p>
                                    </div>
                                )}
                            </div>
                            <div className="flex items-center justify-between border-t border-[#e7e3da] px-4 py-3 text-xs text-[#737a74]">
                                <span>
                                    {requests.total} request
                                    {requests.total === 1 ? '' : 's'}
                                </span>
                                <div className="flex gap-1">
                                    {requests.links
                                        .filter(
                                            (link) =>
                                                link.url &&
                                                ![
                                                    '&laquo; Previous',
                                                    'Next &raquo;',
                                                ].includes(link.label),
                                        )
                                        .map((link) => (
                                            <Link
                                                key={link.label}
                                                href={link.url!}
                                                preserveScroll
                                                className={`grid size-8 place-items-center rounded-md text-xs font-bold ${link.active ? 'bg-[#17191b] text-white' : 'bg-[#f1efe9] text-[#59605b]'}`}
                                                dangerouslySetInnerHTML={{
                                                    __html: link.label,
                                                }}
                                            />
                                        ))}
                                </div>
                            </div>
                        </aside>

                        {selected ? (
                            <article className="min-w-0 p-4 sm:p-6 lg:p-8">
                                <div className="flex flex-wrap items-start justify-between gap-4 border-b border-[#e7e3da] pb-5">
                                    <div>
                                        <p className="text-[10px] font-black tracking-[.17em] text-[#c83221] uppercase">
                                            {selected.event?.title ??
                                                'Racing.lk staff review'}
                                        </p>
                                        <h2 className="mt-2 text-2xl font-black tracking-tight text-[#17191b]">
                                            {selected.profile.name}
                                        </h2>
                                        <p className="mt-1 text-sm text-[#737a74]">
                                            {selected.profile.type} profile ·
                                            submitted{' '}
                                            {formatDate(selected.created_at)}
                                        </p>
                                    </div>
                                    <Link
                                        href={`/${selected.profile.type}s/${selected.profile.slug}`}
                                        className="rounded-lg border border-[#d9d5ca] px-3 py-2 text-xs font-bold text-[#454c47] transition hover:border-[#17191b] hover:text-[#17191b]"
                                    >
                                        View public profile
                                    </Link>
                                </div>

                                <div className="mt-5 grid gap-4 xl:grid-cols-[minmax(0,1.2fr)_minmax(280px,.8fr)]">
                                    <section>
                                        <h3 className="text-sm font-black text-[#17191b]">
                                            Submitted documents
                                        </h3>
                                        <div className="mt-3 grid gap-3 sm:grid-cols-2">
                                            {selected.documents.map(
                                                (document) => (
                                                    <a
                                                        key={document.id}
                                                        href={
                                                            document.preview_url ??
                                                            undefined
                                                        }
                                                        target="_blank"
                                                        rel="noreferrer"
                                                        className="flex items-center gap-3 rounded-xl border border-[#e4e0d7] bg-[#f8f6f0] p-3 transition hover:border-[#b7b2a8]"
                                                    >
                                                        <span className="grid size-10 shrink-0 place-items-center rounded-lg bg-[#17191b] text-[#f6c84f]">
                                                            <FileText
                                                                size={18}
                                                            />
                                                        </span>
                                                        <span className="min-w-0">
                                                            <strong className="block truncate text-xs font-extrabold text-[#17191b]">
                                                                {documentLabels[
                                                                    document
                                                                        .type
                                                                ] ??
                                                                    'Racer document'}
                                                            </strong>
                                                            <small className="mt-1 block text-[10px] text-[#737a74]">
                                                                {document.mime_type ??
                                                                    'Document'}{' '}
                                                                ·{' '}
                                                                {formatDate(
                                                                    document.uploaded_at,
                                                                )}
                                                            </small>
                                                        </span>
                                                    </a>
                                                ),
                                            )}
                                        </div>
                                        <p className="mt-3 text-xs leading-5 text-[#737a74]">
                                            Documents are private. Review them
                                            only for this event; do not save or
                                            share copies.
                                        </p>
                                    </section>

                                    <section className="rounded-xl border border-[#e4e0d7] p-4">
                                        <h3 className="text-sm font-black text-[#17191b]">
                                            Request history
                                        </h3>
                                        <div className="mt-3 max-h-56 space-y-3 overflow-y-auto">
                                            {selected.messages.length ? (
                                                selected.messages.map(
                                                    (message) => (
                                                        <div
                                                            key={message.id}
                                                            className="rounded-lg bg-[#f8f6f0] p-3"
                                                        >
                                                            <p className="text-[10px] font-bold text-[#737a74]">
                                                                {message.sender}{' '}
                                                                ·{' '}
                                                                {formatDate(
                                                                    message.created_at,
                                                                )}
                                                            </p>
                                                            <p className="mt-1 text-xs leading-5 whitespace-pre-wrap text-[#343a36]">
                                                                {message.body}
                                                            </p>
                                                        </div>
                                                    ),
                                                )
                                            ) : (
                                                <p className="text-xs text-[#737a74]">
                                                    No messages yet.
                                                </p>
                                            )}
                                        </div>
                                    </section>
                                </div>

                                {selected.status === 'pending' ? (
                                    <form
                                        onSubmit={requestInformation}
                                        className="mt-4 rounded-xl border border-slate-200 bg-white p-4 sm:p-5"
                                    >
                                        <label
                                            htmlFor="request-information"
                                            className="text-sm font-bold text-slate-900"
                                        >
                                            Need a clearer copy or another
                                            document?
                                        </label>
                                        <p className="mt-1 text-xs text-slate-600">
                                            Your note will appear in the racer’s
                                            profile and be emailed to them.
                                            Racing.lk staff make the final
                                            verification decision.
                                        </p>
                                        <textarea
                                            id="request-information"
                                            value={reply.data.message}
                                            onChange={(event) =>
                                                reply.setData(
                                                    'message',
                                                    event.target.value,
                                                )
                                            }
                                            rows={3}
                                            maxLength={2000}
                                            required
                                            minLength={5}
                                            className="mt-3 w-full rounded-lg border border-slate-300 bg-white px-3 py-3 text-sm text-slate-900 outline-none placeholder:text-slate-400 focus:border-red-600 focus:ring-2 focus:ring-red-600/15"
                                            placeholder="Describe exactly what the racer should provide…"
                                        />
                                        {reply.errors.message && (
                                            <p className="mt-2 text-xs font-bold text-[#ffb5a9]">
                                                {reply.errors.message}
                                            </p>
                                        )}
                                        <button
                                            disabled={reply.processing}
                                            className="mt-3 min-h-10 rounded-lg bg-[#e8422b] px-4 py-2 text-xs font-extrabold text-white transition hover:bg-[#c83221] disabled:opacity-50"
                                        >
                                            Send information request
                                        </button>
                                    </form>
                                ) : (
                                    <p className="mt-5 rounded-xl bg-[#fff2ce] p-4 text-sm font-semibold text-[#634d19]">
                                        Waiting for the racer to reply. The
                                        final verification decision belongs to
                                        Racing.lk staff.
                                    </p>
                                )}
                            </article>
                        ) : (
                            <div className="grid min-h-[420px] place-items-center p-8 text-center">
                                <div>
                                    <ShieldCheck
                                        className="mx-auto text-[#9da39c]"
                                        size={36}
                                    />
                                    <p className="mt-3 font-bold text-[#454c47]">
                                        Select a verification request
                                    </p>
                                </div>
                            </div>
                        )}
                    </section>
                </div>
            </main>
        </>
    );
}
