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 { mockProductFamilies } from '@/data/mockData';
import FormModal, { FormSection } from '@/components/ui/FormModal';
import { InputField } from "../ui/InputValidator";
import { Article, ArticleRequest, ArticleUpdateRequest } from '@/types/articleType';
import { Info, InfoIcon, Loader2, Save } from 'lucide-react';
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { articleStatus, getAllArticles } from "@/store/features/article/selectors";
import Button from '@mui/material/Button';
import { createArticle, getarticleById, updateArticle } from "@/store/features/article/thunk";
import { toast } from "../ui/use-toast";
import { selectArticle } from "@/store/features/article/slice";
import { useNavigate } from "react-router-dom";
import { getAllfamilles } from "@/store/features/famille/selectors";
import { Famille } from "@/types/familleType";
import { Alert } from "@mui/material";
import { Switch } from "../ui/switchTsx";

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

const articleSchema = z.object({
    reference: z.string()
    .min(1, "La référence est requise")
    .regex(
        /^[A-Za-z0-9]+$/, 
        "La référence ne peut contenir que des lettres et des chiffres"
    ),
    reference_client: z.string().optional(),
    designation: z.string().min(1, "Le libellé est requis"),
    designation_complementaire: z.string().optional(),
    famille_code: z.string().min(1, "La famille est requise"),
    est_actif: z.boolean().default(true),
    en_sommeil: z.boolean().default(false),
    description: z.string().optional(),
    code_ean: z
        .string()
        .regex(/^\d*$/, { message: 'Le code EAN doit contenir uniquement des chiffres' })
        .max(13, { message: 'Le code EAN ne doit pas dépasser 13 chiffres' })
        .optional(),
    prix_achat: z.coerce.number().min(0, "Le prix d'achat doit être positif").optional(),
    prix_vente: z.coerce.number().min(0, "Le prix de vente doit être positif"),
    tva_code: z.string().default("20"),
    unite_vente: z.string().default("pcs"),
    stock_reel: z.coerce.number().default(0),
    stock_mini: z.coerce.number().default(5),
    stock_maxi: z.coerce.number().optional(),
    poids: z.coerce.number().optional(),
    volume: z.coerce.number().optional(),
});

type ArticleFormData = z.infer<typeof articleSchema>;

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

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

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

export function ModalArticle({
    open,
    onClose,
    title,
    editing
}: ArticleFormModalProps) {
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [isStocked, setIsStocked] = useState(false);
    const isEditing = !!editing;
    const status = useAppSelector(articleStatus);
    const dispatch = useAppDispatch();
    const navigate = useNavigate();
    const articles = useAppSelector(getAllArticles) as Article[];
    const [error, setError] = useState<string | null>(null)

    const familles = useAppSelector(getAllfamilles) as Famille[]

    const {
        control,
        handleSubmit,
        watch,
        reset,
        formState: { errors, isValid }
    } = useForm<ArticleFormData>({
        resolver: zodResolver(articleSchema),
        mode: "onChange",
        defaultValues: {
            reference: "",
            reference_client: "",
            designation: "",
            designation_complementaire: "",
            famille_code: "",
            est_actif: true,
            en_sommeil: false,
            description: "",
            code_ean: "",
            prix_achat: 0,
            prix_vente: 0,
            tva_code: "20",
            unite_vente: "pcs",
            stock_reel: 0,
            stock_mini: 5,
            stock_maxi: undefined,
            poids: undefined,
            volume: undefined,
        }
    });

    const prixAchat = watch("prix_achat") || 0;
    const prixVente = watch("prix_vente") || 0;

    const marge = useMemo(() => {
        if (prixVente > 0 && prixAchat > 0) {
            const margeValue = ((prixVente - prixAchat) / prixVente) * 100;
            return margeValue.toFixed(2) + "%";
        }
        return "—";
    }, [prixAchat, prixVente]);

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

        if (editing) {
            reset({
                reference: editing.reference || "",
                reference_client: "",
                designation: editing.designation || "",
                designation_complementaire: editing.designation_complementaire || "",
                famille_code: editing.famille_code || "",
                est_actif: editing.est_actif ?? true,
                en_sommeil: editing.en_sommeil ?? false,
                description: editing.description || "",
                code_ean: editing.code_ean || "",
                prix_achat: editing.prix_achat || 0,
                prix_vente: editing.prix_vente || 0,
                tva_code: editing.tva_code || "20",
                unite_vente: editing.unite_vente || "pcs",
                stock_reel: editing.stock_reel || 0,
                stock_mini: editing.stock_mini || 5,
                stock_maxi: editing.stock_maxi,
                poids: editing.poids,
                volume: editing.volume,
            });
        } else {
            reset({
                reference: "",
                reference_client: "",
                designation: "",
                designation_complementaire: "",
                famille_code: "",
                est_actif: true,
                en_sommeil: false,
                description: "",
                code_ean: "",
                prix_achat: 0,
                prix_vente: 0,
                tva_code: "20",
                unite_vente: "pcs",
                stock_reel: 0,
                stock_mini: 5,
                stock_maxi: undefined,
                poids: undefined,
                volume: undefined,
            });
        }
    }, [open, editing, reset]);

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

        try {

            if(isEditing){
                const payload: ArticleUpdateRequest = {
                    designation: data.designation,
                    famille: data.famille_code,
                    prix_vente: Number(data.prix_vente),
                    prix_achat: Number(data.prix_achat ?? 0),
                    stock_maxi: Number(data.stock_maxi ?? 0),
                    stock_mini: Number(data.stock_mini ?? 0),
                    code_ean: data.code_ean || "",
                    description: data.description || "",
                    stock_reel: Number(data.stock_reel ?? 0),
                    publie: data.est_actif
                };

                const result = await dispatch(updateArticle({
                    reference: editing!.reference,
                    data: payload
                })).unwrap() as Article;

                await dispatch(getarticleById(result.reference)).unwrap() as any;

                toast({
                    title: "Article modifiée !",
                    description: `L'article ${data.reference} a été modifié avec succès.`,
                    className: "bg-green-500 text-white border-green-600"
                });
                
                await new Promise(resolve => setTimeout(resolve, 1500));

                dispatch(selectArticle(result)),
                onClose();
                navigate(`/home/articles/${result.reference.replace(/\//g, '')}`)
                
            }else{
                const payload: ArticleRequest = {
                    reference: data.reference,
                    designation: data.designation,
                    famille: data.famille_code,
                    prix_vente: Number(data.prix_vente),
                    prix_achat: Number(data.prix_achat ?? 0),
                    stock_maxi: Number(data.stock_maxi ?? 0),
                    stock_mini: Number(data.stock_mini ?? 0),
                    code_ean: data.code_ean || "",
                    description: data.description || "",
                    stock_reel: Number(data.stock_reel ?? 0)
                };
                const articleExist = articles.find(art => art.reference === payload.reference);
                if(articleExist){
                    setError(`Un article avec la référence "${payload.reference}" existe déjà.`);
                    setIsSubmitting(false);
                    return;
                }
                console.log("payload : ",payload);
                
                
                // TODO: Dispatch create/update action here
                const result = await dispatch(createArticle(payload)).unwrap() as Article

                await dispatch(getarticleById(result.reference)).unwrap() as any;
                
                toast({
                    title: "Article créé !",
                    description: `Un nouveau article a été créé avec succès.`,
                    className: "bg-green-500 text-white border-green-600"
                });
                
                await new Promise(resolve => setTimeout(resolve, 1500));
                
                dispatch(selectArticle(result)),
                onClose();
                navigate(`/home/articles/${result.reference.replace(/\//g, '')}`)
            }
            

        } 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 l'article" : "Créer un nouvel article")}
            size="xl"
            onSubmit={handleSubmit(onSave)}
            loading={ isSubmitting || status === "loading" ? true : false}
        >

                 {error && (
                    <Alert severity="error" onClose={() => setError(null)} className="my-2">
                    {error}
                    </Alert>
                )}
                {/* Section: Informations générales */}
                <FormSection
                    title="Identification"
                    description="Information de base"
                >
                    <div className="grid md: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: ART001"
                                    error={errors.reference?.message}
                                />
                            )}
                        />
                        <Controller
                            name="code_ean"
                            control={control}
                            render={({ field }) => (
                                <InputField
                                    {...field}
                                    label="Code EAN"
                                    inputType="text"
                                    maxLength={13}
                                    placeholder="Code-barres EAN13"
                                    error={errors.code_ean?.message}
                                />
                            )}
                        />
                    </div>

                    <div>
                        <Controller
                            name="designation"
                            control={control}
                            render={({ field }) => (
                                <InputField
                                    {...field}
                                    label="Libellé"
                                    inputType="text"
                                    required
                                    placeholder="Désignation du produit..."
                                    error={errors.designation?.message}
                                />
                            )}
                        />
                    </div>

                    <div className="grid md:grid-cols-2 gap-4">
                        <Controller
                            name="famille_code"
                            control={control}
                            render={({ field }) => (
                                <InputField
                                    {...field}
                                    label="Famille"
                                    as="select"
                                    required
                                    error={errors.famille_code?.message}
                                    options={[
                                        { value: "", label: "Sélectionner une famille..." },
                                        ...familles.filter(item => item.type_libelle ==="Détail").map(f => ({
                                            value: f.code,
                                            label: f.intitule
                                        }))
                                    ]}
                                />
                            )}
                        />
                        <Controller
                            name="est_actif"
                            control={control}
                            render={({ field }) => (
                                <InputField
                                    {...field}
                                    value={field.value ? "active" : "inactive"}
                                    onChange={(e) => field.onChange(e.target.value === "active")}
                                    label="Statut"
                                    as="select"
                                    options={[
                                        { value: "active", label: "Actif" },
                                        { value: "inactive", label: "Inactif" },
                                    ]}
                                />
                            )}
                        />
                    </div>

                    <Controller
                        name="description"
                        control={control}
                        render={({ field }) => (
                            <InputField
                                {...field}
                                label="Description"
                                inputType="text"
                                placeholder="Description commerciale..."
                                containerClassName="col-span-2"
                            />
                        )}
                    />
                </FormSection> 
                
                {/* Section: Logistique & Stock */}
                <FormSection title="Gestion des Stocks (Sage 100)" description="Paramètres logistiques stricts">
                    <div className="flex items-center justify-between p-4 bg-gray-50 dark:bg-gray-900 rounded-lg border border-gray-200 dark:border-gray-800 mb-6">
                        <div className="flex items-center gap-3">
                            <div className="p-2 bg-white dark:bg-gray-800 rounded shadow-sm">
                                <InfoIcon className="w-5 h-5 text-[#338660]" />
                            </div>
                            <div>
                                <span className="font-bold text-gray-900 dark:text-white block">Article géré en stock ?</span>
                                <span className="text-xs text-gray-500">Active le suivi des mouvements et la valorisation</span>
                            </div>
                        </div>
                        <Switch checked={isStocked} onCheckedChange={setIsStocked} />
                    </div>

                    {isStocked && (
                        <div className="space-y-4 animate-in fade-in slide-in-from-top-2 duration-300">

                            <div className="grid grid-cols-3 gap-4 pt-2">
                                 <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 actuel"
                                            inputType="number"
                                            error={errors.stock_reel?.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}
                                        />
                                    )}
                                />
                                <Controller
                                    name="poids"
                                    control={control}
                                    render={({ field }) => (
                                        <InputField
                                            {...field}
                                            value={field.value?.toString() || ""}
                                            onChange={(e) => field.onChange(parseFloat(e.target.value) || undefined)}
                                            label="Poids (kg)"
                                            inputType="number"
                                            placeholder="0.00"
                                        />
                                    )}
                                />
                            </div>
                        </div>
                    )}
                </FormSection>
                {/* <FormSection
                    title="Logistique & Stock"
                    description="Gestion des stocks"
                >
                    <div className="grid grid-cols-2 gap-4">
                        <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³" },
                                    ]}
                                />
                            )}
                        />
                        <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 actuel"
                                    inputType="number"
                                    error={errors.stock_reel?.message}
                                />
                            )}
                        />
                    </div>

                    <div className="grid grid-cols-2 gap-4">
                        <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}
                                />
                            )}
                        />
                        <Controller
                            name="poids"
                            control={control}
                            render={({ field }) => (
                                <InputField
                                    {...field}
                                    value={field.value?.toString() || ""}
                                    onChange={(e) => field.onChange(parseFloat(e.target.value) || undefined)}
                                    label="Poids (kg)"
                                    inputType="number"
                                    placeholder="0.00"
                                />
                            )}
                        />
                    </div>
                </FormSection> */}

                {/* Section: Tarification */}
                <FormSection
                    title="Tarification"
                    description="Prix et marges"
                >
                    <div className="grid grid-cols-2 gap-4">
                        <Controller
                            name="prix_achat"
                            control={control}
                            render={({ field }) => (
                                <InputField
                                    {...field}
                                    value={field.value?.toString() || ""}
                                    onChange={(e) => field.onChange(parseFloat(e.target.value) || 0)}
                                    label="Prix d'achat HT (€)"
                                    inputType="number"
                                    placeholder="0.00"
                                    error={errors.prix_achat?.message}
                                />
                            )}
                        />
                        <Controller
                            name="prix_vente"
                            control={control}
                            render={({ field }) => (
                                <InputField
                                    {...field}
                                    value={field.value?.toString() || ""}
                                    onChange={(e) => field.onChange(parseFloat(e.target.value) || 0)}
                                    label="Prix de vente HT (€)"
                                    inputType="number"
                                    required
                                    placeholder="0.00"
                                    error={errors.prix_vente?.message}
                                />
                            )}
                        />
                    </div>

                    <div className="grid grid-cols-2 gap-4">
                        <Controller
                            name="tva_code"
                            control={control}
                            render={({ field }) => (
                                <InputField
                                    {...field}
                                    label="Taux TVA"
                                    as="select"
                                    options={[
                                        { value: "20", label: "20%" },
                                        { value: "10", label: "10%" },
                                        { value: "5.5", label: "5.5%" },
                                        { value: "0", label: "0%" },
                                    ]}
                                />
                            )}
                        />
                        <InputField
                            label="Marge théorique"
                            inputType="text"
                            value={marge}
                            disabled
                            className="bg-gray-50 dark:bg-gray-800"
                        />
                    </div>
                </FormSection>

               
               
        </FormModal>
    );
}