/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useEffect, useMemo, useState, useCallback } from "react";
import { motion, AnimatePresence } from 'framer-motion';
import {
    X, Save, Building2, MapPin, User, Phone, Mail, Globe, CreditCard, Hash,
    Loader2,
} from "lucide-react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { useNavigate } from "react-router-dom";
import { toast } from "@/components/ui/use-toast";
import { Client, ClientRequest, ClientUpdateRequest } from "@/types/clientType";
import { addClient, updateClient } from "@/store/features/client/thunk";
import { clientStatus, getAllClients } from "@/store/features/client/selectors";
import { selectClient } from "@/store/features/client/slice";
import { cn } from "@/lib/utils";
import { Progress } from "../ui/Progress";
import { Section } from "../ui/Section";
import { InputField, InputType, validators } from "../ui/InputValidator";
import z from "zod";
import { useForm, Controller, type SubmitHandler } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Alert } from "@mui/material";

// ============================================
// HELPERS ZOD
// ============================================

const createZodValidator = (inputType: InputType, message?: string) => {
    return z.string().refine(
        (val) => !val || validators[inputType](val).isValid,
        (val) => ({ message: message || validators[inputType](val).message })
    );
};

// Schéma optionnel (valide si vide OU si format correct)
const optionalZodValidator = (inputType: InputType, message?: string) => {
    return z.string().refine(
        (val) => !val || val.trim() === "" || validators[inputType](val).isValid,
        (val) => ({ message: message || validators[inputType](val).message })
    ).optional().or(z.literal(""));
};

// ============================================
// SCHÉMA DE VALIDATION DU FORMULAIRE
// ============================================

const clientSchema = z.object({
    // Identification
    numero: z.string()
        .min(1, "Le code client est requise")
        .regex(
            /^[A-Za-z0-9]+$/, 
            "Le code client ne peut contenir que des lettres et des chiffres"
        ),
    compte_collectif: z.string().min(1, "Le code collectif est requis"),
    intitule: z.string().min(1, "L'intitulé est requis"),
    type_tiers: z.string().default("client"),
    est_entreprise: z.boolean().default(true),
    est_particulier: z.boolean().default(false),
    est_prospect: z.boolean().default(false),
    est_actif: z.boolean().default(true),
    forme_juridique: z.string().optional(),
    secteur: z.string().optional(),

    // Contact
    civilite: z.string().optional(),
    nom: z.string().optional(),
    prenom: z.string().optional(),
    contact: z.string().optional(),
    email: optionalZodValidator("email", "Format email invalide"),
    telephone: optionalZodValidator("phone", "Format téléphone invalide"),
    portable: optionalZodValidator("phone", "Format téléphone invalide"),
    telecopie: z.string().optional(),
    site_web: optionalZodValidator("url", "Format URL invalide"),

    // Adresse
    adresse: z.string().optional(),
    complement: z.string().optional(),
    code_postal: optionalZodValidator("postal_code", "Code postal invalide"),
    ville: z.string().optional(),
    region: z.string().optional(),
    pays: z.string().default("France"),

    // Informations légales
    siret: optionalZodValidator("siret", "SIRET invalide (14 chiffres)"),
    siren: optionalZodValidator("siren", "SIREN invalide (9 chiffres)"),
    tva_intra: optionalZodValidator("tva_intra", "TVA intracommunautaire invalide"),
    code_naf: z.string().optional(),
    effectif: z.number().nullable().optional(),
    ca_annuel: z.number().nullable().optional(),

    // Commercial & Comptabilité
    commercial_code: z.string().optional(),
    commercial_nom: z.string().optional(),
    categorie_tarifaire: z.any().nullable().optional(),
    categorie_comptable: z.any().nullable().optional(),
    encours_autorise: z.number().default(0),
    compte_general: z.string().optional(),
});

type ClientFormData = z.infer<typeof clientSchema>;

// ============================================
// COMPOSANT PRINCIPAL
// ============================================

export function ModalClient({
    open,
    onClose,
    title,
    editing
}: {
    open: boolean;
    onClose: () => void;
    title?: string;
    editing?: Client | null;
}) {
    const navigate = useNavigate();
    const dispatch = useAppDispatch();
    const status = useAppSelector(clientStatus);
    const [completion, setCompletion] = useState(0);
    const clients = useAppSelector(getAllClients) as Client[];
    const [error, setError] = useState<string | null>(null)
    const isEditing = !!editing;

    // React Hook Form
    const {
        control,
        handleSubmit,
        watch,
        reset,
        setValue,
        formState: { errors, isValid, dirtyFields }
    } = useForm<ClientFormData>({
        resolver: zodResolver(clientSchema),
        mode: "onBlur",
        defaultValues: {
            numero: "",
            compte_collectif: "",
            intitule: "",
            type_tiers: "client",
            est_entreprise: true,
            est_particulier: false,
            est_prospect: false,
            est_actif: true,
            civilite: "",
            nom: "",
            prenom: "",
            contact: "",
            adresse: "",
            complement: "",
            code_postal: "",
            ville: "",
            region: "",
            pays: "France",
            telephone: "",
            portable: "",
            telecopie: "",
            email: "",
            site_web: "",
            siret: "",
            siren: "",
            tva_intra: "",
            code_naf: "",
            forme_juridique: "",
            secteur: "",
            effectif: null,
            ca_annuel: null,
            commercial_code: "",
            commercial_nom: "",
            categorie_tarifaire: null,
            categorie_comptable: null,
            encours_autorise: 0,
            compte_general: "",
        }
    });

    // Watch pour les valeurs réactives
    const formValues = watch();
    const est_entreprise = watch("est_entreprise");

    // Reset form quand le modal s'ouvre
    useEffect(() => {
        if (!open) return;
        if (editing) {
            reset({
                ...editing,
                effectif: editing.effectif ?? null,
                ca_annuel: editing.ca_annuel ?? null,
            });
        } else {
            reset({
                numero: "",
                compte_collectif: "",
                intitule: "",
                type_tiers: "client",
                est_entreprise: true,
                est_particulier: false,
                est_prospect: false,
                est_actif: true,
                civilite: "",
                nom: "",
                prenom: "",
                contact: "",
                adresse: "",
                complement: "",
                code_postal: "",
                ville: "",
                region: "",
                pays: "France",
                telephone: "",
                portable: "",
                telecopie: "",
                email: "",
                site_web: "",
                siret: "",
                siren: "",
                tva_intra: "",
                code_naf: "",
                forme_juridique: "",
                secteur: "",
                effectif: null,
                ca_annuel: null,
                commercial_code: "",
                commercial_nom: "",
                categorie_tarifaire: null,
                categorie_comptable: null,
                encours_autorise: 0,
                compte_general: "",
            });
        }
    }, [open, editing, reset]);

    // Calcul completion
    useEffect(() => {
        const requiredFields: (keyof ClientFormData)[] = ['numero', 'intitule', 'email', 'telephone'];
        const filled = requiredFields.filter(f => !!formValues[f]);
        setCompletion(Math.round((filled.length / requiredFields.length) * 100));
    }, [formValues]);

    const canSave = useMemo(() => {
        return !!formValues.intitule && !!formValues.numero;
    }, [formValues.intitule, formValues.numero]);

    // Submit handler
    const onSave: SubmitHandler<ClientFormData> = async (data) => {
        error && setError(null);
        try {
            if (isEditing) {
                const payload: ClientUpdateRequest = {
                    intitule: data.intitule,
                    adresse: data.adresse,
                    code_postal: data.code_postal,
                    ville: data.ville,
                    email: data.email,
                    telephone: data.telephone,
                    pays: data.pays,
                    siret: data.siret,
                    tva_intra: data.tva_intra || ""
                };

                const rep = await dispatch(updateClient({
                    numero: data.numero,
                    data: payload
                })).unwrap() as any;

                const dataResponse = rep.client as Client;
                toast({
                    title: "Client mis à jour !",
                    description: `Le client ${dataResponse.numero} a été mis à jour avec succès.`,
                    className: "bg-green-500 text-white border-green-600"
                });

                setTimeout(() => {
                    dispatch(selectClient(dataResponse));
                    navigate(`/home/clients/${dataResponse.numero}`);
                }, 1500);

            } else {
                const payloadCreate: ClientRequest = {
                    num: data.numero,
                    compte_collectif: data.compte_collectif,
                    intitule: data.intitule,
                    adresse: data.adresse,
                    code_postal: data.code_postal,
                    ville: data.ville,
                    email: data.email,
                    telephone: data.telephone,
                    pays: data.pays,
                    siret: data.siret,
                    tva_intra: data.tva_intra || ""
                };

                const existingClient = clients.find(client => client.numero === data.numero);
                if (existingClient) {
                    setError(`Le code client "${data.numero}" est déjà utilisé. Veuillez en choisir un autre.`);
                    return;
                }
                console.log("payloadCreate : ",payloadCreate);
                

                const rep = await dispatch(addClient(payloadCreate)).unwrap() as any;
                
                const dataResponse = rep.data as Client;

                toast({
                    title: "Client créé !",
                    description: `Un nouveau client a été créé avec succès.`,
                    className: "bg-green-500 text-white border-green-600"
                });

                setTimeout(() => {
                    dispatch(selectClient(dataResponse));
                    navigate(`/home/clients/${dataResponse.numero}`);
                }, 1500);
            }

            onClose();
        } catch (e) {
            toast({
                title: "Erreur",
                description: "Une erreur est survenue.",
                variant: "destructive"
            });
        }
    };

    if (!open) return null;

    return (
        <AnimatePresence>
            {open && (
                <>
                    <motion.div
                        initial={{ opacity: 0 }}
                        animate={{ opacity: 1 }}
                        exit={{ opacity: 0 }}
                        onClick={onClose}
                        className="fixed inset-0 bg-black/40 backdrop-blur-sm z-50"
                    />
                    <motion.div
                        initial={{ x: "100%" }}
                        animate={{ x: 0 }}
                        exit={{ x: "100%" }}
                        transition={{ type: "spring", damping: 25, stiffness: 200 }}
                        className="fixed inset-y-0 right-0 w-full max-w-xl bg-white dark:bg-gray-950 shadow-2xl z-50 flex flex-col border-l border-gray-200 dark:border-gray-800"
                    >
                        {/* Header */}
                        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-800 bg-white/80 dark:bg-gray-950/80 backdrop-blur-md">
                            <div>
                                <h2 className="text-lg font-bold text-gray-900 dark:text-white">
                                    {title || (isEditing ? "Modifier le client" : "Nouveau client")}
                                </h2>
                                <p className="text-xs text-gray-500">{completion}% complété</p>
                            </div>
                            <button onClick={onClose} className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-full transition-colors">
                                <X className="w-5 h-5 text-gray-500" />
                            </button>
                        </div>
                        <Progress value={completion} className="h-4 rounded-none" />

                        {/* Body */}
                        <form onSubmit={handleSubmit(onSave)} className="flex-1 overflow-y-auto bg-gray-50/50 dark:bg-black/20">
                            {/* Type de client */}
                            <div className="p-4 border-b border-gray-100 dark:border-gray-800">
                                <div className="flex gap-2">
                                    {[
                                        { val: true, label: 'Entreprise', icon: Building2 },
                                        { val: false, label: 'Particulier', icon: User }
                                    ].map((opt) => (
                                        <button
                                            key={opt.label}
                                            type="button"
                                            onClick={() => {
                                                setValue('est_entreprise', opt.val);
                                                setValue('est_particulier', !opt.val);
                                            }}
                                            className={cn(
                                                "flex-1 flex items-center justify-center gap-2 py-2.5 rounded-xl border text-sm font-medium transition-all",
                                                est_entreprise === opt.val
                                                    ? "bg-[#941403] text-white border-[#941403] shadow-lg shadow-red-900/20"
                                                    : "bg-white dark:bg-gray-900 text-gray-600 dark:text-gray-400 border-gray-200 dark:border-gray-700 hover:border-gray-300"
                                            )}
                                        >
                                            <opt.icon className="w-4 h-4" />
                                            {opt.label}
                                        </button>
                                    ))}
                                </div>
                            </div>

                            {/* Sections */}
                            <Section title="Identification" icon={Hash} defaultOpen={true}>
                                <div className="grid grid-cols-2 gap-4">
                                    <Controller
                                        name="numero"
                                        control={control}
                                        render={({ field }) => (
                                            <InputField
                                                {...field}
                                                label="Code client"
                                                inputType="text"
                                                required
                                                disabled={isEditing}
                                                placeholder="Ex: CLI001"
                                                error={errors.numero?.message}
                                                className={cn(isEditing && "bg-gray-100 dark:bg-gray-800 cursor-not-allowed")}
                                            />
                                        )}
                                    />
                                    <Controller
                                        name="compte_collectif"
                                        control={control}
                                        render={({ field }) => (
                                            <InputField
                                                {...field}
                                                label="Compte collectif"
                                                required
                                                inputType="text"
                                                placeholder="411000"
                                                error={errors.compte_collectif?.message}
                                            />
                                        )}
                                    />
                                </div>
                                <Controller
                                    name="intitule"
                                    control={control}
                                    render={({ field }) => (
                                        <InputField
                                            {...field}
                                            label="Intitulé / Raison sociale"
                                            inputType="text"
                                            required
                                            placeholder="Nom de l'entreprise ou du client"
                                            error={errors.intitule?.message}
                                        />
                                    )}
                                />
                                {est_entreprise && (
                                    <div className="grid grid-cols-2 gap-4">
                                        <Controller
                                            name="forme_juridique"
                                            control={control}
                                            render={({ field }) => (
                                                <InputField
                                                    {...field}
                                                    label="Forme juridique"
                                                    as="select"
                                                    options={[
                                                        { value: "", label: "Sélectionner..." },
                                                        { value: "SARL", label: "SARL" },
                                                        { value: "SAS", label: "SAS" },
                                                        { value: "SA", label: "SA" },
                                                        { value: "EURL", label: "EURL" },
                                                        { value: "EI", label: "EI" },
                                                        { value: "SCI", label: "SCI" },
                                                    ]}
                                                />
                                            )}
                                        />
                                        <Controller
                                            name="secteur"
                                            control={control}
                                            render={({ field }) => (
                                                <InputField
                                                    {...field}
                                                    label="Secteur d'activité"
                                                    inputType="text"
                                                    placeholder="Ex: Commerce"
                                                />
                                            )}
                                        />
                                    </div>
                                )}
                                <div className="flex gap-4">
                                    <Controller
                                        name="est_prospect"
                                        control={control}
                                        render={({ field }) => (
                                            <label className="flex items-center gap-2 cursor-pointer">
                                                <input
                                                    type="checkbox"
                                                    checked={field.value || false}
                                                    onChange={(e) => field.onChange(e.target.checked)}
                                                    className="w-4 h-4 text-[#941403] rounded border-gray-300 focus:ring-[#941403]"
                                                />
                                                <span className="text-sm text-gray-700 dark:text-gray-300">Prospect</span>
                                            </label>
                                        )}
                                    />
                                    <Controller
                                        name="est_actif"
                                        control={control}
                                        render={({ field }) => (
                                            <label className="flex items-center gap-2 cursor-pointer">
                                                <input
                                                    type="checkbox"
                                                    checked={field.value !== false}
                                                    onChange={(e) => field.onChange(e.target.checked)}
                                                    className="w-4 h-4 text-[#941403] rounded border-gray-300 focus:ring-[#941403]"
                                                />
                                                <span className="text-sm text-gray-700 dark:text-gray-300">Actif</span>
                                            </label>
                                        )}
                                    />
                                </div>
                            </Section>

                            <Section title="Contact principal" icon={User} defaultOpen={true}>
                                <div className="grid grid-cols-4 gap-4">
                                    <Controller
                                        name="civilite"
                                        control={control}
                                        render={({ field }) => (
                                            <InputField
                                                {...field}
                                                label="Civilité"
                                                as="select"
                                                options={[
                                                    { value: "", label: "-" },
                                                    { value: "M.", label: "M." },
                                                    { value: "Mme", label: "Mme" },
                                                ]}
                                            />
                                        )}
                                    />
                                    <Controller
                                        name="prenom"
                                        control={control}
                                        render={({ field }) => (
                                            <InputField
                                                {...field}
                                                label="Prénom"
                                                inputType="text"
                                                containerClassName="col-span-1"
                                            />
                                        )}
                                    />
                                    <Controller
                                        name="nom"
                                        control={control}
                                        render={({ field }) => (
                                            <InputField
                                                {...field}
                                                label="Nom"
                                                inputType="text"
                                                containerClassName="col-span-2"
                                            />
                                        )}
                                    />
                                </div>
                                <Controller
                                    name="contact"
                                    control={control}
                                    render={({ field }) => (
                                        <InputField
                                            {...field}
                                            label="Fonction / Contact"
                                            inputType="text"
                                            placeholder="Ex: Directeur commercial"
                                        />
                                    )}
                                />
                                <div className="grid grid-cols-2 gap-4">
                                    <Controller
                                        name="email"
                                        control={control}
                                        render={({ field }) => (
                                            <InputField
                                                {...field}
                                                label="Email"
                                                inputType="email"
                                                required
                                                placeholder="email@exemple.com"
                                                error={errors.email?.message}
                                                leftIcon={<Mail className="w-4 h-4" />}
                                            />
                                        )}
                                    />
                                    <Controller
                                        name="telephone"
                                        control={control}
                                        render={({ field }) => (
                                            <InputField
                                                {...field}
                                                label="Téléphone"
                                                inputType="phone"
                                                placeholder="01 23 45 67 89"
                                                error={errors.telephone?.message}
                                                leftIcon={<Phone className="w-4 h-4" />}
                                            />
                                        )}
                                    />
                                </div>
                                <div className="grid grid-cols-2 gap-4">
                                    <Controller
                                        name="portable"
                                        control={control}
                                        render={({ field }) => (
                                            <InputField
                                                {...field}
                                                label="Portable"
                                                inputType="phone"
                                                placeholder="06 12 34 56 78"
                                                error={errors.portable?.message}
                                            />
                                        )}
                                    />
                                    <Controller
                                        name="site_web"
                                        control={control}
                                        render={({ field }) => (
                                            <InputField
                                                {...field}
                                                label="Site web"
                                                inputType="url"
                                                placeholder="https://..."
                                                error={errors.site_web?.message}
                                                leftIcon={<Globe className="w-4 h-4" />}
                                            />
                                        )}
                                    />
                                </div>
                            </Section>

                            <Section title="Adresse" icon={MapPin} defaultOpen={true}>
                                <Controller
                                    name="adresse"
                                    control={control}
                                    render={({ field }) => (
                                        <InputField
                                            {...field}
                                            label="Adresse"
                                            inputType="text"
                                            placeholder="Numéro et nom de rue"
                                        />
                                    )}
                                />
                                <Controller
                                    name="complement"
                                    control={control}
                                    render={({ field }) => (
                                        <InputField
                                            {...field}
                                            label="Complément"
                                            inputType="text"
                                            placeholder="Bâtiment, étage..."
                                        />
                                    )}
                                />
                                <div className="grid grid-cols-3 gap-4">
                                    <Controller
                                        name="code_postal"
                                        control={control}
                                        render={({ field }) => (
                                            <InputField
                                                {...field}
                                                label="Code postal"
                                                required
                                                inputType="postal_code"
                                                error={errors.code_postal?.message}
                                            />
                                        )}
                                    />
                                    <Controller
                                        name="ville"
                                        control={control}
                                        render={({ field }) => (
                                            <InputField
                                                {...field}
                                                label="Ville"
                                                required
                                                inputType="text"
                                                containerClassName="col-span-2"
                                            />
                                        )}
                                    />
                                </div>
                                <div className="grid grid-cols-2 gap-4">
                                    <Controller
                                        name="region"
                                        control={control}
                                        render={({ field }) => (
                                            <InputField
                                                {...field}
                                                label="Région"
                                                inputType="text"
                                            />
                                        )}
                                    />
                                    <Controller
                                        name="pays"
                                        control={control}
                                        render={({ field }) => (
                                            <InputField
                                                {...field}
                                                label="Pays"
                                                inputType="text"
                                            />
                                        )}
                                    />
                                </div>
                            </Section>

                            {est_entreprise && (
                                <Section title="Informations légales" icon={Building2} defaultOpen={false}>
                                    <div className="grid grid-cols-2 gap-4">
                                        <Controller
                                            name="siret"
                                            control={control}
                                            render={({ field }) => (
                                                <InputField
                                                    {...field}
                                                    label="SIRET"
                                                    inputType="siret"
                                                    placeholder="14 chiffres"
                                                    error={errors.siret?.message}
                                                />
                                            )}
                                        />
                                        <Controller
                                            name="siren"
                                            control={control}
                                            render={({ field }) => (
                                                <InputField
                                                    {...field}
                                                    label="SIREN"
                                                    inputType="siren"
                                                    placeholder="9 chiffres"
                                                    error={errors.siren?.message}
                                                />
                                            )}
                                        />
                                    </div>
                                    <div className="grid grid-cols-2 gap-4">
                                        <Controller
                                            name="tva_intra"
                                            control={control}
                                            render={({ field }) => (
                                                <InputField
                                                    {...field}
                                                    label="TVA Intracommunautaire"
                                                    inputType="tva_intra"
                                                    placeholder="FR12345678901"
                                                    error={errors.tva_intra?.message}
                                                />
                                            )}
                                        />
                                        <Controller
                                            name="code_naf"
                                            control={control}
                                            render={({ field }) => (
                                                <InputField
                                                    {...field}
                                                    label="Code NAF"
                                                    inputType="text"
                                                    placeholder="Ex: 6201Z"
                                                />
                                            )}
                                        />
                                    </div>
                                    <div className="grid grid-cols-2 gap-4">
                                        <Controller
                                            name="effectif"
                                            control={control}
                                            render={({ field }) => (
                                                <InputField
                                                    {...field}
                                                    value={field.value?.toString() || ""}
                                                    onChange={(e) => field.onChange(e.target.value ? parseInt(e.target.value) : null)}
                                                    label="Effectif"
                                                    as="select"
                                                    options={[
                                                        { value: "", label: "Sélectionner..." },
                                                        { value: "1", label: "1-10" },
                                                        { value: "10", label: "11-50" },
                                                        { value: "50", label: "51-200" },
                                                        { value: "200", label: "200+" },
                                                    ]}
                                                />
                                            )}
                                        />
                                        <Controller
                                            name="ca_annuel"
                                            control={control}
                                            render={({ field }) => (
                                                <InputField
                                                    {...field}
                                                    value={field.value?.toString() || ""}
                                                    onChange={(e) => field.onChange(e.target.value ? parseFloat(e.target.value) : null)}
                                                    label="CA annuel (€)"
                                                    inputType="number"
                                                    placeholder="0"
                                                />
                                            )}
                                        />
                                    </div>
                                </Section>
                            )}

                            <Section title="Commercial & Comptabilité" icon={CreditCard} defaultOpen={false}>
                                <div className="grid grid-cols-2 gap-4">
                                    <Controller
                                        name="commercial_nom"
                                        control={control}
                                        render={({ field }) => (
                                            <InputField
                                                {...field}
                                                label="Commercial"
                                                inputType="text"
                                                placeholder="Nom du commercial"
                                            />
                                        )}
                                    />
                                    <Controller
                                        name="commercial_code"
                                        control={control}
                                        render={({ field }) => (
                                            <InputField
                                                {...field}
                                                label="Code commercial"
                                                inputType="text"
                                            />
                                        )}
                                    />
                                </div>
                                <div className="grid grid-cols-2 gap-4">
                                    <Controller
                                        name="categorie_tarifaire"
                                        control={control}
                                        render={({ field }) => (
                                            <InputField
                                                {...field}
                                                value={field.value?.toString() || ""}
                                                label="Catégorie tarifaire"
                                                inputType="text"
                                            />
                                        )}
                                    />
                                    <Controller
                                        name="categorie_comptable"
                                        control={control}
                                        render={({ field }) => (
                                            <InputField
                                                {...field}
                                                value={field.value?.toString() || ""}
                                                label="Catégorie comptable"
                                                inputType="text"
                                            />
                                        )}
                                    />
                                </div>
                                <div className="grid grid-cols-2 gap-4">
                                    <Controller
                                        name="compte_general"
                                        control={control}
                                        render={({ field }) => (
                                            <InputField
                                                {...field}
                                                label="Compte général"
                                                inputType="text"
                                                placeholder="411000"
                                            />
                                        )}
                                    />
                                    <Controller
                                        name="encours_autorise"
                                        control={control}
                                        render={({ field }) => (
                                            <InputField
                                                {...field}
                                                value={field.value?.toString() || ""}
                                                onChange={(e) => field.onChange(parseFloat(e.target.value) || 0)}
                                                label="Encours autorisé (€)"
                                                inputType="number"
                                            />
                                        )}
                                    />
                                </div>
                            </Section>
                        </form>

                        {/* Footer */}
                        <div className="p-4 border-t border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-950 flex justify-end gap-3">
                            <button
                                type="button"
                                onClick={onClose}
                                className="px-4 py-2.5 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-xl transition-colors"
                            >
                                Annuler
                            </button>
                            <button
                                onClick={handleSubmit(onSave)}
                                disabled={!canSave || status === "loading"}
                                className="inline-flex items-center gap-2 px-6 py-2.5 bg-[#00D639] text-white text-sm font-medium rounded-xl hover:bg-[#7a1002] disabled:opacity-50 disabled:cursor-not-allowed transition-colors shadow-lg shadow-red-900/20"
                            >
                                {status === "loading" ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
                                {isEditing ? "Mettre à jour" : "Créer le client"}
                            </button>
                        </div>
                    </motion.div>
                    {error && (
                        <Alert severity="error" onClose={() => setError(null)} className="my-2">
                        {error}
                        </Alert>
                    )}
                </>
            )}
        </AnimatePresence>
    );
}