import { Form, Head, Link, usePage } from '@inertiajs/react';
import { Building2, Car, Check, CheckCircle2, LogIn, MapPin, Search, Star, X } from 'lucide-react';
import { useState } from 'react';
import InputError from '@/components/input-error';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { cn } from '@/lib/utils';
import type { User as AuthUser } from '@/types/auth';

type FixedLocation = {
    id: number;
    name: string;
    address: string | null;
    city: string | null;
    state: string | null;
    zip: string | null;
};

function fmtLocationAddress(loc: FixedLocation): string | null {
    const parts = [loc.address, loc.city, loc.state, loc.zip].filter(Boolean);

    return parts.length > 0 ? parts.join(', ') : null;
}

type ServiceType = {
    slug: string;
    label: string;
    description: string | null;
};

type Props = {
    locations: FixedLocation[];
    activeServiceTypes: ServiceType[];
    defaultLocationId?: number | null;
    draft?: {
        service_type?: 'mobile' | 'fixed';
        service_zip?: string | null;
        location_id?: number | null;
    };
};

export default function Step1Location({
    locations,
    activeServiceTypes,
    defaultLocationId = null,
    draft,
}: Props) {
    const { auth } = usePage().props as { auth?: { user?: AuthUser } };
    const user = auth?.user ?? null;
    const loginUrl = `/login?redirect_to=${encodeURIComponent('/book/location')}`;

    const mobileType = activeServiceTypes.find((t) => t.slug === 'mobile_zone');
    const fixedType = activeServiceTypes.find((t) => t.slug === 'fixed');
    const mobileAvailable = mobileType !== undefined;
    const fixedAvailable = fixedType !== undefined;

    const preferredLocationId =
        draft?.location_id ??
        (defaultLocationId && locations.some((loc) => loc.id === defaultLocationId)
            ? defaultLocationId
            : null);

    const resolveDefaultType = (): 'mobile' | 'fixed' => {
        const draftType = draft?.service_type;

        if (draftType === 'mobile' && mobileAvailable) {
            return 'mobile';
        }

        if (draftType === 'fixed' && fixedAvailable) {
            return 'fixed';
        }

        if (preferredLocationId !== null && fixedAvailable) {
            return 'fixed';
        }

        if (mobileAvailable) {
            return 'mobile';
        }

        return 'fixed';
    };

    const [serviceType, setServiceType] = useState<'mobile' | 'fixed'>(resolveDefaultType);
    const [selectedLocation, setSelectedLocation] = useState<number | null>(preferredLocationId);
    const [search, setSearch] = useState('');

    const query = search.trim().toLowerCase();
    const filteredLocations = query
        ? locations.filter((loc) =>
              [loc.name, loc.address, loc.city, loc.state, loc.zip]
                  .filter(Boolean)
                  .join(' ')
                  .toLowerCase()
                  .includes(query),
          )
        : locations;

    const defaultLocation =
        defaultLocationId != null
            ? locations.find((loc) => loc.id === defaultLocationId) ?? null
            : null;

    const showDefaultLocationCard =
        user !== null &&
        defaultLocation !== null &&
        serviceType === 'fixed' &&
        selectedLocation === defaultLocation.id;

    return (
        <>
            <Head title="Book: location" />

            <Form action="/book/location" method="post">
                {({ errors, processing }) => (
                    <div className="flex flex-col gap-8">

                        {/* Heading */}
                        <div>
                            <h2 className="text-2xl font-bold tracking-tight">
                                How would you like your car washed?
                            </h2>
                            <p className="mt-2 text-base text-muted-foreground">
                                We come to you, or you drop off at one of our wash bays — your choice.
                            </p>
                        </div>

                        {/* Returning customer + service type cards */}
                        <div className="flex flex-col gap-4">
                            {user ? (
                                <div className="flex items-center gap-4 rounded-2xl border-2 border-border bg-muted/20 p-5">
                                    <div className="flex size-12 shrink-0 items-center justify-center rounded-xl bg-primary/15 text-primary">
                                        <CheckCircle2 className="size-6" />
                                    </div>
                                    <div className="min-w-0 flex-1">
                                        <p className="text-base font-bold">Welcome back, {user.name}</p>
                                        <p className="mt-0.5 text-sm text-muted-foreground">
                                            You're signed in — your saved details will carry through the booking.
                                        </p>
                                    </div>
                                </div>
                            ) : (
                                <Link
                                    href={loginUrl}
                                    className="flex items-center gap-4 rounded-2xl border-2 border-border p-5 transition-all hover:border-primary/40 hover:bg-accent/40"
                                >
                                    <div className="flex size-12 shrink-0 items-center justify-center rounded-xl bg-primary/15 text-primary">
                                        <LogIn className="size-6" />
                                    </div>
                                    <div className="min-w-0 flex-1">
                                        <p className="text-base font-bold">Returning customer</p>
                                        <p className="mt-0.5 text-sm text-muted-foreground">
                                            Please sign in here
                                        </p>
                                    </div>
                                </Link>
                            )}

                            {showDefaultLocationCard && defaultLocation && (
                                <div>
                                    <p className="mb-3 text-sm font-medium">Your default wash bay</p>
                                    <div
                                        className="flex w-full items-center gap-4 rounded-xl border-2 border-primary bg-primary/5 px-4 py-3 shadow-sm"
                                        role="status"
                                        aria-live="polite"
                                    >
                                        <span className="flex size-4 shrink-0 items-center justify-center rounded-full border-2 border-primary">
                                            <span className="size-2 rounded-full bg-primary" />
                                        </span>
                                        <div className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-primary/10">
                                            <Building2 className="size-4 text-primary" />
                                        </div>
                                        <div className="min-w-0 flex-1">
                                            <p className="truncate text-sm font-semibold text-primary">
                                                {defaultLocation.name}
                                            </p>
                                            {fmtLocationAddress(defaultLocation) && (
                                                <p className="truncate text-xs text-muted-foreground">
                                                    {fmtLocationAddress(defaultLocation)}
                                                </p>
                                            )}
                                        </div>
                                        <span className="flex shrink-0 items-center gap-1 rounded-full bg-primary/10 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-primary">
                                            <Star className="size-2.5 fill-primary" />
                                            Default
                                        </span>
                                    </div>
                                </div>
                            )}

                            {/* Mobile */}
                            {mobileAvailable && (
                                <label
                                    className={cn(
                                        'relative flex cursor-pointer flex-col gap-5 rounded-2xl border-2 p-5 transition-all',
                                        serviceType === 'mobile'
                                            ? 'border-primary bg-primary/5 shadow-sm ring-2 ring-primary/10'
                                            : 'border-border hover:border-primary/40 hover:bg-accent/40',
                                    )}
                                >
                                    <input
                                        type="radio"
                                        name="service_type"
                                        value="mobile"
                                        checked={serviceType === 'mobile'}
                                        onChange={() => {
                                            setServiceType('mobile');
                                            setSearch('');
                                        }}
                                        className="sr-only"
                                    />

                                    <div className="flex items-start gap-4">
                                        <div
                                            className={cn(
                                                'flex size-12 shrink-0 items-center justify-center rounded-xl transition-colors',
                                                serviceType === 'mobile'
                                                    ? 'bg-primary/15 text-primary'
                                                    : 'bg-muted text-muted-foreground',
                                            )}
                                        >
                                            <Car className="size-6" />
                                        </div>

                                        <div className="min-w-0 flex-1">
                                            <p className="text-base font-bold">
                                                {mobileType?.label ?? 'Mobile Service'}
                                            </p>
                                            <p className="mt-0.5 text-sm leading-relaxed text-muted-foreground">
                                                {mobileType?.description ??
                                                    'We come to your home, office, or anywhere that works for you.'}
                                            </p>
                                        </div>

                                        {serviceType === 'mobile' && (
                                            <div className="flex size-6 shrink-0 items-center justify-center rounded-full bg-primary">
                                                <Check
                                                    className="size-3.5 text-primary-foreground"
                                                    strokeWidth={3}
                                                />
                                            </div>
                                        )}
                                    </div>

                                    {serviceType === 'mobile' && (
                                        <div className="border-t border-primary/10 pt-5">
                                            <div className="mb-4 flex items-center gap-3">
                                                <div className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-primary/10">
                                                    <MapPin className="size-4 text-primary" />
                                                </div>
                                                <div>
                                                    <p className="text-sm font-semibold">What's your zip code?</p>
                                                    <p className="text-xs text-muted-foreground">
                                                        We'll confirm mobile service is available in your area.
                                                    </p>
                                                </div>
                                            </div>

                                            <div className="relative">
                                                <MapPin className="absolute left-3.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
                                                <Input
                                                    id="service_zip"
                                                    name="service_zip"
                                                    placeholder="Enter your zip code — e.g. 75001"
                                                    className="h-11 bg-background pl-10 text-base"
                                                    maxLength={5}
                                                    defaultValue={draft?.service_zip ?? ''}
                                                    inputMode="numeric"
                                                />
                                            </div>

                                            {errors.service_zip && (
                                                <p className="mt-2 text-sm text-destructive">
                                                    {errors.service_zip}
                                                </p>
                                            )}
                                        </div>
                                    )}
                                </label>
                            )}

                            {/* Site / fixed location */}
                            {fixedAvailable && (
                                <label
                                    className={cn(
                                        'relative flex cursor-pointer flex-col gap-5 rounded-2xl border-2 p-5 transition-all',
                                        serviceType === 'fixed'
                                            ? 'border-primary bg-primary/5 shadow-sm ring-2 ring-primary/10'
                                            : 'border-border hover:border-primary/40 hover:bg-accent/40',
                                    )}
                                >
                                    <input
                                        type="radio"
                                        name="service_type"
                                        value="fixed"
                                        checked={serviceType === 'fixed'}
                                        onChange={() => setServiceType('fixed')}
                                        className="sr-only"
                                    />

                                    <div className="flex items-start gap-4">
                                        <div
                                            className={cn(
                                                'flex size-12 shrink-0 items-center justify-center rounded-xl transition-colors',
                                                serviceType === 'fixed'
                                                    ? 'bg-primary/15 text-primary'
                                                    : 'bg-muted text-muted-foreground',
                                            )}
                                        >
                                            <Building2 className="size-6" />
                                        </div>

                                        <div className="min-w-0 flex-1">
                                            <p className="text-base font-bold">
                                                {fixedType?.label ?? 'Site'}
                                            </p>
                                            <p className="mt-0.5 text-sm leading-relaxed text-muted-foreground">
                                                {fixedType?.description ??
                                                    'Drop off at one of our professional wash bays and pick it up spotless.'}
                                            </p>
                                        </div>

                                        {serviceType === 'fixed' && (
                                            <div className="flex size-6 shrink-0 items-center justify-center rounded-full bg-primary">
                                                <Check
                                                    className="size-3.5 text-primary-foreground"
                                                    strokeWidth={3}
                                                />
                                            </div>
                                        )}
                                    </div>

                                    {serviceType === 'fixed' && (
                                        <div className="flex flex-col gap-4 border-t border-primary/10 pt-5">
                                            <input
                                                type="hidden"
                                                name="location_id"
                                                value={selectedLocation ?? ''}
                                            />

                                            <div className="flex items-center justify-between">
                                                <p className="text-sm font-semibold">
                                                    Select a wash bay location
                                                </p>
                                                {query && (
                                                    <p className="text-xs text-muted-foreground">
                                                        {filteredLocations.length} of {locations.length}{' '}
                                                        locations
                                                    </p>
                                                )}
                                            </div>

                                            {locations.length > 4 && (
                                                <div className="relative">
                                                    <Search className="absolute left-3.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
                                                    <Input
                                                        type="text"
                                                        placeholder="Search by name, city, or zip…"
                                                        value={search}
                                                        onChange={(e) => setSearch(e.target.value)}
                                                        className="h-11 bg-background pl-10 pr-10 text-base"
                                                        autoComplete="off"
                                                    />
                                                    {search && (
                                                        <button
                                                            type="button"
                                                            onClick={() => setSearch('')}
                                                            className="absolute right-3.5 top-1/2 -translate-y-1/2 text-muted-foreground transition-colors hover:text-foreground"
                                                            aria-label="Clear search"
                                                        >
                                                            <X className="size-4" />
                                                        </button>
                                                    )}
                                                </div>
                                            )}

                                            <div className="flex max-h-72 flex-col gap-2.5 overflow-y-auto pr-0.5">
                                                {locations.length === 0 ? (
                                                    <div className="rounded-xl border border-dashed p-6 text-center">
                                                        <Building2 className="mx-auto mb-2 size-7 text-muted-foreground/40" />
                                                        <p className="text-sm font-medium">
                                                            No locations available yet
                                                        </p>
                                                        <p className="mt-1 text-xs text-muted-foreground">
                                                            Try our mobile service instead.
                                                        </p>
                                                    </div>
                                                ) : filteredLocations.length === 0 ? (
                                                    <div className="rounded-xl border border-dashed p-6 text-center">
                                                        <p className="text-sm font-medium">
                                                            No locations match "{search}"
                                                        </p>
                                                        <button
                                                            type="button"
                                                            onClick={() => setSearch('')}
                                                            className="mt-2 text-sm text-primary hover:underline"
                                                        >
                                                            Clear search
                                                        </button>
                                                    </div>
                                                ) : (
                                                    filteredLocations.map((location) => (
                                                        <div
                                                            key={location.id}
                                                            role="button"
                                                            tabIndex={0}
                                                            onClick={(e) => {
                                                                e.preventDefault();
                                                                e.stopPropagation();
                                                                setSelectedLocation(location.id);
                                                            }}
                                                            onKeyDown={(e) => {
                                                                if (e.key === 'Enter' || e.key === ' ') {
                                                                    e.preventDefault();
                                                                    e.stopPropagation();
                                                                    setSelectedLocation(location.id);
                                                                }
                                                            }}
                                                            className={cn(
                                                                'relative flex cursor-pointer items-start gap-3 rounded-xl border-2 p-4 transition-all',
                                                                selectedLocation === location.id
                                                                    ? 'border-primary bg-background shadow-sm'
                                                                    : 'border-border bg-background hover:border-primary/40',
                                                            )}
                                                        >
                                                            <div
                                                                className={cn(
                                                                    'flex size-9 shrink-0 items-center justify-center rounded-lg transition-colors',
                                                                    selectedLocation === location.id
                                                                        ? 'bg-primary/15 text-primary'
                                                                        : 'bg-muted text-muted-foreground',
                                                                )}
                                                            >
                                                                <Building2 className="size-4" />
                                                            </div>

                                                            <div className="min-w-0 flex-1">
                                                                <p className="text-sm font-semibold">
                                                                    {location.name}
                                                                </p>
                                                                {location.address && (
                                                                    <p className="mt-0.5 text-xs text-muted-foreground">
                                                                        {location.address}
                                                                        {location.city && `, ${location.city}`}
                                                                        {location.state && `, ${location.state}`}
                                                                        {location.zip && ` ${location.zip}`}
                                                                    </p>
                                                                )}
                                                            </div>

                                                            {selectedLocation === location.id && (
                                                                <div className="flex size-5 shrink-0 items-center justify-center rounded-full bg-primary">
                                                                    <Check
                                                                        className="size-3 text-primary-foreground"
                                                                        strokeWidth={3}
                                                                    />
                                                                </div>
                                                            )}
                                                        </div>
                                                    ))
                                                )}
                                            </div>

                                            <InputError message={errors.location_id} />
                                        </div>
                                    )}
                                </label>
                            )}
                        </div>

                        <Button
                            type="submit"
                            disabled={
                                processing ||
                                (serviceType === 'fixed' && selectedLocation === null)
                            }
                            size="lg"
                            className="h-14 w-full text-base font-semibold"
                        >
                            Continue to vehicle
                        </Button>
                    </div>
                )}
            </Form>
        </>
    );
}
