import { useState } from 'react';
import { Head, router } from '@inertiajs/react';
import {
    Check,
    ChevronLeft,
    MapPin,
    Phone,
    SearchX,
    ShieldQuestion,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import type { InspectionConfirmProps, InspectionIntakeCandidate } from '@/types';

/**
 * The second screen: is this the right client?
 *
 * The address was looked up before the page was drawn, so what is here is what
 * the CRM already holds for that street. The crew is standing in front of the
 * meter, which makes them the best judge of whether the record is the same
 * place — a wrong link is worse than no link, because the report then files
 * itself against somebody else's system.
 *
 * "None of these" is a first-class answer: a system installed before this CRM
 * existed, a street the office spells differently, a customer who sold the house.
 * The report still opens, with the typed name and address on it, and the office
 * links it afterwards.
 */
export default function ConfirmClient({
    intake,
    candidates,
    purposes,
    urls,
}: InspectionConfirmProps) {
    const [busy, setBusy] = useState<number | 'none' | null>(null);

    const post = (siteId: number | null) => {
        setBusy(siteId ?? 'none');

        router.post(
            urls.link,
            { ...intake, site_id: siteId },
            { onFinish: () => setBusy(null) },
        );
    };

    const purpose =
        purposes.find((option) => option.value === intake.purpose)?.label ??
        'Inspection';

    return (
        <>
            <Head title="Confirm the client" />

            <div className="mx-auto grid max-w-3xl gap-5">
                <div>
                    <button
                        type="button"
                        onClick={() => router.visit(urls.back)}
                        className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-xs font-medium"
                    >
                        <ChevronLeft className="size-3.5" />
                        Change the name or address
                    </button>

                    <h1 className="mt-2 text-2xl font-semibold tracking-tight sm:text-3xl">
                        Is this the right client?
                    </h1>
                    <p className="text-muted-foreground mt-2 text-sm leading-relaxed">
                        {purpose} at{' '}
                        <span className="text-foreground font-medium">
                            {intake.site_address}
                        </span>
                        , {intake.site_suburb} {intake.site_state}{' '}
                        {intake.site_postcode} — for {intake.customer_name}.
                    </p>
                </div>

                <div className="grid gap-2.5">
                    {candidates.map((candidate: InspectionIntakeCandidate) => (
                        <div
                            key={candidate.id}
                            className="bg-card shadow-card rounded-xl p-4 ring-1 ring-hairline"
                        >
                            <div className="flex flex-wrap items-start justify-between gap-3">
                                <div className="min-w-0">
                                    <p className="text-sm font-semibold">
                                        {candidate.customer}
                                    </p>
                                    <p className="text-muted-foreground mt-0.5 flex items-start gap-1.5 text-xs">
                                        <MapPin className="mt-0.5 size-3.5 shrink-0" />
                                        {candidate.address}
                                    </p>
                                    {candidate.phone ? (
                                        <p className="text-muted-foreground mt-0.5 flex items-center gap-1.5 text-xs">
                                            <Phone className="size-3.5" />
                                            {candidate.phone}
                                        </p>
                                    ) : null}
                                </div>

                                <Button
                                    size="sm"
                                    variant="outline"
                                    onClick={() => post(candidate.id)}
                                    disabled={busy !== null}
                                >
                                    {busy === candidate.id ? (
                                        'Opening…'
                                    ) : (
                                        <>
                                            <Check />
                                            This one
                                        </>
                                    )}
                                </Button>
                            </div>

                            <div className="mt-3 flex flex-wrap items-center gap-x-3 gap-y-1 border-t border-hairline pt-2.5 text-[11px]">
                                <span
                                    className={cn(
                                        'font-medium',
                                        candidate.score >= 60
                                            ? 'text-emerald-700 dark:text-emerald-400'
                                            : 'text-amber-700 dark:text-amber-400',
                                    )}
                                >
                                    {candidate.reason}
                                </span>
                                {candidate.job ? (
                                    <span className="text-muted-foreground">
                                        Last job {candidate.job.job_number}
                                        {candidate.job.title
                                            ? ` · ${candidate.job.title}`
                                            : ''}
                                    </span>
                                ) : (
                                    <span className="text-muted-foreground">
                                        No jobs recorded at this address
                                    </span>
                                )}
                            </div>
                        </div>
                    ))}
                </div>

                <div className="ring-hairline rounded-xl bg-card p-4 shadow-card ring-1">
                    <div className="flex items-start gap-2.5">
                        <ShieldQuestion className="text-muted-foreground mt-0.5 size-4 shrink-0" />
                        <div className="min-w-0">
                            <p className="text-sm font-medium">
                                None of these is the right place
                            </p>
                            <p className="text-muted-foreground mt-1 text-xs leading-relaxed">
                                Carry on anyway. The report opens for the address
                                you typed, and the office links it to the client
                                once they have the paperwork in front of them.
                            </p>

                            <Button
                                size="sm"
                                variant="outline"
                                className="mt-3"
                                onClick={() => post(null)}
                                disabled={busy !== null}
                            >
                                <SearchX />
                                {busy === 'none'
                                    ? 'Opening…'
                                    : 'Start the report without a client match'}
                            </Button>
                        </div>
                    </div>
                </div>

                <p className="text-muted-foreground text-center text-[11px] leading-relaxed">
                    Only the client record is being confirmed here. Nothing is
                    changed on their file: a correction to a name or an address is
                    the office's job, from the report.
                </p>
            </div>
        </>
    );
}
