import { Head, useForm, usePage } from '@inertiajs/react';
import {
    ArrowRight,
    ClipboardList,
    MapPin,
    ShieldCheck,
    TriangleAlert,
    UserRound,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { NativeSelect } from '@/components/crm/native-select';
import { cn } from '@/lib/utils';
import type { InspectionIntakeFormProps } from '@/types';

/**
 * The first screen of the standing warranty link: who and where.
 *
 * This is the door a crew opens on site, without a job number and without
 * waiting for the office. Three things are asked before anything else, because
 * they are what the report is filed against: whose installation it is, where it
 * is, and what the crew is there for. The next screen shows what the CRM already
 * holds for that address, and the crew says whether it is the same place.
 *
 * Written for a phone in a driveway: one column, large targets, and the address
 * split into the parts the match actually uses.
 */
export default function StartInspection({
    purposes,
    states,
    intake,
    urls,
}: InspectionIntakeFormProps) {
    const { errors } = usePage<{ errors: Record<string, string> }>().props;

    const { data, setData, post, processing } = useForm({
        customer_name: intake?.customer_name ?? '',
        customer_phone: intake?.customer_phone ?? '',
        site_address: intake?.site_address ?? '',
        site_suburb: intake?.site_suburb ?? '',
        site_state: intake?.site_state ?? 'QLD',
        site_postcode: intake?.site_postcode ?? '',
        purpose: intake?.purpose ?? purposes[0]?.value ?? 'warranty',
        inspector_name: intake?.inspector_name ?? '',
        inspector_business: intake?.inspector_business ?? '',
    });

    const fieldError = (field: string) => errors[field];

    return (
        <>
            <Head title="Start a warranty or service report" />

            <div className="mx-auto grid max-w-3xl gap-5">
                <div>
                    <p className="text-muted-foreground flex items-center gap-1.5 text-xs font-medium tracking-wide uppercase">
                        <ShieldCheck className="text-solar size-3.5" />
                        Standing warranty and service link
                    </p>
                    <h1 className="mt-1.5 text-2xl font-semibold tracking-tight sm:text-3xl">
                        Start a report on site
                    </h1>
                    <p className="text-muted-foreground mt-2 max-w-2xl text-sm leading-relaxed">
                        No job number needed and nothing to wait for. Confirm who
                        the system belongs to and where it is, then fill in the
                        same inspection report the office sends out — array,
                        inverter, battery, earthing, labels and photos.
                    </p>
                </div>

                <ol className="text-muted-foreground grid gap-2 text-xs sm:grid-cols-3">
                    {[
                        ['Who and where', 'The name on the bill and the address.'],
                        ['Confirm the client', 'Pick the match, or say none of them.'],
                        ['The report', 'Checklist, readings, photos, signature.'],
                    ].map(([title, hint], index) => (
                        <li
                            key={title}
                            className={cn(
                                'flex items-start gap-2 rounded-lg px-3 py-2.5 ring-1',
                                index === 0
                                    ? 'bg-solar-soft text-solar-ink ring-solar/30'
                                    : 'ring-hairline bg-card',
                            )}
                        >
                            <span className="crm-num mt-0.5 text-[11px] font-semibold">
                                {index + 1}
                            </span>
                            <span>
                                <span className="block font-medium text-foreground">
                                    {title}
                                </span>
                                <span className="block leading-snug">{hint}</span>
                            </span>
                        </li>
                    ))}
                </ol>

                <form
                    onSubmit={(event) => {
                        event.preventDefault();
                        post(urls.start);
                    }}
                    className="grid gap-5"
                >
                    <section className="bg-card shadow-card rounded-xl p-4 ring-1 ring-hairline sm:p-5">
                        <div className="flex items-center gap-2">
                            <UserRound className="text-muted-foreground size-4" />
                            <h2 className="text-sm font-semibold">
                                Whose installation is it?
                            </h2>
                        </div>

                        <div className="mt-3.5 grid gap-3.5 sm:grid-cols-2">
                            <label className="grid gap-1.5 sm:col-span-2">
                                <span className="text-xs font-medium">
                                    Customer name
                                </span>
                                <Input
                                    value={data.customer_name}
                                    onChange={(event) =>
                                        setData('customer_name', event.target.value)
                                    }
                                    placeholder="The name on the bill, or the business"
                                    autoComplete="off"
                                    aria-invalid={Boolean(fieldError('customer_name'))}
                                />
                                {fieldError('customer_name') ? (
                                    <span className="text-xs text-red-600 dark:text-red-400">
                                        {fieldError('customer_name')}
                                    </span>
                                ) : null}
                            </label>

                            <label className="grid gap-1.5">
                                <span className="text-xs font-medium">
                                    Phone{' '}
                                    <span className="text-muted-foreground font-normal">
                                        (optional)
                                    </span>
                                </span>
                                <Input
                                    value={data.customer_phone}
                                    onChange={(event) =>
                                        setData('customer_phone', event.target.value)
                                    }
                                    placeholder="0455 835 300"
                                    inputMode="tel"
                                />
                                <span className="text-muted-foreground text-[11px]">
                                    A number on the account is the quickest way to
                                    find the client.
                                </span>
                            </label>

                            <label className="grid gap-1.5">
                                <span className="text-xs font-medium">
                                    What are you there for?
                                </span>
                                <NativeSelect
                                    value={data.purpose}
                                    onChange={(event) =>
                                        setData('purpose', event.target.value)
                                    }
                                >
                                    {purposes.map((purpose) => (
                                        <option key={purpose.value} value={purpose.value}>
                                            {purpose.label}
                                        </option>
                                    ))}
                                </NativeSelect>
                                <span className="text-muted-foreground text-[11px] leading-snug">
                                    {purposes.find((p) => p.value === data.purpose)
                                        ?.description ?? ''}
                                </span>
                            </label>
                        </div>
                    </section>

                    <section className="bg-card shadow-card rounded-xl p-4 ring-1 ring-hairline sm:p-5">
                        <div className="flex items-center gap-2">
                            <MapPin className="text-muted-foreground size-4" />
                            <h2 className="text-sm font-semibold">
                                Where is the system?
                            </h2>
                        </div>

                        <div className="mt-3.5 grid gap-3.5 sm:grid-cols-6">
                            <label className="grid gap-1.5 sm:col-span-6">
                                <span className="text-xs font-medium">
                                    Street address
                                </span>
                                <Input
                                    value={data.site_address}
                                    onChange={(event) =>
                                        setData('site_address', event.target.value)
                                    }
                                    placeholder="12 Smith Street"
                                    autoComplete="off"
                                    aria-invalid={Boolean(fieldError('site_address'))}
                                />
                                {fieldError('site_address') ? (
                                    <span className="text-xs text-red-600 dark:text-red-400">
                                        {fieldError('site_address')}
                                    </span>
                                ) : null}
                            </label>

                            <label className="grid gap-1.5 sm:col-span-3">
                                <span className="text-xs font-medium">Suburb</span>
                                <Input
                                    value={data.site_suburb}
                                    onChange={(event) =>
                                        setData('site_suburb', event.target.value)
                                    }
                                    autoComplete="off"
                                    aria-invalid={Boolean(fieldError('site_suburb'))}
                                />
                                {fieldError('site_suburb') ? (
                                    <span className="text-xs text-red-600 dark:text-red-400">
                                        {fieldError('site_suburb')}
                                    </span>
                                ) : null}
                            </label>

                            <label className="grid gap-1.5 sm:col-span-2">
                                <span className="text-xs font-medium">State</span>
                                <NativeSelect
                                    value={data.site_state}
                                    onChange={(event) =>
                                        setData('site_state', event.target.value)
                                    }
                                >
                                    {states.map((state) => (
                                        <option key={state.value} value={state.value}>
                                            {state.value}
                                        </option>
                                    ))}
                                </NativeSelect>
                            </label>

                            <label className="grid gap-1.5 sm:col-span-1">
                                <span className="text-xs font-medium">Postcode</span>
                                <Input
                                    value={data.site_postcode}
                                    onChange={(event) =>
                                        setData(
                                            'site_postcode',
                                            event.target.value.replace(/\D/g, '').slice(0, 4),
                                        )
                                    }
                                    placeholder="4551"
                                    inputMode="numeric"
                                    aria-invalid={Boolean(fieldError('site_postcode'))}
                                />
                            </label>
                        </div>

                        {fieldError('site_postcode') ? (
                            <p className="mt-1.5 text-xs text-red-600 dark:text-red-400">
                                {fieldError('site_postcode')}
                            </p>
                        ) : null}
                    </section>

                    <section className="bg-card shadow-card rounded-xl p-4 ring-1 ring-hairline sm:p-5">
                        <div className="flex items-center gap-2">
                            <ClipboardList className="text-muted-foreground size-4" />
                            <h2 className="text-sm font-semibold">Who is inspecting?</h2>
                        </div>

                        <div className="mt-3.5 grid gap-3.5 sm:grid-cols-2">
                            <label className="grid gap-1.5">
                                <span className="text-xs font-medium">Your name</span>
                                <Input
                                    value={data.inspector_name}
                                    onChange={(event) =>
                                        setData('inspector_name', event.target.value)
                                    }
                                    placeholder="Dana Whitfield"
                                    autoComplete="off"
                                    aria-invalid={Boolean(fieldError('inspector_name'))}
                                />
                                {fieldError('inspector_name') ? (
                                    <span className="text-xs text-red-600 dark:text-red-400">
                                        {fieldError('inspector_name')}
                                    </span>
                                ) : null}
                            </label>

                            <label className="grid gap-1.5">
                                <span className="text-xs font-medium">
                                    Business{' '}
                                    <span className="text-muted-foreground font-normal">
                                        (optional)
                                    </span>
                                </span>
                                <Input
                                    value={data.inspector_business}
                                    onChange={(event) =>
                                        setData('inspector_business', event.target.value)
                                    }
                                    placeholder="Northline Electrical"
                                    autoComplete="off"
                                />
                                <span className="text-muted-foreground text-[11px]">
                                    If your business is on our installer register, this
                                    links the report to it.
                                </span>
                            </label>
                        </div>
                    </section>

                    <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                        <p className="text-muted-foreground flex items-start gap-1.5 text-[11px] leading-relaxed">
                            <TriangleAlert className="mt-0.5 size-3.5 shrink-0" />
                            If anything is unsafe, isolate it and ring the office
                            before you carry on.
                        </p>

                        <Button type="submit" disabled={processing} className="sm:min-w-44">
                            {processing ? 'Checking…' : 'Continue'}
                            <ArrowRight />
                        </Button>
                    </div>
                </form>
            </div>
        </>
    );
}
