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, InputType, validators } from "../ui/InputValidator";
import { Article, ArticleRequest } from '@/types/articleType';
import { Euro, Warehouse } from 'lucide-react';

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

const articleSchema = z.object({
    // Informations générales
    reference: z.string().min(1, "La référence est requise"),
    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().optional(),

    // Tarification
    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"),

    // Logistique & Stock
    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 ArticleFormModal({
    open,
    onClose,
    title,
    editing
}: ArticleFormModalProps) {
    const [isSubmitting, setIsSubmitting] = useState(false);
    const isEditing = !!editing;

    const {
        control,
        handleSubmit,
        watch,
        reset,
        formState: { errors }
    } = useForm<ArticleFormData>({
        resolver: zodResolver(articleSchema),
        mode: "onBlur",
        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 formValues = watch();
    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;

        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]);


    const handleFormSubmit: SubmitHandler<ArticleFormData> = async (data) => {
        setIsSubmitting(true);

        try {
            const payload: ArticleRequest = {
                reference: data.reference,
                designation: data.designation,
                famille: data.famille_code,
                prix_vente: data.prix_vente.toString(),
                prix_achat: (data.prix_achat || 0).toString(),
                stock_reel: data.stock_reel.toString(),
                stock_mini: data.stock_mini.toString(),
                code_ean: data.code_ean || "",
                unite_vente: data.unite_vente,
                tva_code: data.tva_code,
                description: data.description || "",
            };
            console.log("payload : ",payload);
            
            onClose();

        } catch (error) {
            console.error("Erreur lors de la sauvegarde:", error);
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <FormModal
            isOpen={open}
            onClose={onClose}
            title={title || (isEditing ? "Modifier l'article" : "Créer un nouvel article")}
            size="xl"
            submitLabel={isEditing ? "Mettre à jour" : "Créer l'article"}
        >
            {/* 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}
                            />
                        )}
                    />
                    <Controller
                        name="code_ean"
                        control={control}
                        render={({ field }) => (
                            <InputField
                                {...field}
                                label="Code EAN"
                                inputType="text"
                                placeholder="Code-barres EAN13"
                                error={errors.code_ean?.message}
                            />
                        )}
                    />
                </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 className="grid 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..." },
                                    ...mockProductFamilies.map(f => ({
                                        value: f.id,
                                        label: f.name
                                    }))
                                ]}
                            />
                        )}
                    /> */}
                    <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: 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>

            {/* Section: Logistique & Stock */}
            <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>
        </FormModal>
    );
}