import { Head, Link, useForm, usePage } from '@inertiajs/react';
import { useEffect, useMemo } from 'react';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
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 {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import AppLayout from '@/layouts/app-layout';
import type { BreadcrumbItem } from '@/types';
import {
    ArrowLeft,
    Building2,
    MapPin,
    Map as MapIcon,
    Upload,
} from 'lucide-react';
import SettingsDeliveryStepper from '@/components/settings-delivery-stepper';
import { geoCountries, getCountryByCode } from '@/data/geo';
import { useToast } from '@/components/ui/toast-provider';

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Paramètres', href: '/settings' },
    { title: 'Général', href: '/settings/general' },
];

type GeneralSettingsProps = {
    settings: {
        name: string;
        description: string | null;
        phone_country: string | null;
        phone_code: string | null;
        phone_number: string | null;
        email: string | null;
        logo_path: string | null;
        logo_url: string | null;
    } | null;
    tableMissing?: boolean;
};

export default function GeneralSettings({
    settings,
    tableMissing,
}: GeneralSettingsProps) {
    const { showToast } = useToast();
    const { flash } = usePage().props as {
        flash?: { success?: string; error?: string };
    };
    const {
        data,
        setData,
        post,
        processing,
        errors,
        transform,
    } = useForm({
        name: settings?.name ?? '',
        description: settings?.description ?? '',
        phone_country: settings?.phone_country ?? 'BF',
        phone_code: settings?.phone_code ?? '+226',
        phone_number: settings?.phone_number ?? '',
        email: settings?.email ?? '',
        logo: null as File | null,
        remove_logo: false,
    });
    const logoFile = data.logo;
    const selectedCountry = getCountryByCode(data.phone_country) ?? geoCountries[0];
    const logoPreview = useMemo(() => {
        if (logoFile) {
            return URL.createObjectURL(logoFile);
        }
        if (!data.remove_logo && settings?.logo_path) {
            return `/storage/${settings.logo_path}`;
        }
        if (!data.remove_logo && settings?.logo_url) {
            return settings.logo_url;
        }
        return '/favicon.ico';
    }, [logoFile, settings?.logo_path, settings?.logo_url, data.remove_logo]);
    const hasLogo = Boolean(settings?.logo_url) && !data.remove_logo;

    useEffect(() => {
        return () => {
            if (logoPreview) {
                URL.revokeObjectURL(logoPreview);
            }
        };
    }, [logoPreview]);

    useEffect(() => {
        if (!data.phone_code && selectedCountry?.phoneCode) {
            setData('phone_code', selectedCountry.phoneCode);
        }
    }, [data.phone_code, selectedCountry, setData]);

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

    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',
        },
    ];

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Paramètres généraux" />

            <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">
                            <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 paramètres 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"
                    encType="multipart/form-data"
                    onSubmit={(event) => {
                        event.preventDefault();
                        transform((formData) => {
                            if (formData.logo) {
                                return formData;
                            }

                            const { logo, ...rest } = formData;
                            return rest;
                        });
                        post('/settings/general', {
                            forceFormData: true,
                        });
                    }}
                >
                    <div>
                        <h2 className="text-base font-semibold text-blue-700 dark:text-blue-200">
                            Générales
                        </h2>
                        <p className="text-sm text-muted-foreground">
                            Entrez les informations de votre entreprise : logo,
                            nom, description, téléphone et l&apos;email.
                        </p>
                    </div>

                    <div className="flex flex-col items-center gap-3 rounded-xl border border-dashed border-blue-200/80 bg-blue-50/80 p-4 dark:border-blue-900/60 dark:bg-blue-950/30">
                        <Label className="text-sm font-semibold text-blue-700 dark:text-blue-200">
                            Logo
                        </Label>
                        <div className="relative">
                            <Avatar className="h-28 w-28 ring-2 ring-blue-200/80 dark:ring-blue-900/60">
                                {logoPreview ? (
                                    <AvatarImage
                                        key={logoPreview}
                                        src={logoPreview}
                                        alt="Logo"
                                    />
                                ) : null}
                                <AvatarFallback className="text-xs text-muted-foreground">
                                    Logo
                                </AvatarFallback>
                            </Avatar>
                            <Label
                                htmlFor="logo-upload"
                                className="absolute -bottom-2 -right-2 flex h-9 w-9 cursor-pointer items-center justify-center rounded-full border bg-background shadow-sm"
                            >
                                <Upload className="h-4 w-4 text-muted-foreground" />
                            </Label>
                            <input
                                id="logo-upload"
                                type="file"
                                accept="image/*"
                                className="hidden"
                                onChange={(event) => {
                                    setData(
                                        'logo',
                                        event.target.files?.[0] ?? null,
                                    );
                                    setData('remove_logo', false);
                                }}
                            />
                        </div>
                        {hasLogo ? (
                            <Button
                                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={() => {
                                    setData('logo', null);
                                    setData('remove_logo', true);
                                }}
                            >
                                Supprimer le logo
                            </Button>
                        ) : null}
                        <InputError message={errors.logo} />
                    </div>

                    <div className="grid gap-4">
                        <div className="grid gap-2">
                            <Label htmlFor="company-name">
                                Nom de l&apos;entreprise de livraison
                            </Label>
                            <Input
                                id="company-name"
                                placeholder="Nom de l'entreprise"
                                value={data.name}
                                onChange={(event) =>
                                    setData('name', event.target.value)
                                }
                            />
                            <InputError message={errors.name} />
                        </div>

                        <div className="grid gap-2">
                            <Label htmlFor="company-description">
                                Description
                            </Label>
                            <textarea
                                id="company-description"
                                rows={4}
                                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="Décrivez votre entreprise"
                                value={data.description ?? ''}
                                onChange={(event) =>
                                    setData('description', event.target.value)
                                }
                            />
                            <InputError message={errors.description} />
                        </div>

                        <div className="grid gap-2">
                            <Label>Téléphone</Label>
                            <div className="flex flex-col gap-2 md:flex-row md:items-center">
                                <Select
                                    value={data.phone_country}
                                    onValueChange={(value) => {
                                        const country = getCountryByCode(value);
                                        setData('phone_country', value);
                                        if (country?.phoneCode) {
                                            setData('phone_code', country.phoneCode);
                                        }
                                    }}
                                >
                                    <SelectTrigger className="w-full md:w-40">
                                        <SelectValue placeholder="Pays" />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {geoCountries.map((country) => (
                                            <SelectItem
                                                key={country.code}
                                                value={country.code}
                                            >
                                                {country.name}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>

                                <Input
                                    className="w-full md:w-24"
                                    value={data.phone_code ?? ''}
                                    onChange={(event) =>
                                        setData('phone_code', event.target.value)
                                    }
                                    aria-label="Indicatif"
                                />
                                <Input
                                    className="w-full"
                                    placeholder="Numéro de téléphone"
                                    value={data.phone_number ?? ''}
                                    onChange={(event) =>
                                        setData('phone_number', event.target.value)
                                    }
                                />
                            </div>
                            <InputError message={errors.phone_country} />
                            <InputError message={errors.phone_code} />
                            <InputError message={errors.phone_number} />
                        </div>

                        <div className="grid gap-2">
                            <Label htmlFor="company-email">Email</Label>
                            <Input
                                id="company-email"
                                type="email"
                                placeholder="email@exemple.com"
                                value={data.email ?? ''}
                                onChange={(event) =>
                                    setData('email', event.target.value)
                                }
                            />
                            <InputError message={errors.email} />
                        </div>
                    </div>

                    <div className="flex justify-start">
                        <Button type="submit" disabled={processing}>
                            Enregistrer & Suivant
                        </Button>
                    </div>
                </form>
            </div>
        </AppLayout>
    );
}
