import { Head, useForm } from '@inertiajs/react';
import { useState } from 'react';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import InputError from '@/components/input-error';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { geoCountries, getCountryByCode } from '@/data/geo';
import {
    Building2,
    Check,
    ChevronLeft,
    ChevronRight,
    Shield,
    Sparkles,
    Upload,
} from 'lucide-react';

const STEPS = [
    { id: 1, title: 'Compte administrateur', short: 'Admin', icon: Shield, color: 'red' },
    { id: 2, title: 'Paramètres plateforme', short: 'Plateforme', icon: Building2, color: 'blue' },
];

export default function Install() {
    const [step, setStep] = useState(1);
    const {
        data,
        setData,
        post,
        processing,
        errors,
        transform,
    } = useForm({
        admin_name: '',
        admin_email: '',
        admin_password: '',
        admin_password_confirmation: '',
        platform_name: '',
        platform_description: '',
        platform_email: '',
        platform_phone_country: 'BF',
        platform_phone_code: '+226',
        platform_phone_number: '',
        platform_logo: null as File | null,
    });

    const logoPreview = data.platform_logo
        ? URL.createObjectURL(data.platform_logo)
        : null;

    const canNextStep1 =
        data.admin_name.trim() !== '' &&
        data.admin_email.trim() !== '' &&
        data.admin_password.length >= 6 &&
        data.admin_password === data.admin_password_confirmation;

    const canSubmit = canNextStep1 && data.platform_name.trim() !== '';

    const submit = (e: React.FormEvent) => {
        e.preventDefault();
        transform((formData) => {
            if (formData.platform_logo) return formData;
            const { platform_logo, ...rest } = formData;
            return rest;
        });
        post('/install', { forceFormData: true });
    };

    const inputBase =
        'rounded-lg border-2 bg-neutral-900/50 text-white placeholder:text-neutral-500 focus:border-red-500 focus:ring-2 focus:ring-red-500/20 transition-colors';
    const labelClass = 'text-sm font-medium text-neutral-300';

    return (
        <>
            <Head title="Installation" />
            <div className="min-h-svh relative flex flex-col items-center justify-center overflow-hidden bg-neutral-950 p-4 md:p-8">
                {/* Fond décoratif : dégradés rouge, bleu, vert */}
                <div
                    className="pointer-events-none fixed inset-0"
                    aria-hidden
                >
                    <div className="absolute -left-40 -top-40 h-80 w-80 rounded-full bg-red-600/20 blur-[100px]" />
                    <div className="absolute -right-40 top-1/3 h-80 w-80 rounded-full bg-blue-600/20 blur-[100px]" />
                    <div className="absolute bottom-0 left-1/2 h-64 w-96 -translate-x-1/2 rounded-full bg-green-600/15 blur-[80px]" />
                </div>

                <div className="relative z-10 w-full max-w-xl">
                    {/* En-tête */}
                    <div className="mb-8 text-center">
                        <div className="mb-4 inline-flex items-center justify-center rounded-full bg-neutral-800/80 px-4 py-2 text-sm font-medium text-neutral-300 ring-1 ring-neutral-700">
                            <Sparkles className="mr-2 h-4 w-4 text-green-500" />
                            Assistant d’installation
                        </div>
                        <h1 className="text-3xl font-bold tracking-tight text-white md:text-4xl">
                            Installation du logiciel
                        </h1>
                        <p className="mt-2 text-neutral-400">
                            Créez votre compte administrateur puis configurez la plateforme en quelques clics.
                        </p>
                    </div>

                    {/* Indicateur d’étapes */}
                    <div className="mb-8">
                        <div className="flex items-center justify-between">
                            {STEPS.map((s, index) => (
                                <div key={s.id} className="flex flex-1 items-center">
                                    <div className="flex flex-col items-center">
                                        <div
                                            className={`flex h-12 w-12 items-center justify-center rounded-full border-2 transition-all ${
                                                step > s.id
                                                    ? 'border-green-500 bg-green-500/20 text-green-400'
                                                    : step === s.id
                                                      ? s.color === 'red'
                                                          ? 'border-red-500 bg-red-500/20 text-red-400 ring-4 ring-red-500/20'
                                                          : 'border-blue-500 bg-blue-500/20 text-blue-400 ring-4 ring-blue-500/20'
                                                      : 'border-neutral-600 bg-neutral-800/80 text-neutral-500'
                                            }`}
                                        >
                                            {step > s.id ? (
                                                <Check className="h-6 w-6" />
                                            ) : (
                                                <s.icon className="h-6 w-6" />
                                            )}
                                        </div>
                                        <span
                                            className={`mt-2 hidden text-center text-xs font-medium sm:block ${
                                                step >= s.id ? 'text-neutral-300' : 'text-neutral-500'
                                            }`}
                                        >
                                            {s.short}
                                        </span>
                                    </div>
                                    {index < STEPS.length - 1 && (
                                        <div
                                            className={`mx-2 h-0.5 flex-1 rounded transition-colors ${
                                                step > s.id ? 'bg-green-500/50' : 'bg-neutral-700'
                                            }`}
                                        />
                                    )}
                                </div>
                            ))}
                        </div>
                        <p className="mt-3 text-center text-sm text-neutral-500">
                            Étape {step} sur {STEPS.length}
                        </p>
                    </div>

                    {/* Formulaire */}
                    <form
                        onSubmit={submit}
                        className={`overflow-hidden rounded-2xl border border-neutral-800 bg-neutral-900/60 shadow-2xl backdrop-blur-sm ${
                            step === 1
                                ? 'border-l-4 border-l-red-500'
                                : 'border-l-4 border-l-blue-500'
                        }`}
                        encType="multipart/form-data"
                    >
                        <div className="p-6 md:p-8">
                            {step === 1 && (
                                <div className="space-y-5">
                                    <div className="flex items-center gap-3">
                                        <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-red-500/20 text-red-400">
                                            <Shield className="h-5 w-5" />
                                        </div>
                                        <div>
                                            <h2 className="text-lg font-semibold text-white">
                                                Compte administrateur
                                            </h2>
                                            <p className="text-sm text-neutral-400">
                                                Identifiants de connexion pour gérer la plateforme
                                            </p>
                                        </div>
                                    </div>

                                    <div className="grid gap-4 sm:grid-cols-2">
                                        <div className="sm:col-span-2">
                                            <Label htmlFor="admin_name" className={labelClass}>
                                                Nom complet
                                            </Label>
                                            <Input
                                                id="admin_name"
                                                value={data.admin_name}
                                                onChange={(e) => setData('admin_name', e.target.value)}
                                                placeholder="Jean Dupont"
                                                required
                                                className={inputBase}
                                            />
                                            <InputError message={errors.admin_name} />
                                        </div>
                                        <div className="sm:col-span-2">
                                            <Label htmlFor="admin_email" className={labelClass}>
                                                Email
                                            </Label>
                                            <Input
                                                id="admin_email"
                                                type="email"
                                                value={data.admin_email}
                                                onChange={(e) => setData('admin_email', e.target.value)}
                                                placeholder="admin@exemple.com"
                                                required
                                                className={inputBase}
                                            />
                                            <InputError message={errors.admin_email} />
                                        </div>
                                        <div>
                                            <Label htmlFor="admin_password" className={labelClass}>
                                                Mot de passe
                                            </Label>
                                            <Input
                                                id="admin_password"
                                                type="password"
                                                value={data.admin_password}
                                                onChange={(e) => setData('admin_password', e.target.value)}
                                                placeholder="••••••••"
                                                required
                                                minLength={6}
                                                className={inputBase}
                                            />
                                            <InputError message={errors.admin_password} />
                                            <p className="mt-1 text-xs text-neutral-500">
                                                Min. 6 caractères
                                            </p>
                                        </div>
                                        <div>
                                            <Label htmlFor="admin_password_confirmation" className={labelClass}>
                                                Confirmer le mot de passe
                                            </Label>
                                            <Input
                                                id="admin_password_confirmation"
                                                type="password"
                                                value={data.admin_password_confirmation}
                                                onChange={(e) =>
                                                    setData('admin_password_confirmation', e.target.value)
                                                }
                                                placeholder="••••••••"
                                                required
                                                className={inputBase}
                                            />
                                            <InputError message={errors.admin_password_confirmation} />
                                        </div>
                                    </div>
                                </div>
                            )}

                            {step === 2 && (
                                <div className="space-y-5">
                                    <div className="flex items-center gap-3">
                                        <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-blue-500/20 text-blue-400">
                                            <Building2 className="h-5 w-5" />
                                        </div>
                                        <div>
                                            <h2 className="text-lg font-semibold text-white">
                                                Paramètres de la plateforme
                                            </h2>
                                            <p className="text-sm text-neutral-400">
                                                Nom, logo et coordonnées affichés aux utilisateurs
                                            </p>
                                        </div>
                                    </div>

                                    <div className="flex flex-col items-center gap-3 rounded-xl border-2 border-dashed border-neutral-700 bg-neutral-800/50 p-6 transition-colors hover:border-blue-500/50">
                                        <Label className="font-medium text-neutral-300">
                                            Logo (optionnel)
                                        </Label>
                                        <div className="relative">
                                            <Avatar className="h-24 w-24 ring-4 ring-neutral-700">
                                                {logoPreview ? (
                                                    <AvatarImage src={logoPreview} alt="Logo" />
                                                ) : null}
                                                <AvatarFallback className="bg-neutral-700 text-neutral-400">
                                                    Logo
                                                </AvatarFallback>
                                            </Avatar>
                                            <Label
                                                htmlFor="platform_logo"
                                                className="absolute -bottom-1 -right-1 flex h-9 w-9 cursor-pointer items-center justify-center rounded-full border-2 border-neutral-600 bg-neutral-800 text-blue-400 shadow-lg transition-colors hover:border-blue-500 hover:bg-blue-500/20"
                                            >
                                                <Upload className="h-4 w-4" />
                                            </Label>
                                            <input
                                                id="platform_logo"
                                                type="file"
                                                accept="image/*"
                                                className="hidden"
                                                onChange={(e) =>
                                                    setData(
                                                        'platform_logo',
                                                        e.target.files?.[0] ?? null,
                                                    )
                                                }
                                            />
                                        </div>
                                        <span className="text-xs text-neutral-500">
                                            Cliquez sur l’icône pour choisir une image
                                        </span>
                                    </div>

                                    <div className="grid gap-4">
                                        <div>
                                            <Label htmlFor="platform_name" className={labelClass}>
                                                Nom de la plateforme <span className="text-red-400">*</span>
                                            </Label>
                                            <Input
                                                id="platform_name"
                                                value={data.platform_name}
                                                onChange={(e) =>
                                                    setData('platform_name', e.target.value)
                                                }
                                                placeholder="Ex. E-Logi"
                                                required
                                                className={inputBase}
                                            />
                                            <InputError message={errors.platform_name} />
                                        </div>
                                        <div>
                                            <Label htmlFor="platform_description" className={labelClass}>
                                                Description (optionnel)
                                            </Label>
                                            <textarea
                                                id="platform_description"
                                                rows={2}
                                                className={`w-full ${inputBase} resize-none px-3 py-2`}
                                                placeholder="Courte description de votre plateforme"
                                                value={data.platform_description ?? ''}
                                                onChange={(e) =>
                                                    setData('platform_description', e.target.value)
                                                }
                                            />
                                        </div>
                                        <div className="grid gap-2">
                                            <Label className={labelClass}>Téléphone (optionnel)</Label>
                                            <div className="flex flex-col gap-2 sm:flex-row sm:items-center">
                                                <Select
                                                    value={data.platform_phone_country}
                                                    onValueChange={(value) => {
                                                        const country = getCountryByCode(value);
                                                        setData('platform_phone_country', value);
                                                        if (country?.phoneCode)
                                                            setData('platform_phone_code', country.phoneCode);
                                                    }}
                                                >
                                                    <SelectTrigger className={`w-full sm:w-36 ${inputBase} border-neutral-700`}>
                                                        <SelectValue placeholder="Pays" />
                                                    </SelectTrigger>
                                                    <SelectContent className="bg-neutral-900 border-neutral-700">
                                                        {geoCountries.map((c) => (
                                                            <SelectItem key={c.code} value={c.code}>
                                                                {c.name}
                                                            </SelectItem>
                                                        ))}
                                                    </SelectContent>
                                                </Select>
                                                <Input
                                                    className={`w-full sm:w-20 ${inputBase}`}
                                                    value={data.platform_phone_code ?? ''}
                                                    onChange={(e) =>
                                                        setData('platform_phone_code', e.target.value)
                                                    }
                                                    aria-label="Indicatif"
                                                />
                                                <Input
                                                    className={`w-full ${inputBase}`}
                                                    placeholder="Numéro"
                                                    value={data.platform_phone_number ?? ''}
                                                    onChange={(e) =>
                                                        setData('platform_phone_number', e.target.value)
                                                    }
                                                />
                                            </div>
                                        </div>
                                        <div>
                                            <Label htmlFor="platform_email" className={labelClass}>
                                                Email contact (optionnel)
                                            </Label>
                                            <Input
                                                id="platform_email"
                                                type="email"
                                                placeholder="contact@exemple.com"
                                                value={data.platform_email ?? ''}
                                                onChange={(e) =>
                                                    setData('platform_email', e.target.value)
                                                }
                                                className={inputBase}
                                            />
                                            <InputError message={errors.platform_email} />
                                        </div>
                                    </div>
                                </div>
                            )}
                        </div>

                        {/* Pied : navigation */}
                        <div className="flex items-center justify-between border-t border-neutral-800 bg-neutral-900/80 px-6 py-4 md:px-8">
                            {step === 1 ? (
                                <div />
                            ) : (
                                <Button
                                    type="button"
                                    variant="ghost"
                                    onClick={() => setStep(1)}
                                    className="gap-2 text-neutral-400 hover:bg-neutral-800 hover:text-white"
                                >
                                    <ChevronLeft className="h-4 w-4" />
                                    Retour
                                </Button>
                            )}
                            {step === 1 ? (
                                <Button
                                    type="button"
                                    disabled={!canNextStep1}
                                    onClick={() => setStep(2)}
                                    className="gap-2 bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-50"
                                >
                                    Suivant
                                    <ChevronRight className="h-4 w-4" />
                                </Button>
                            ) : (
                                <Button
                                    type="submit"
                                    disabled={processing || !canSubmit}
                                    className="gap-2 bg-green-600 text-white hover:bg-green-700 disabled:opacity-50"
                                >
                                    {processing ? (
                                        <>
                                            <span className="h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" />
                                            Installation…
                                        </>
                                    ) : (
                                        <>
                                            <Check className="h-4 w-4" />
                                            Terminer l’installation
                                        </>
                                    )}
                                </Button>
                            )}
                        </div>
                    </form>

                    <p className="mt-6 text-center text-xs text-neutral-600">
                        Après l’installation, vous serez redirigé vers la page de connexion.
                    </p>
                </div>
            </div>
        </>
    );
}
