/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { DevisListItem, DevisRequest, DevisResponse, LigneDevis } from "@/types/devisType";
import FormModal, { FormSection, FormField, Input } from '@/components/ui/FormModal';
import { AlertTriangle, Package, PenLine, Plus, Trash2 } from "lucide-react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import ClientAutocomplete from "../molecules/ClientAutocomplete";
import { useEffect, useMemo, useState } from "react";
import { Client } from "@/types/clientType";
import ArticleAutocomplete from "../molecules/ArticleAutocomplete";
import { Article } from "@/types/articleType";
import { Alert, Divider } from "@mui/material";
import { createDevis, getDevisById, updateDevis } from "@/store/features/devis/thunk";
import { selectDevis } from "@/store/features/devis/slice";
import { useNavigate } from "react-router-dom";
import { toast } from "../ui/use-toast";
import { devisStatus } from "@/store/features/devis/selectors";
import { ModalLoading } from "./ModalLoading";
import { formatForDateInput, cn } from "@/lib/utils";
import { ModalArticle } from "./ModalArticle";
import { Tooltip, TooltipTrigger, TooltipProvider, TooltipContent } from "@/components/ui/tooltip";

// ============================================
// TYPES
// ============================================

interface LigneDevisForm extends LigneDevis {
    id: string;
    article?: Article | null;
    remiseValide?: boolean;
    isManual: boolean;
    designation?: string;
}

// Générer un ID unique
const generateLineId = () => `line_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

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

export function ModalQuote({
    open,
    onClose,
    title,
    editing,
    client
}: {
    open: boolean;
    onClose: () => void;
    title?: string;
    editing?: DevisListItem | null;
    client?: Client | null
}) {

    const navigate = useNavigate();
    const dispatch = useAppDispatch();
    const statusDevis = useAppSelector(devisStatus);

    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [success, setSuccess] = useState(false);

    // États pour le modal article
    const [isArticleModalOpen, setIsArticleModalOpen] = useState(false);
    const [currentLineId, setCurrentLineId] = useState<string | null>(null);
    const [activeLineId, setActiveLineId] = useState<string | null>(null);

    // Nouveaux champs
    const [dateEmission, setDateEmission] = useState(() => {
        const d = new Date()
        d.setDate(d.getDate() + 1);
        return d.toISOString().split("T")[0];
    });

    const [dateLivraison, setDateLivraison] = useState(() => {
        const d = new Date()
        d.setDate(d.getDate() + 8);
        return d.toISOString().split("T")[0];
    });

    const [validiteJours, setValiditeJours] = useState(30);
    const [referenceClient, setReferenceClient] = useState('');

    const [clientSelectionne, setClientSelectionne] = useState<Client | null>(client ?? null);

    const [lignes, setLignes] = useState<LigneDevisForm[]>([
        { id: generateLineId(), article_code: '', quantite: 1, remise_pourcentage: 0, article: null, remiseValide: true, isManual: false, designation: '' },
    ]);

    const isEditing = !!editing;

    // Initialiser le formulaire avec les données d'édition
    useEffect(() => {
        if (!open) return;

        if (editing) {
            setClientSelectionne({
                numero: editing.client_code,
                intitule: editing.client_intitule,
                compte_collectif: "",
                adresse: "",
                code_postal: "",
                ville: "",
                email: "",
                telephone: "",
            } as Client);

            const lignesInitiales: LigneDevisForm[] = editing.lignes.map(ligne => ({
                id: generateLineId(),
                article_code: ligne.article_code,
                quantite: ligne.quantite,
                prix_unitaire_ht: ligne.prix_unitaire_ht,
                remise_pourcentage: 0,
                article: ligne.article_code ? {
                    reference: ligne.article_code,
                    designation: ligne.designation,
                    prix_vente: ligne.prix_unitaire_ht,
                } as Article : null,
                remiseValide: true,
                isManual: !ligne.article_code,
                designation: ligne.designation || '',
            }));

            setLignes(lignesInitiales.length > 0 ? lignesInitiales : [
                { id: generateLineId(), article_code: '', quantite: 1, remise_pourcentage: 0, article: null, remiseValide: true, isManual: false, designation: '' }
            ]);

            if (editing.date) setDateEmission(editing.date);
            if (editing.date_livraison) setDateLivraison(editing.date_livraison);
            setReferenceClient(editing.reference || '');
        } else {
            if (!client) {
                setClientSelectionne(null);
            } else {
                setClientSelectionne(client);
            }
            setLignes([
                { id: generateLineId(), article_code: '', quantite: 1, remise_pourcentage: 0, article: null, remiseValide: true, isManual: false, designation: '' }
            ]);
            setDateEmission(new Date().toISOString().split('T')[0]);
            setDateLivraison(() => {
                const d = new Date()
                d.setDate(d.getDate() + 8);
                return d.toISOString().split("T")[0];
            });
            setReferenceClient('');
            setValiditeJours(30);
        }

        setError(null);
        setSuccess(false);
    }, [open, editing, client]);

    // Toggle mode Article/Libre
    const toggleLineMode = (lineId: string) => {
        setLignes(prev => prev.map(ligne => {
            if (ligne.id === lineId) {
                const newIsManual = !ligne.isManual;
                return {
                    ...ligne,
                    isManual: newIsManual,
                    article_code: newIsManual ? '' : ligne.article_code,
                    article: newIsManual ? null : ligne.article,
                    designation: '',
                    prix_unitaire_ht: newIsManual ? 0 : ligne.prix_unitaire_ht,
                };
            }
            return ligne;
        }));
    };

    const appliquerBareme = async (lineId: string, articleRef: string) => {
        if (!clientSelectionne) return;
        try {
            // Logique d'application du barème
        } catch (err) {
            console.error('Erreur application barème:', err);
        }
    };

    const ajouterLigne = () => {
        setLignes([
            ...lignes,
            { id: generateLineId(), article_code: '', quantite: 1, remise_pourcentage: 0, article: null, remiseValide: true, isManual: false, designation: '' },
        ]);
    };

    const supprimerLigne = (lineId: string) => {
        if (lignes.length > 1) {
            setLignes(lignes.filter(l => l.id !== lineId));
        }
    };

    const updateLigne = (lineId: string, field: keyof LigneDevisForm, value: any) => {
        setLignes(prev => prev.map(ligne => {
            if (ligne.id !== lineId) return ligne;

            if (field === 'article' && value) {
                const article = value as Article;
                if (clientSelectionne) {
                    appliquerBareme(lineId, article.reference);
                }
                return {
                    ...ligne,
                    article: article,
                    article_code: article.reference,
                    designation: article.designation,
                    prix_unitaire_ht: article.prix_vente,
                };
            } else if (field === 'article' && !value) {
                return {
                    ...ligne,
                    article: null,
                    article_code: '',
                    designation: '',
                    prix_unitaire_ht: 0,
                };
            } else {
                return { ...ligne, [field]: value };
            }
        }));
    };

    // Ouvrir le modal de création d'article
    const handleOpenArticleModal = (lineId: string) => {
        setCurrentLineId(lineId);
        setIsArticleModalOpen(true);
        setActiveLineId(null);
    };

    // Callback après création d'article
    const handleArticleCreated = (article: Article) => {
        if (currentLineId) {
            updateLigne(currentLineId, 'article', article);
            // Repasser en mode article catalogue
            setLignes(prev => prev.map(ligne => {
                if (ligne.id === currentLineId) {
                    return { ...ligne, isManual: false };
                }
                return ligne;
            }));
        }
        setIsArticleModalOpen(false);
        setCurrentLineId(null);
    };

    
    const calculerTotalLigne = (ligne: LigneDevisForm) => {
        const prix = ligne.prix_unitaire_ht || ligne.article?.prix_vente || 0;
        const montantBrut = prix * ligne.quantite;
        const remise = montantBrut * ((ligne.remise_pourcentage || 0) / 100);
        return montantBrut - remise;
    };

    const calculerTotal = () => {
        return lignes.reduce((total, ligne) => total + calculerTotalLigne(ligne), 0);
    };

    const toutesRemisesValides = () => {
        return lignes.every((ligne) => ligne.remiseValide !== false);
    };

    const canSave = useMemo(() => {
        if (!clientSelectionne) return false;
        // Accepter les lignes avec article OU les lignes manuelles avec désignation
        const lignesValides = lignes.filter((l) => l.article_code || (l.isManual && l.designation));
        if (lignesValides.length === 0) return false;
        if (!toutesRemisesValides()) return false;
        return true;
    }, [clientSelectionne, lignes]);

    const onSave = async () => {
        if (!clientSelectionne) {
            setError('Veuillez sélectionner un client');
            return;
        }

        const lignesValides = lignes.filter((l) => l.article_code || (l.isManual && l.designation));

        if (lignesValides.length === 0) {
            setError('Veuillez ajouter au moins un article ou une ligne');
            return;
        }

        if (!toutesRemisesValides()) {
            setError('Certaines remises ne sont pas autorisées. Veuillez les corriger.');
            return;
        }

        try {
            setLoading(true);
            setError(null);

            const lignesPayload = lignesValides.map((l) => ({
                article_code: l.article_code || 'DIVERS',
                quantite: l.quantite,
                remise_pourcentage: l.remise_pourcentage,
                // Ajouter la désignation pour les lignes manuelles
                ...(l.isManual && l.designation && { designation: l.designation })
            }));

            if (isEditing) {
                const payloadUpdate = {
                    client_id: clientSelectionne.numero,
                    date_devis: (() => {
                        const d = new Date(dateEmission);
                        d.setDate(d.getDate() + 1);
                        return d.toISOString().split("T")[0];
                    })(),
                    reference: referenceClient,
                    date_livraison: (() => {
                        const d = new Date(dateLivraison);
                        d.setDate(d.getDate() + 1);
                        return d.toISOString().split("T")[0];
                    })(),
                    lignes: lignesPayload,
                };

                const result = await dispatch(updateDevis({
                    numero: editing!.numero,
                    data: payloadUpdate
                })).unwrap() as any;

                const numero = result.devis.numero as any;

                setSuccess(true);
                toast({
                    title: "Devis mis à jour !",
                    description: `Le devis a été mis à jour avec succès.`,
                    className: "bg-green-500 text-white border-green-600"
                });

                await new Promise(resolve => setTimeout(resolve, 1500));

                const devisCreated = await dispatch(getDevisById(numero)).unwrap() as any;
                const res = devisCreated.data as DevisListItem;
                dispatch(selectDevis(res));

                setLoading(false);
                onClose();
                navigate(`/home/devis/${numero}`);

            } else {
                const payloadCreate: DevisRequest = {
                    client_id: clientSelectionne.numero,
                    date_devis: (() => {
                        const d = new Date(dateEmission);
                        d.setDate(d.getDate() + 1);
                        return d.toISOString().split("T")[0];
                    })(),
                    reference: referenceClient,
                    date_livraison: (() => {
                        const d = new Date(dateLivraison);
                        d.setDate(d.getDate() + 1);
                        return d.toISOString().split("T")[0];
                    })(),
                    lignes: lignesPayload,
                };

                const result = await dispatch(createDevis(payloadCreate)).unwrap() as DevisResponse;

                setSuccess(true);

                await new Promise(resolve => setTimeout(resolve, 1500));

                const devisCreated = await dispatch(getDevisById(result.id)).unwrap() as any;

                const res = devisCreated.data as DevisListItem;
                dispatch(selectDevis(res));

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

                setLoading(false);
                onClose();
                navigate(`/home/devis/${result.id}`);
            }

        } catch (err: any) {
            setError("Cet article n'est pas disponible pour ce client.");
            setLoading(false);
        }
    };

    const totalHT = calculerTotal();
    const totalTVA = totalHT * 0.20;
    const totalTTC = totalHT + totalTVA;
    const remisesNonAutorisees = lignes.filter((l) => l.remiseValide === false).length;
    const lignesValides = lignes.filter((l) => l.article_code || (l.isManual && l.designation)).length;

    if (!open) return null;

    return (
        <>
            <FormModal
                isOpen={open}
                onClose={onClose}
                title={title || (isEditing ? "Modifier le devis" : "Créer un devis")}
                size="xl"
                onSubmit={onSave}
                loading={statusDevis === "loading"}
            >
                {/* Section Client */}
                <FormSection title="Informations client" description="Sélectionnez le client et les coordonnées">
                    <FormField label="Client" required fullWidth>
                        <ClientAutocomplete
                            value={clientSelectionne}
                            onChange={setClientSelectionne}
                            required
                        />
                    </FormField>

                    <div className="col-span-1 md:col-span-2 grid grid-cols-1 md:grid-cols-3 gap-4 mt-4">
                        <FormField label="Date d'émission" required>
                            <Input
                                type="date"
                                value={formatForDateInput(dateEmission)}
                                onChange={(e) => setDateEmission(e.target.value)}
                            />
                        </FormField>
                        <FormField label="Date d'échéance" required>
                            <Input
                                type="date"
                                value={formatForDateInput(dateLivraison)}
                                onChange={(e) => setDateLivraison(e.target.value)}
                            />
                        </FormField>
                        <FormField label="Référence">
                            <Input
                                placeholder="Ex: REF-PROJET-123"
                                value={referenceClient}
                                onChange={(e) => setReferenceClient(e.target.value)}
                            />
                        </FormField>
                    </div>
                </FormSection>

                {/* Section Lignes */}
                <FormSection title="Lignes du devis" description="Ajoutez les produits et services">
                    <div className="col-span-2">
                        <div className="overflow-x-auto">
                            <table className="w-full mb-4">
                                <thead className="text-left bg-gray-50 dark:bg-gray-900/50 text-xs uppercase text-gray-500">
                                    <tr>
                                        <th className="px-2 py-3 w-10 text-center rounded-l-lg">Mode</th>
                                        <th className="px-4 py-3" style={{ width: '45%' }}>Article / Description</th>
                                        <th className="px-2 py-3 text-center" style={{ width: '70px' }}>Qté</th>
                                        <th className="px-2 py-3 text-right" style={{ width: '90px' }}>P.U. HT</th>
                                        <th className="px-2 py-3 text-right" style={{ width: '80px' }}>Remise</th>
                                        <th className="px-2 py-3 text-right" style={{ width: '90px' }}>Total HT</th>
                                        <th className="rounded-r-lg" style={{ width: '40px' }}></th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-gray-100 dark:divide-gray-800">
                                    {lignes.map((ligne) => (
                                        <tr key={ligne.id} className="group hover:bg-gray-50/50 dark:hover:bg-gray-900/20">
                                            {/* Mode Toggle */}
                                            <td className="px-2 py-2 align-middle">
                                                <TooltipProvider>
                                                    <Tooltip>
                                                        <TooltipTrigger asChild>
                                                            <button
                                                                type="button"
                                                                onClick={() => toggleLineMode(ligne.id)}
                                                                className={cn(
                                                                    "p-1.5 rounded-md transition-all duration-200",
                                                                    ligne.isManual
                                                                        ? "text-amber-600 bg-amber-50 hover:bg-amber-100"
                                                                        : "text-[#007E45] bg-green-50 hover:bg-green-100"
                                                                )}
                                                            >
                                                                {ligne.isManual ? (
                                                                    <PenLine className="w-4 h-4" />
                                                                ) : (
                                                                    <Package className="w-4 h-4" />
                                                                )}
                                                            </button>
                                                        </TooltipTrigger>
                                                        {/* <TooltipContent side="right">
                                                            <p>Mode: {ligne.isManual ? 'Saisie libre' : 'Article catalogue'}</p>
                                                            <p className="text-xs text-gray-400">Cliquer pour changer</p>
                                                        </TooltipContent> */}
                                                    </Tooltip>
                                                </TooltipProvider>
                                            </td>

                                            {/* Article / Désignation */}
                                            <td className="px-4 py-2 align-top">
                                                {ligne.isManual ? (
                                                    <div className="relative">
                                                        <input
                                                            type="text"
                                                            value={ligne.designation || ''}
                                                            onChange={(e) => updateLigne(ligne.id, 'designation', e.target.value)}
                                                            onFocus={() => setActiveLineId(ligne.id)}
                                                            onBlur={() => setTimeout(() => setActiveLineId(null), 200)}
                                                            className="w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#007E45]/20 focus:border-[#007E45]"
                                                            placeholder="Saisir une désignation..."
                                                        />

                                                        {/* Menu dropdown */}
                                                        {activeLineId === ligne.id && ligne.designation && (
                                                            <div className="overflow-hidden mt-1 w-full bg-white rounded-xl border border-gray-200 shadow-lg">
                                                                <button
                                                                    type="button"
                                                                    onMouseDown={(e) => e.preventDefault()}
                                                                    onClick={() => handleOpenArticleModal(ligne.id)}
                                                                    className="w-full px-4 py-3 flex items-center gap-3 hover:bg-green-50 transition-colors text-left"
                                                                >
                                                                    <div className="p-1.5 bg-[#007E45] rounded-lg text-white">
                                                                        <Plus className="w-4 h-4" />
                                                                    </div>
                                                                    <span className="text-sm font-medium text-gray-900">
                                                                        Créer l'article "<span className="text-[#007E45]">{ligne.designation}</span>"
                                                                    </span>
                                                                </button>
                                                                <div className="border-t border-gray-100" />
                                                                <div className="w-full py-2 text-xs text-gray-400 flex flex-row items-center justify-center gap-3 text-center">
                                                                    <PenLine className="w-4 h-4" />
                                                                    <span className="text-xs font-medium">Texte libre accepté</span>
                                                                </div>
                                                            </div>
                                                        )}
                                                    </div>
                                                ) : (
                                                    <ArticleAutocomplete
                                                        value={ligne.article!}
                                                        onChange={(article) => updateLigne(ligne.id, 'article', article)}
                                                        required
                                                    />
                                                )}
                                            </td>

                                            {/* Quantité */}
                                            <td className="px-2 py-2 align-top">
                                                <Input
                                                    type="number"
                                                    value={ligne.quantite}
                                                    onChange={(e) => updateLigne(ligne.id, 'quantite', parseFloat(e.target.value) || 0)}
                                                    min={0}
                                                    step={1}
                                                />
                                            </td>

                                            {/* Prix Unitaire HT */}
                                            <td className="px-2 py-2 align-top">
                                                <Input
                                                    type="number"
                                                    value={ligne.prix_unitaire_ht || ligne.article?.prix_vente || 0}
                                                    onChange={(e) => updateLigne(ligne.id, 'prix_unitaire_ht', parseFloat(e.target.value) || 0)}
                                                    min={0}
                                                    step={0.01}
                                                />
                                            </td>

                                            {/* Remise */}
                                            <td className="px-2 py-2 align-top">
                                                <Input
                                                    type="number"
                                                    value={ligne.remise_pourcentage || 0}
                                                    onChange={(e) => updateLigne(ligne.id, 'remise_pourcentage', parseFloat(e.target.value) || 0)}
                                                    min={0}
                                                    step={1}
                                                />
                                            </td>

                                            {/* Total HT */}
                                            <td className="px-2 py-3 text-right align-middle">
                                                <span className="font-semibold text-gray-900 dark:text-white text-sm">
                                                    {calculerTotalLigne(ligne).toFixed(2)} €
                                                </span>
                                            </td>

                                            {/* Bouton Supprimer */}
                                            <td className="px-1 py-3 text-center align-middle">
                                                <button
                                                    type="button"
                                                    onClick={() => supprimerLigne(ligne.id)}
                                                    disabled={lignes.length === 1}
                                                    className="p-1.5 text-gray-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors disabled:opacity-30 disabled:cursor-not-allowed opacity-0 group-hover:opacity-100"
                                                >
                                                    <Trash2 className="w-4 h-4" />
                                                </button>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>

                        <div className="flex justify-between items-start mt-4">
                            <button
                                type="button"
                                onClick={ajouterLigne}
                                className="text-sm text-[#007E45] font-medium hover:underline flex items-center gap-1"
                            >
                                <Plus className="w-4 h-4" /> Ajouter une ligne
                            </button>

                            {/* Récapitulatif */}
                            <div style={{ width: "42vh" }} className="w-72 bg-gray-50 dark:bg-gray-900 rounded-xl p-4 space-y-3">
                                <Divider className="!my-3" />
                                <div className="flex justify-between text-sm">
                                    <span className="text-gray-600 dark:text-gray-400">Total HT</span>
                                    <span className="font-medium text-gray-900 dark:text-white">{totalHT.toFixed(2)} €</span>
                                </div>
                                <div className="flex justify-between text-sm">
                                    <span className="text-gray-600 dark:text-gray-400">Taux TVA </span>
                                    <span className="font-medium text-gray-900 dark:text-white">20%</span>
                                </div>
                                <div className="pt-3 border-t border-gray-200 dark:border-gray-700 flex justify-between">
                                    <span className="font-bold text-gray-900 dark:text-white">Total TTC</span>
                                    <span className="font-bold text-[#007E45] text-lg">{totalTTC.toFixed(2)} €</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </FormSection>

                {/* Alertes */}
                {remisesNonAutorisees > 0 && (
                    <Alert severity="warning" icon={<AlertTriangle size={16} />} className="mb-4">
                        {remisesNonAutorisees} remise(s) non autorisée(s) à corriger
                    </Alert>
                )}

                {error && (
                    <Alert severity="error" className="mb-4">{error}</Alert>
                )}

                {loading && <ModalLoading />}
            </FormModal>

            {/* Modal création article */}
            <ModalArticle
                open={isArticleModalOpen}
                onClose={() => {
                    setIsArticleModalOpen(false);
                }}
                // defaultDesignation={currentLineId ? lignes.find(l => l.id === currentLineId)?.designation : undefined}
                // onArticleCreated={handleArticleCreated}
            />
        </>
    );
}