import { useEffect, useState } from "react";
import { useForm, Controller, type SubmitHandler } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import z from "zod";
import FormModal, { FormSection } from '@/components/ui/FormModal';
import { InputField } from "../ui/InputValidator";
import { Article, StockRequest } from '@/types/articleType';
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { articleStatus } from "@/store/features/article/selectors";
import { addStock } from "@/store/features/article/thunk";
import { toast } from "../ui/use-toast";
import { useNavigate } from "react-router-dom";
import { getAllfamilles } from "@/store/features/famille/selectors";
import { Famille } from "@/types/familleType";

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

const articleSchema = z.object({
    reference: z.string().min(1, "La référence est requise"),
    stock_reel: z.coerce.number().default(0),
    stock_mini: z.coerce.number().default(5),
    stock_maxi: z.coerce.number().default(10),
});

type ArticleFormData = z.infer<typeof articleSchema>;

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

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

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

export function ModalStock({
    open,
    onClose,
    title,
    editing
}: ArticleFormModalProps) {
    const [isSubmitting, setIsSubmitting] = useState(false);
    const isEditing = !!editing;
    const status = useAppSelector(articleStatus);
    const dispatch = useAppDispatch();
    const navigate = useNavigate();

    const {
        control,
        handleSubmit,
        watch,
        reset,
        formState: { errors, isValid }
    } = useForm<ArticleFormData>({
        resolver: zodResolver(articleSchema),
        mode: "onChange", // ✅ Validation en temps réel pour activer/désactiver le bouton
        defaultValues: {
            reference: "",
            stock_reel: 0,
            stock_mini: 5,
            stock_maxi: 10,
        }
    });

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

        if (editing) {
            reset({
                reference: editing.reference || "",
                stock_reel: 0,
                stock_mini: editing.stock_mini || 5,
                stock_maxi: editing.stock_maxi || 10,
            });
        } else {
            reset({
                reference: "",
                stock_reel: 0,
                stock_mini: 5,
                stock_maxi: 10
            });
        }
    }, [open, editing, reset]);

    // ✅ Fonction de soumission
    const onSave: SubmitHandler<ArticleFormData> = async (data) => {
        setIsSubmitting(true);
        console.log("ato");
        
        try {

            if(isEditing){
                 const payload: StockRequest = {
                    commentaire: "",
                    date_entree: (() => {
                        const d = new Date();
                        d.setDate(d.getDate() + 1);
                        return d.toISOString().split("T")[0];
                    })(),
                    lignes: [
                        {
                            article_ref: data.reference,
                            quantite: data.stock_reel,
                            stock_mini: data.stock_mini,
                            stock_maxi: data.stock_maxi 
                        }
                    ],
                    reference:""
                };
                
                await dispatch(addStock(payload)).unwrap() 
                
                toast({
                    title: "Stock bien ajouté!",
                    description: `Le stock de votre article a été bien modifié.`,
                    className: "bg-green-500 text-white border-green-600"
                });
                
                await new Promise(resolve => setTimeout(resolve, 1500));
                
                onClose();
                
            }
            

        } catch (error) {
            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 l'article" : "Créer un nouvel article")}
            size="md"
            onSubmit={handleSubmit(onSave)}
            loading={ isSubmitting || status === "loading" ? true : false}
        >
                {/* Section: Informations générales */}
                <FormSection
                    title="Informations générales"
                    description="Identification du produit"
                >
                    <div className="grid grid-cols-2 gap-4">
                        <Controller
                            name="reference"
                            control={control}
                            render={({ field }) => (
                                <InputField
                                    {...field}
                                    label="Référence"
                                    inputType="text"
                                    required
                                    disabled={isEditing}
                                    placeholder="Ex: ART-2025-001"
                                    error={errors.reference?.message}
                                />
                            )}
                        />
                    </div>
                </FormSection>
                {/* Section: Logistique & Stock */}
                <FormSection
                    title="Logistique & Stock"
                    description="Gestion des stocks"
                >
                    <div className="grid grid-cols-2 gap-4">
                        <Controller
                            name="stock_reel"
                            control={control}
                            render={({ field }) => (
                                <InputField
                                    {...field}
                                    value={editing?.stock_reel}
                                    label="Stock actuel"
                                    disabled={isEditing}
                                    inputType="number"
                                />
                            )}
                        />
                         <Controller
                            name="stock_reel"
                            control={control}
                            render={({ field }) => (
                                <InputField
                                    {...field}
                                    value={field.value?.toString() || "0"}
                                    onChange={(e) => field.onChange(parseInt(e.target.value) || 0)}
                                    label="Stock ajouté"
                                    inputType="number"
                                    error={errors.stock_reel?.message}
                                />
                            )}
                        />
                    </div>
                     <div className="grid grid-cols-2 gap-4">
                        <Controller
                            name="stock_maxi"
                            control={control}
                            render={({ field }) => (
                                <InputField
                                    {...field}
                                    value={field.value?.toString() || "10"}
                                    onChange={(e) => field.onChange(parseInt(e.target.value) || 0)}
                                    label="Stock maximum"
                                    inputType="number"
                                    error={errors.stock_maxi?.message}
                                />
                            )}
                        />
                        <Controller
                            name="stock_mini"
                            control={control}
                            render={({ field }) => (
                                <InputField
                                    {...field}
                                    value={field.value?.toString() || "5"}
                                    onChange={(e) => field.onChange(parseInt(e.target.value) || 0)}
                                    label="Stock minimum"
                                    inputType="number"
                                    error={errors.stock_mini?.message}
                                />
                            )}
                        />
                    </div>
                </FormSection>

        </FormModal>
    );
}