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 {
    getCitiesByCountry,
    getCommunesByCity,
    getNeighborhoodsByCommune,
} from '@/data/geo';
import { useToast } from '@/components/ui/toast-provider';

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Paramètres', href: '/settings' },
    { title: 'Zones de livraison', href: '/settings/zones-livraison' },
];

type ZoneItem = {
    zone_name: string;
    city: string;
    commune: string;
    neighborhoods: string;
    fee: string;
};

type ZonesProps = {
    zones: {
        zone_name: string;
        city: string;
        commune: string;
        neighborhoods: string | null;
        fee: number;
    }[];
    defaultCountry: string;
    defaultCity: string | null;
    tableMissing?: boolean;
};

export default function ZonesLivraisonSettings({
    zones,
    defaultCountry,
    defaultCity,
    tableMissing,
}: ZonesProps) {
    const { showToast } = useToast();
    const { flash } = usePage().props as {
        flash?: { success?: string; error?: string };
    };
    const {
        data,
        setData,
        post,
        processing,
        errors,
    } = useForm({
        zones: zones.length
            ? zones.map((zone) => ({
                  zone_name: zone.zone_name,
                  city: zone.city,
                  commune: zone.commune,
                  neighborhoods: zone.neighborhoods ?? '',
                  fee: zone.fee ? String(zone.fee) : '',
              }))
            : [
                  {
                      zone_name: '',
                      city: defaultCity ?? '',
                      commune: '',
                      neighborhoods: '',
                      fee: '',
                  },
              ],
    });

    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 updateZone = (
        index: number,
        field: keyof ZoneItem,
        value: string,
    ) => {
        const updated = [...data.zones];
        updated[index] = { ...updated[index], [field]: value };
        if (field === 'city') {
            const firstCommune =
                getCommunesByCity(defaultCountry, value)[0] ?? '';
            updated[index].commune = firstCommune;
        }
        setData('zones', updated);
    };

    const appendNeighborhood = (index: number, value: string) => {
        const current = data.zones[index]?.neighborhoods ?? '';
        if (current.includes(value)) {
            return;
        }
        const next = current.trim()
            ? `${current.trim()}, ${value}`
            : value;
        updateZone(index, 'neighborhoods', next);
    };

    const addZone = () => {
        const firstCity = getCitiesByCountry(defaultCountry)[0]?.name ?? '';
        const firstCommune =
            getCommunesByCity(defaultCountry, firstCity)[0] ?? '';
        setData('zones', [
            ...data.zones,
            {
                zone_name: '',
                city: firstCity,
                commune: firstCommune,
                neighborhoods: '',
                fee: '',
            },
        ]);
    };

    const removeZone = (index: number) => {
        const updated = data.zones.filter((_, i) => i !== index);
        setData(
            'zones',
            updated.length
                ? updated
                : [
                      {
                          zone_name: '',
                          city: '',
                          commune: '',
                          neighborhoods: '',
                          fee: '',
                      },
                  ],
        );
    };

    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="Zones de livraison" />

            <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/localisation">
                            <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 des zones 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/zones-livraison');
                    }}
                >
                    <div className="space-y-2">
                        <h2 className="text-base font-semibold text-blue-700 dark:text-blue-200">
                            Zones de livraison
                        </h2>
                        <p className="text-sm text-muted-foreground">
                            Ajoutez vos zones et frais de livraison.
                        </p>
                    </div>

                    <div className="space-y-6">
                        {data.zones.map((zone, index) => (
                            <div
                                key={`zone-${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={`zone-city-list-${index}`}>
                                    {getCitiesByCountry(defaultCountry).map(
                                        (city) => (
                                            <option key={city.name} value={city.name} />
                                        ),
                                    )}
                                </datalist>
                                <datalist id={`zone-commune-list-${index}`}>
                                    {getCommunesByCity(defaultCountry, zone.city).map(
                                        (commune) => (
                                            <option key={commune} value={commune} />
                                        ),
                                    )}
                                </datalist>
                                <div className="flex items-center justify-between">
                                    <h3 className="text-sm font-semibold">
                                        Zone de livraison {index + 1}
                                    </h3>
                                    <Button
                                        type="button"
                                        variant="ghost"
                                        size="icon"
                                        onClick={() => removeZone(index)}
                                    >
                                        <Trash2 className="h-4 w-4 text-destructive" />
                                    </Button>
                                </div>

                                <div className="mt-4 grid gap-4">
                                    <div className="grid gap-2">
                                        <Label>Zone</Label>
                                        <Input
                                            placeholder="Zone"
                                            value={zone.zone_name}
                                            onChange={(event) =>
                                                updateZone(
                                                    index,
                                                    'zone_name',
                                                    event.target.value,
                                                )
                                            }
                                        />
                                        <InputError
                                            message={
                                                errors[`zones.${index}.zone_name`]
                                            }
                                        />
                                    </div>

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

                                    <div className="grid gap-2">
                                        <Label>Commune</Label>
                                        <Input
                                            placeholder="Commune"
                                            list={`zone-commune-list-${index}`}
                                            value={zone.commune}
                                            onChange={(event) =>
                                                updateZone(
                                                    index,
                                                    'commune',
                                                    event.target.value,
                                                )
                                            }
                                        />
                                        <InputError
                                            message={
                                                errors[`zones.${index}.commune`]
                                            }
                                        />
                                    </div>

                                    <div className="grid gap-2">
                                        <Label>Quartiers livrés</Label>
                                        <textarea
                                            rows={3}
                                            className="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-xs placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
                                            placeholder="Listez les quartiers"
                                            value={zone.neighborhoods}
                                            onChange={(event) =>
                                                updateZone(
                                                    index,
                                                    'neighborhoods',
                                                    event.target.value,
                                                )
                                            }
                                        />
                                        <div className="flex flex-wrap gap-2">
                                            {getNeighborhoodsByCommune(
                                                defaultCountry,
                                                zone.city,
                                                zone.commune,
                                            ).map((neighborhood) => (
                                                <Button
                                                    key={neighborhood}
                                                    type="button"
                                                    variant="outline"
                                                    size="sm"
                                                    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={() =>
                                                        appendNeighborhood(
                                                            index,
                                                            neighborhood,
                                                        )
                                                    }
                                                >
                                                    {neighborhood}
                                                </Button>
                                            ))}
                                        </div>
                                        <InputError
                                            message={
                                                errors[
                                                    `zones.${index}.neighborhoods`
                                                ]
                                            }
                                        />
                                    </div>

                                    <div className="grid gap-2">
                                        <Label>Frais de livraison</Label>
                                        <Input
                                            placeholder="Montant"
                                            value={zone.fee}
                                            onChange={(event) =>
                                                updateZone(
                                                    index,
                                                    'fee',
                                                    event.target.value,
                                                )
                                            }
                                        />
                                        <InputError
                                            message={errors[`zones.${index}.fee`]}
                                        />
                                    </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={addZone}
                        >
                            <Plus className="mr-2 h-4 w-4" />
                            Ajouter une zone
                        </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/localisation">Précédent</Link>
                        </Button>
                        <Button type="submit" disabled={processing || tableMissing}>
                            Enregistrer
                        </Button>
                    </div>
                </form>
            </div>
        </AppLayout>
    );
}
