import { useEffect, useMemo, useState } from "react";
import { useForm, Controller, type SubmitHandler } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import z from "zod";
import FormModal, { FormField, FormSection, Select } from '@/components/ui/FormModal';
import { InputField } from "../ui/InputValidator";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { articleStatus } from "@/store/features/article/selectors";
import { useNavigate } from "react-router-dom";
import { getAllfamilles } from "@/store/features/famille/selectors";
import { Famille, FamilleRequest } from "@/types/familleType";
import { createFamille } from "@/store/features/famille/thunk";
import { selectfamille } from "@/store/features/famille/slice";
import { toast } from "../ui/use-toast";
import { Alert } from "@mui/material";

// ============================================
// SCHÉMA DE VALIDATION ZOD
// ============================================

const itemSchema = z.object({
    code: z.string().min(1, "La code est requise"),
    intitule: z.string().min(1, "L'intitule est requise"),
    compte_achat: z.string().optional(),
    compte_vente: z.string().optional(),
    unite_vente: z.string().default("pcs"),
});

type ItemFormData = z.infer<typeof itemSchema>;

// ============================================
// INTERFACE PROPS
// ============================================

interface FormModalProps {
    open: boolean;
    onClose: () => void;
    title?: string;
    editing?: Famille | null;
}

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

export function ModalFamille({
    open,
    onClose,
    title,
    editing
}: FormModalProps) {
    const [isSubmitting, setIsSubmitting] = useState(false);
    const isEditing = !!editing;
    const status = useAppSelector(articleStatus);
    const dispatch = useAppDispatch();
    const navigate = useNavigate();
    const [error, setError] = useState<string | null>(null)

    const familles = useAppSelector(getAllfamilles) as Famille[];
    
    const {
        control,
        handleSubmit,
        watch,
        reset,
        formState: { errors, isValid }
    } = useForm<ItemFormData>({
        resolver: zodResolver(itemSchema),
        mode: "onChange",
        defaultValues: {
            code: "",
            intitule: "",
            compte_achat: "",
            compte_vente: "",
        }
    });


    useEffect(() => {
        if (!open) return;
        setIsSubmitting(false);

        if (editing) {
            reset({
                code: editing.code || "",
                intitule: editing.intitule || "",
                compte_achat: editing.compte_achat || "",
                compte_vente: editing.compte_vente || "",
            });
        } else {
            reset({
                code: "",
                intitule: "",
                compte_achat: "",
                compte_vente: "",
            });
        }
    }, [open, editing, reset]);

    // ✅ Fonction de soumission
    const onSave: SubmitHandler<ItemFormData> = async (data) => {
        setError('')
        setIsSubmitting(true);

        try {

            if(isEditing){
                const payload: FamilleRequest = {
                    code: data.code,
                    intitule: data.intitule,
                    compte_achat: data.compte_achat || "",
                    compte_vente: data.compte_vente || "",
                    type: 0
                };

                console.log("payload update: ",payload)
                
                
            }else{
                const payload: FamilleRequest = {
                    code: data.code,
                    intitule: data.intitule,
                    compte_achat: data.compte_achat || "",
                    compte_vente: data.compte_vente || "",
                    type: 0
                };
                const familleExist = familles.findIndex((item) => item.code === payload.code)
                if(familleExist !== -1){
                    console.log("ato");
                    
                    setError("Une famille avec ce code existe déjà.")
                    setIsSubmitting(false);
                    return;
                }
                const result = await dispatch(createFamille(payload)).unwrap() as Famille
                dispatch(selectfamille(result))

                toast({
                    title: "Famille d'article bien créée !",
                    description: `Une nouvelle famille d'article ${result.code} a été créée avec succès.`,
                    className: "bg-green-500 text-white border-green-600"
                });

                navigate(`/home/familles-articles/${result.code}`)
                
            }
            

        } catch (error) {
            setError("Une erreur est survenue lors de la sauvegarde.");
            console.error("Erreur lors de la sauvegarde:", error);
        } finally {
            setIsSubmitting(false);
        }
    };
    
    // ✅ Vérifier si le formulaire peut être soumis
    const canSave = isValid && !isSubmitting && status !== "loading";

    if (!open) return null;

    return (
        <FormModal
            isOpen={open}
            onClose={onClose}
            title={title || (isEditing ? `Modifier ${editing.code} famille` : "Nouvelle famille d'article")}
            size="xl"
            onSubmit={handleSubmit(onSave)}
            loading={ isSubmitting || status === "loading" ? true : false}
        >
               
                {/* Section: Informations générales */}
                <FormSection title="Informations générales" description="Identification de la famille">
                    <div className="grid grid-cols-2 gap-4">
                        <Controller
                            name="code"
                            control={control}
                            render={({ field }) => (
                                <InputField
                                    {...field}
                                    label="Code famille"
                                    inputType="text"
                                    required
                                    disabled={isEditing}
                                    placeholder="Ex: FAM001"
                                    error={errors.code?.message}
                                />
                            )}
                        />
                        <Controller
                            name="intitule"
                            control={control}
                            render={({ field }) => (
                                <InputField
                                    {...field}
                                    label="Intitulé"
                                    inputType="text"
                                    placeholder="Ex: Ordinateur"
                                    error={errors.intitule?.message}
                                />
                            )}
                        />
                    </div>
                </FormSection>

                {/* Section: regle par défault */}
                <FormSection title="Règles par défaut" description="Appliquées aux nouveaux articles">
                    <div className="grid grid-cols-1 gap-4">
                        <FormField label="Taux TVA par défaut">
                            <Select defaultValue="20">
                                <option value="20">20%</option>
                                <option value="10">10%</option>
                                <option value="5.5">5.5%</option>
                                <option value="0">0%</option>
                            </Select>
                        </FormField>
                        <Controller
                            name="compte_vente"
                            control={control}
                            render={({ field }) => (
                                <InputField
                                    {...field}
                                    value={field.value?.toString() || ""}
                                    label="Compte comptable vente"
                                    inputType="text"
                                    required
                                    placeholder="707..."
                                    error={errors.compte_vente?.message}
                                />
                            )}
                        />
                    </div>

                    <div className="grid grid-cols-1 gap-4">
                        <Controller
                            name="compte_achat"
                            control={control}
                            render={({ field }) => (
                                <InputField
                                    {...field}
                                    value={field.value?.toString() || ""}
                                    label="Compte comptable achat"
                                    inputType="text"
                                    required
                                    placeholder="404..."
                                    error={errors.compte_achat?.message}
                                />
                            )}
                        />
                        <Controller
                            name="unite_vente"
                            control={control}
                            render={({ field }) => (
                                <InputField
                                    {...field}
                                    label="Unité"
                                    as="select"
                                    options={[
                                        { value: "pcs", label: "Pièce" },
                                        { value: "h", label: "Heure" },
                                        { value: "kg", label: "Kg" },
                                        { value: "l", label: "Litre" },
                                        { value: "m", label: "Mètre" },
                                        { value: "m2", label: "M²" },
                                        { value: "m3", label: "M³" },
                                    ]}
                                />
                            )}
                        />
                    </div>

                    
                   
                </FormSection>
                 {error && (
                    <Alert severity="error" onClose={() => setError(null)} className="my-2">
                    {error}
                    </Alert>
                )}
        </FormModal>
    );
}