import { Form, Head, Link, usePage } from '@inertiajs/react';
import { CheckCircle2, LogIn, Mail, MapPin, MessageSquare, Phone, User } from 'lucide-react';
import { useState } from 'react';
import { FormField } from '@/components/form-field';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Separator } from '@/components/ui/separator';
import { Textarea } from '@/components/ui/textarea';
import { formatUSPhone } from '@/lib/utils';
import type { User as AuthUser } from '@/types/auth';

function IconInput({
    icon: Icon,
    ...props
}: React.InputHTMLAttributes<HTMLInputElement> & { icon: React.ComponentType<{ className?: string }> }) {
    return (
        <div className="relative">
            <Icon className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
            <Input {...props} className="pl-9" />
        </div>
    );
}

type Props = {
    draft?: {
        name?: string;
        email?: string;
        phone?: string;
        office_suite?: string;
        cell?: string;
        service_type?: 'mobile' | 'fixed';
        service_address?: string;
        service_city?: string;
        service_state?: string;
        service_zip?: string;
        notes?: string;
        location?: {
            name: string;
            address: string | null;
            city: string | null;
            state: string | null;
            zip: string | null;
        } | null;
    };
};

export default function Step6CustomerInfo({ draft }: Props) {
    const { auth } = usePage().props as { auth?: { user?: AuthUser } };
    const user = auth?.user ?? null;

    const userPhone = (user?.phone as string | undefined) ?? '';
    const userOfficeSuite = (user?.office_suite as string | undefined) ?? '';
    const userCell = (user?.cell as string | undefined) ?? '';

    const [values, setValues] = useState({
        name: draft?.name || user?.name || '',
        email: draft?.email || user?.email || '',
        phone: draft?.phone || userPhone,
        office_suite: draft?.office_suite || userOfficeSuite,
        cell: draft?.cell || userCell,
        service_address: draft?.service_address || '',
        service_city: draft?.service_city || '',
        service_state: draft?.service_state || '',
        service_zip: draft?.service_zip || '',
        notes: draft?.notes || '',
    });

    const set =
        (key: keyof typeof values) =>
        (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) =>
            setValues((v) => ({ ...v, [key]: e.target.value }));

    const loginUrl = `/login?redirect_to=${encodeURIComponent('/book/customer-info')}`;

    return (
        <>
            <Head title="Book: your info" />

            <Form action="/book/customer-info" method="post">
                {({ errors, processing }) => (
                    <div className="flex flex-col gap-6">
                        <div>
                            <h2 className="text-xl font-semibold tracking-tight">Your contact details</h2>
                            <p className="mt-1 text-sm text-muted-foreground">
                                We'll use this to confirm your booking and reach you if needed.
                            </p>
                        </div>

                        {/* Auth banner */}
                        {user ? (
                            <div className="flex items-center gap-3 rounded-2xl border border-primary/25 bg-primary/5 px-4 py-3.5">
                                <div className="flex size-9 shrink-0 items-center justify-center rounded-full bg-primary/15">
                                    <CheckCircle2 className="size-4 text-primary" />
                                </div>
                                <div className="min-w-0 flex-1">
                                    <p className="text-sm font-medium">Signed in as {user.name}</p>
                                    <p className="text-xs text-muted-foreground">
                                        Your details have been pre-filled — edit anything below.
                                    </p>
                                </div>
                            </div>
                        ) : (
                            <div className="flex items-center gap-3 rounded-2xl border bg-muted/40 px-4 py-3.5">
                                <div className="flex size-9 shrink-0 items-center justify-center rounded-full bg-muted">
                                    <LogIn className="size-4 text-muted-foreground" />
                                </div>
                                <div className="min-w-0 flex-1">
                                    <p className="text-sm font-medium">Returning customer?</p>
                                    <p className="text-xs text-muted-foreground">
                                        Sign in to pre-fill your contact details.
                                    </p>
                                </div>
                                <Link
                                    href={loginUrl}
                                    className="shrink-0 text-sm font-semibold text-primary underline-offset-4 hover:underline"
                                >
                                    Sign in
                                </Link>
                            </div>
                        )}

                        <Separator />

                        {/* Contact info */}
                        <div className="rounded-2xl border bg-muted/30 p-4">
                            <p className="mb-4 text-sm font-medium">Contact information</p>
                            <div className="flex flex-col gap-4">
                                <FormField label="Full name" htmlFor="name" error={errors.name}>
                                    <IconInput
                                        icon={User}
                                        id="name"
                                        name="name"
                                        placeholder="John Smith"
                                        autoComplete="name"
                                        value={values.name}
                                        onChange={set('name')}
                                    />
                                </FormField>

                                <FormField label="Email address" htmlFor="email" error={errors.email}>
                                    <IconInput
                                        icon={Mail}
                                        id="email"
                                        name="email"
                                        type="email"
                                        placeholder="john@example.com"
                                        autoComplete="email"
                                        value={values.email}
                                        onChange={set('email')}
                                    />
                                </FormField>

                                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                    <FormField label="Cell" htmlFor="cell" error={errors.cell}>
                                        <IconInput
                                            icon={Phone}
                                            id="cell"
                                            name="cell"
                                            type="tel"
                                            placeholder="(555) 000-0000"
                                            autoComplete="tel"
                                            value={values.cell}
                                            onChange={(e) =>
                                                setValues((v) => ({
                                                    ...v,
                                                    cell: formatUSPhone(e.target.value),
                                                }))
                                            }
                                        />
                                    </FormField>

                                    <FormField label="Phone number" htmlFor="phone" error={errors.phone}>
                                        <IconInput
                                            icon={Phone}
                                            id="phone"
                                            name="phone"
                                            type="tel"
                                            placeholder="(555) 000-0000"
                                            autoComplete="tel"
                                            value={values.phone}
                                            onChange={(e) =>
                                                setValues((v) => ({
                                                    ...v,
                                                    phone: formatUSPhone(e.target.value),
                                                }))
                                            }
                                        />
                                    </FormField>
                                </div>

                                <FormField
                                    label="Office / Suite Location"
                                    htmlFor="office_suite"
                                    error={errors.office_suite}
                                >
                                    <Input
                                        id="office_suite"
                                        name="office_suite"
                                        placeholder="Suite 200, Building B"
                                        autoComplete="address-line2"
                                        value={values.office_suite}
                                        onChange={set('office_suite')}
                                    />
                                </FormField>
                            </div>
                        </div>

                        {/* Service address — read-only for fixed, editable for mobile */}
                        {draft?.service_type === 'fixed' && draft?.location ? (
                            <div className="rounded-2xl border bg-muted/30 p-4">
                                <p className="mb-3 text-sm font-medium">Service location</p>
                                <div className="flex items-start gap-3 rounded-xl border bg-background px-4 py-3.5">
                                    <MapPin className="mt-0.5 size-4 shrink-0 text-primary" />
                                    <div>
                                        <p className="font-medium">{draft.location.name}</p>
                                        {draft.location.address && (
                                            <p className="mt-0.5 text-sm text-muted-foreground">
                                                {draft.location.address}
                                                {draft.location.city && `, ${draft.location.city}`}
                                                {draft.location.state && `, ${draft.location.state}`}
                                                {draft.location.zip && ` ${draft.location.zip}`}
                                            </p>
                                        )}
                                    </div>
                                </div>
                            </div>
                        ) : (
                            <div className="rounded-2xl border bg-muted/30 p-4">
                                <p className="mb-4 text-sm font-medium">Service address</p>
                                <div className="flex flex-col gap-4">
                                    <FormField
                                        label="Street address"
                                        htmlFor="service_address"
                                        error={errors.service_address}
                                    >
                                        <div className="relative">
                                            <MapPin className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
                                            <Input
                                                id="service_address"
                                                name="service_address"
                                                placeholder="123 Main St"
                                                className="pl-9"
                                                autoComplete="street-address"
                                                value={values.service_address}
                                                onChange={set('service_address')}
                                            />
                                        </div>
                                    </FormField>

                                    <div className="grid grid-cols-3 gap-3">
                                        <div className="col-span-2">
                                            <FormField
                                                label="City"
                                                htmlFor="service_city"
                                                error={errors.service_city}
                                            >
                                                <Input
                                                    id="service_city"
                                                    name="service_city"
                                                    placeholder="Dallas"
                                                    autoComplete="address-level2"
                                                    value={values.service_city}
                                                    onChange={set('service_city')}
                                                />
                                            </FormField>
                                        </div>
                                        <FormField
                                            label="State"
                                            htmlFor="service_state"
                                            error={errors.service_state}
                                        >
                                            <Input
                                                id="service_state"
                                                name="service_state"
                                                placeholder="TX"
                                                maxLength={2}
                                                className="uppercase"
                                                autoComplete="address-level1"
                                                value={values.service_state}
                                                onChange={set('service_state')}
                                            />
                                        </FormField>
                                    </div>

                                    <FormField
                                        label="Zip code"
                                        htmlFor="service_zip"
                                        error={errors.service_zip}
                                    >
                                        <Input
                                            id="service_zip"
                                            name="service_zip"
                                            placeholder="75001"
                                            maxLength={5}
                                            autoComplete="postal-code"
                                            value={values.service_zip}
                                            onChange={set('service_zip')}
                                        />
                                    </FormField>
                                </div>
                            </div>
                        )}

                        {/* Notes */}
                        <div className="rounded-2xl border bg-muted/30 p-4">
                            <FormField
                                label="Special notes (optional)"
                                htmlFor="notes"
                                error={errors.notes}
                            >
                                <div className="relative">
                                    <MessageSquare className="absolute left-3 top-3 size-4 text-muted-foreground" />
                                    <Textarea
                                        id="notes"
                                        name="notes"
                                        rows={3}
                                        placeholder="Gate code, specific areas to focus on, allergies to products…"
                                        className="resize-none pl-9"
                                        value={values.notes}
                                        onChange={set('notes')}
                                    />
                                </div>
                            </FormField>
                        </div>

                        <Button type="submit" disabled={processing} size="lg" className="w-full">
                            Continue to payment
                        </Button>
                    </div>
                )}
            </Form>
        </>
    );
}
