import { Head, Link, useForm, usePage } from '@inertiajs/react';
import { useEffect } from 'react';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import InputError from '@/components/input-error';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import AppLayout from '@/layouts/app-layout';
import type { BreadcrumbItem } from '@/types';
import { ArrowLeft, Building2, MapPin, Map as MapIcon, Plus, Trash2 } from 'lucide-react';
import SettingsDeliveryStepper from '@/components/settings-delivery-stepper';
import { geoCountries, getCitiesByCountry } from '@/data/geo';
import { useToast } from '@/components/ui/toast-provider';

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Paramètres', href: '/settings' },
    { title: 'Localisation', href: '/settings/localisation' },
];

type LocationItem = {
    country: string;
    city: string;
    address: string;
};

type LocalisationProps = {
    locations: LocationItem[];
    defaultCountry: string;
    defaultCity: string | null;
    tableMissing?: boolean;
};

export default function LocalisationSettings({
    locations,
    defaultCountry,
    defaultCity,
    tableMissing,
}: LocalisationProps) {
    const { showToast } = useToast();
    const { flash } = usePage().props as {
        flash?: { success?: string; error?: string };
    };
    const {
        data,
        setData,
        post,
        processing,
        errors,
    } = useForm({
        locations: locations.length
            ? locations
            : [
                  {
                      country: defaultCountry,
                      city: defaultCity ?? '',
                      address: '',
                  },
              ],
    });

    const steps = [
        { label: 'Générales', icon: Building2, href: '/settings/general' },
        { label: 'Localisation', icon: MapPin, href: '/settings/localisation' },
        {
            label: 'Zones de livraison',
            icon: MapIcon,
            href: '/settings/zones-livraison',
        },
    ];

    const updateLocation = (
        index: number,
        field: keyof LocationItem,
        value: string,
    ) => {
        const updated = [...data.locations];
        updated[index] = { ...updated[index], [field]: value };
        if (field === 'country') {
            const firstCity = getCitiesByCountry(value)[0]?.name ?? '';
            updated[index].city = firstCity;
        }
        setData('locations', updated);
    };

    const addLocation = () => {
        setData('locations', [
            ...data.locations,
            { country: '', city: '', address: '' },
        ]);
    };

    const removeLocation = (index: number) => {
        const updated = data.locations.filter((_, i) => i !== index);
        setData('locations', updated.length ? updated : [{ country: '', city: '', address: '' }]);
    };

    useEffect(() => {
        if (flash?.success) {
            showToast({ type: 'success', message: flash.success });
        }
        if (flash?.error) {
            showToast({ type: 'error', message: flash.error });
        }
    }, [flash?.success, flash?.error, showToast]);

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Localisation" />

            <div className="space-y-8 rounded-3xl bg-gradient-to-b from-blue-50 via-white to-emerald-50 p-4 md:p-6 dark:from-blue-950/40 dark:via-neutral-950 dark:to-emerald-950/40">
                <div className="flex items-center gap-3">
                    <Button variant="ghost" size="icon" asChild>
                        <Link href="/settings/general">
                            <ArrowLeft className="h-5 w-5" />
                        </Link>
                    </Button>
                    <h1 className="text-center text-lg font-semibold md:text-xl">
                        Votre entreprise de livraison
                    </h1>
                </div>

                <SettingsDeliveryStepper steps={steps} />

                {tableMissing && (
                    <Alert variant="destructive">
                        <AlertTitle>Erreur</AlertTitle>
                        <AlertDescription>
                            La table de localisation est introuvable. Lancez les migrations
                            avant d’enregistrer.
                        </AlertDescription>
                    </Alert>
                )}

                <form
                    className="space-y-6 rounded-2xl border border-blue-100/80 bg-white/90 p-6 shadow-lg backdrop-blur dark:border-blue-900/50 dark:bg-neutral-900/80"
                    onSubmit={(event) => {
                        event.preventDefault();
                        if (tableMissing) {
                            showToast({
                                type: 'error',
                                message:
                                    'Impossible d’enregistrer sans les migrations.',
                            });
                            return;
                        }
                        post('/settings/localisation');
                    }}
                >
                    <div className="space-y-2">
                        <h2 className="text-base font-semibold text-blue-700 dark:text-blue-200">
                            Localisation
                        </h2>
                        <p className="text-sm text-muted-foreground">
                            Où êtes-vous situé ? Ajoutez une ou plusieurs localisations.
                        </p>
                    </div>

                    <div className="space-y-6">
                        {data.locations.map((location, index) => (
                            <div
                                key={`location-${index}`}
                                className="rounded-xl border border-blue-100/80 bg-white/80 p-4 shadow-sm dark:border-blue-900/50 dark:bg-neutral-950/40"
                            >
                                <datalist id={`location-city-list-${index}`}>
                                    {getCitiesByCountry(location.country).map(
                                        (city) => (
                                            <option key={city.name} value={city.name} />
                                        ),
                                    )}
                                </datalist>
                                <div className="flex items-center justify-between">
                                    <h3 className="text-sm font-semibold">
                                        Localisation {index + 1}
                                    </h3>
                                    <Button
                                        type="button"
                                        variant="ghost"
                                        size="icon"
                                        onClick={() => removeLocation(index)}
                                    >
                                        <Trash2 className="h-4 w-4 text-destructive" />
                                    </Button>
                                </div>

                                <div className="mt-4 grid gap-4">
                                    <div className="grid gap-2">
                                        <Label>Pays</Label>
                                        <select
                                            className="flex h-9 w-full rounded-md border border-input bg-background px-3 text-sm shadow-xs focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
                                            value={location.country}
                                            onChange={(event) =>
                                                updateLocation(
                                                    index,
                                                    'country',
                                                    event.target.value,
                                                )
                                            }
                                        >
                                            {geoCountries.map((country) => (
                                                <option
                                                    key={country.code}
                                                    value={country.code}
                                                >
                                                    {country.name}
                                                </option>
                                            ))}
                                        </select>
                                        <InputError
                                            message={
                                                errors[`locations.${index}.country`]
                                            }
                                        />
                                    </div>

                                    <div className="grid gap-2">
                                        <Label>Ville</Label>
                                        <Input
                                            placeholder="Ville"
                                            list={`location-city-list-${index}`}
                                            value={location.city}
                                            onChange={(event) =>
                                                updateLocation(
                                                    index,
                                                    'city',
                                                    event.target.value,
                                                )
                                            }
                                        />
                                        <InputError
                                            message={
                                                errors[`locations.${index}.city`]
                                            }
                                        />
                                    </div>

                                    <div className="grid gap-2">
                                        <Label>Adresse exacte</Label>
                                        <Input
                                            placeholder="Adresse"
                                            value={location.address}
                                            onChange={(event) =>
                                                updateLocation(
                                                    index,
                                                    'address',
                                                    event.target.value,
                                                )
                                            }
                                        />
                                        <InputError
                                            message={
                                                errors[`locations.${index}.address`]
                                            }
                                        />
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>

                    <div className="flex justify-center">
                        <Button
                            type="button"
                            variant="outline"
                            className="border-emerald-200 text-emerald-700 hover:bg-emerald-50 dark:border-emerald-900/60 dark:text-emerald-200 dark:hover:bg-emerald-950/40"
                            onClick={addLocation}
                        >
                            <Plus className="mr-2 h-4 w-4" />
                            Ajouter une localisation
                        </Button>
                    </div>

                    <div className="flex justify-between">
                        <Button
                            type="button"
                            variant="outline"
                            className="border-emerald-200 text-emerald-700 hover:bg-emerald-50 dark:border-emerald-900/60 dark:text-emerald-200 dark:hover:bg-emerald-950/40"
                            asChild
                        >
                            <Link href="/settings/general">Précédent</Link>
                        </Button>
                        <Button type="submit" disabled={processing || tableMissing}>
                            Enregistrer & Suivant
                        </Button>
                    </div>
                </form>
            </div>
        </AppLayout>
    );
}
