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, Upload } from 'lucide-react';
import { geoCountries, getCountryByCode } from '@/data/geo';
import { useToast } from '@/components/ui/toast-provider';

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Paramètres plateforme', href: '/parametres-plateforme' },
];

type PlatformSettingsProps = {
    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 PlatformSettings({
    settings,
    tableMissing,
}: PlatformSettingsProps) {
    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 && logoFile) URL.revokeObjectURL(logoPreview);
        };
    }, [logoPreview, logoFile]);

    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]);

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Paramètres plateforme" />

            <div className="space-y-8">
                <div className="flex items-center gap-3">
                    <Button variant="ghost" size="icon" asChild>
                        <Link href="/dashboard">
                            <ArrowLeft className="h-5 w-5" />
                        </Link>
                    </Button>
                    <div>
                        <h1 className="text-lg font-semibold md:text-xl">
                            Paramètres globaux du logiciel
                        </h1>
                        <p className="text-sm text-muted-foreground">
                            Nom, logo et description de la plateforme (affichés sur les pages de connexion et par défaut).
                        </p>
                    </div>
                </div>

                {tableMissing && (
                    <Alert variant="destructive">
                        <AlertTitle>Erreur</AlertTitle>
                        <AlertDescription>
                            La table des paramètres est introuvable. Lancez les migrations.
                        </AlertDescription>
                    </Alert>
                )}

                <form
                    className="space-y-6 rounded-xl border bg-card p-6 shadow-sm"
                    encType="multipart/form-data"
                    onSubmit={(e) => {
                        e.preventDefault();
                        transform((formData) => {
                            if (formData.logo) return formData;
                            const { logo, ...rest } = formData;
                            return rest;
                        });
                        post('/parametres-plateforme', { forceFormData: true });
                    }}
                >
                    <div className="flex items-center gap-2 text-muted-foreground">
                        <Building2 className="h-5 w-5" />
                        <h2 className="font-semibold text-foreground">Identité de la plateforme</h2>
                    </div>

                    <div className="flex flex-col items-center gap-3 rounded-lg border border-dashed bg-muted/30 p-4">
                        <Label className="font-medium">Logo</Label>
                        <div className="relative">
                            <Avatar className="h-24 w-24 ring-2 ring-border">
                                {logoPreview ? (
                                    <AvatarImage key={logoPreview} src={logoPreview} alt="Logo" />
                                ) : null}
                                <AvatarFallback>Logo</AvatarFallback>
                            </Avatar>
                            <Label
                                htmlFor="platform-logo"
                                className="absolute -bottom-1 -right-1 flex h-8 w-8 cursor-pointer items-center justify-center rounded-full border bg-background shadow-sm"
                            >
                                <Upload className="h-4 w-4" />
                            </Label>
                            <input
                                id="platform-logo"
                                type="file"
                                accept="image/*"
                                className="hidden"
                                onChange={(e) => {
                                    setData('logo', e.target.files?.[0] ?? null);
                                    setData('remove_logo', false);
                                }}
                            />
                        </div>
                        {hasLogo && (
                            <Button
                                type="button"
                                variant="outline"
                                size="sm"
                                onClick={() => {
                                    setData('logo', null);
                                    setData('remove_logo', true);
                                }}
                            >
                                Supprimer le logo
                            </Button>
                        )}
                        <InputError message={errors.logo} />
                    </div>

                    <div className="grid gap-4">
                        <div className="grid gap-2">
                            <Label htmlFor="platform-name">Nom de l&apos;application</Label>
                            <Input
                                id="platform-name"
                                placeholder="Ex. E-Logi"
                                value={data.name}
                                onChange={(e) => setData('name', e.target.value)}
                            />
                            <InputError message={errors.name} />
                        </div>

                        <div className="grid gap-2">
                            <Label htmlFor="platform-description">Description</Label>
                            <textarea
                                id="platform-description"
                                rows={3}
                                className="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                                placeholder="Courte description de la plateforme"
                                value={data.description ?? ''}
                                onChange={(e) => setData('description', e.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((c) => (
                                            <SelectItem key={c.code} value={c.code}>{c.name}</SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                                <Input
                                    className="w-full md:w-24"
                                    value={data.phone_code ?? ''}
                                    onChange={(e) => setData('phone_code', e.target.value)}
                                    aria-label="Indicatif"
                                />
                                <Input
                                    className="w-full"
                                    placeholder="Numéro"
                                    value={data.phone_number ?? ''}
                                    onChange={(e) => setData('phone_number', e.target.value)}
                                />
                            </div>
                            <InputError message={errors.phone_number} />
                        </div>

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

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