import { useState, useMemo, useEffect } from "react";
import { Helmet } from "react-helmet";
import { useNavigate } from "react-router-dom";
import {
   ArrowLeft,
   FileText,
   Eye,
   File,
   Trash2,
   CircleDot,
   Plus,
   X,
   Check,
   Loader2,
   Settings,
} from "lucide-react";
import FormModal, {
   FormField,
   Input,
   RepresentantInput,
   Textarea,
} from "@/components/ui/FormModal";
import { toast } from "@/components/ui/use-toast";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import {
   cn,
   formatDateFR,
   formatDateFRCourt,
   formatForDateInput,
} from "@/lib/utils";
import { getBLSelected, BLStatus } from "@/store/features/bl/selectors";
import { BL, BLRequest } from "@/types/BL_Types";
import { blToFacture, getBL, updateBL } from "@/store/features/bl/thunk";
import { ModalLoading } from "@/components/modal/ModalLoading";
import { getFacture } from "@/store/features/factures/thunk";
import Tabs from "@/components/Tabs";
import PDFPreview from "@/components/modal/PDFPreview";
import {
   PDFActionButtons,
   usePDFPreview,
} from "@/components/ui/PDFActionButtons";
import { CompanyInfo } from "@/data/mockData";
import { getAllClients } from "@/store/features/client/selectors";
import { Client } from "@/types/clientType";
import { Facture } from "@/types/factureType";
import { Article } from "@/types/articleType";
import { selectClient } from "@/store/features/client/slice";
import Timeline from "@/components/Timeline";
import { ActionButton } from "@/components/ribbons/ActionButton";
import { selectfacture } from "@/store/features/factures/slice";
import { selectBL } from "@/store/features/bl/slice";
import StatusBadge from "@/components/ui/StatusBadge";
import ModalStatus from "@/components/modal/ModalStatus";
import ClientAutocomplete from "@/components/molecules/ClientAutocomplete";
import ArticleAutocomplete from "@/components/molecules/ArticleAutocomplete";

export interface LigneForm {
   article_code: string;
   quantite: number;
   prix_unitaire_ht: number;
   taux_taxe1: number;
   montant_ligne_ht: number;
   remise_pourcentage: number;
   designation: string;
   articles: Article | null;
}

const DeliveryNotesDetailPage = () => {
   const { showPreview, openPreview, closePreview } = usePDFPreview();
   const clients = useAppSelector(getAllClients) as Client[];
   const statusBL = useAppSelector(BLStatus);

   const navigate = useNavigate();
   const dispatch = useAppDispatch();

   // États pour la transformation en facture
   const [loadingTransform, setLoadingTransform] = useState(false);
   const [transforming, setTransforming] = useState(false);
   const [error, setError] = useState<string | null>(null);
   const [isTransformOpen, setIsTransformOpen] = useState(false);

   // États UI
   const [activeTab, setActiveTab] = useState("identification");
   const [openStatus, setOpenStatus] = useState(false);

   // États pour l'édition inline
   const [isEditing, setIsEditing] = useState(false);
   const [isSaving, setIsSaving] = useState(false);

   // États des champs éditables
   const [editDate, setEditDate] = useState("");
   const [editDateLivraison, setEditDateLivraison] = useState("");
   const [editReference, setEditReference] = useState("");
   const [editClient, setEditClient] = useState<Client | null>(null);
   const [editLignes, setEditLignes] = useState<LigneForm[]>([]);
   const [editCommentaire, setEditCommentaire] = useState("");

   const bl = useAppSelector(getBLSelected) as BL;

   // Initialiser les valeurs d'édition quand le BL change ou quand on entre en mode édition
   useEffect(() => {
      if (bl && isEditing) {
         setEditDate(bl.date || "");
         setEditDateLivraison(bl.date_livraison || "");
         setEditReference(bl.reference || "");

         const clientFound = clients.find((c) => c.numero === bl.client_code);
         setEditClient(
            clientFound ||
            ({
               numero: bl.client_code,
               intitule: bl.client_intitule,
               compte_collectif: "",
               adresse: "",
               code_postal: "",
               ville: "",
               email: "",
               telephone: "",
            } as Client)
         );

         const lignesInitiales: LigneForm[] =
            bl.lignes?.map((ligne) => ({
               article_code: ligne.article_code,
               quantite: ligne.quantite,
               prix_unitaire_ht: ligne.prix_unitaire_ht ?? 0,
               total_taxes: ligne.montant_taxe1 ?? 0,
               taux_taxe1: ligne.taux_taxe1 ?? 0,
               montant_ligne_ht: ligne.montant_ligne_ht ?? 0,
               remise_pourcentage: ligne.remise_pourcentage ?? 0,
               designation: ligne.designation ?? "",
               articles: {
                  reference: ligne.article_code,
                  designation: ligne.designation ?? "",
                  prix_vente: ligne.prix_unitaire_ht ?? 0,
                  stock_reel: 0,
               } as Article,
            })) ?? [];

         setEditLignes(
            lignesInitiales.length > 0
               ? lignesInitiales
               : [
                  {
                     article_code: "",
                     quantite: 1,
                     prix_unitaire_ht: 0,
                     designation: "",
                     taux_taxe1: 0,
                     montant_ligne_ht: 0,
                     remise_pourcentage: 0,
                     articles: null,
                  },
               ]
         );

         setEditCommentaire(
            "Commande urgente, merci de vérifier le conditionnement."
         );
      }
   }, [bl, isEditing, clients]);

   if (!bl) return <div>Bon de livraison introuvable</div>;

   const totalPoidsNet =
      bl.lignes?.reduce((total, ligne) => total + (ligne.poids_net ?? 0), 0) ?? 0;
   const totalPoidsBrut =
      bl.lignes?.reduce((total, ligne) => total + (ligne.poids_brut ?? 0), 0) ??
      0;

   const client = clients.find((item) => item.numero === bl.client_code);

   const calculerTotalLigne = (ligne: LigneForm) => {
      const prix = ligne.prix_unitaire_ht || ligne.articles?.prix_vente || 0;
      const remise = ligne.remise_pourcentage ?? 0;
      const prixRemise = prix * (1 - remise / 100);
      return prixRemise * ligne.quantite;
   };

   const calculerTotalTva = () => {
      const taxesParLignes = editLignes.reduce((total, ligne) => {
         const totalHtLigne = calculerTotalLigne(ligne);
         const tva = totalHtLigne * (ligne.taux_taxe1 / 100);
         return total + tva;
      }, 0);

      const valeur_frais = bl.valeur_frais;
      return taxesParLignes + valeur_frais * (bl.taxes1 ?? 0.2);
   };

   const calculerTotalHT = () => {
      const total_ligne = editLignes.map((ligne) => calculerTotalLigne(ligne));
      const totalHTLigne = total_ligne.reduce((acc, ligne) => acc + ligne, 0);
      const totalHtNet = totalHTLigne + bl.valeur_frais;
      return totalHtNet;
   };

   const editTotalHT = calculerTotalHT();
   const editTotalTVA = calculerTotalTva();
   const editTotalTTC = editTotalHT + editTotalTVA;

   // Gestion des lignes
   const ajouterLigne = () => {
      setEditLignes([
         ...editLignes,
         {
            article_code: "",
            quantite: 1,
            prix_unitaire_ht: 0,
            designation: "",
            taux_taxe1: 0,
            montant_ligne_ht: 0,
            remise_pourcentage: 0,
            articles: null,
         },
      ]);
   };

   const supprimerLigne = (index: number) => {
      if (editLignes.length > 1) {
         setEditLignes(editLignes.filter((_, i) => i !== index));
      }
   };

   const updateLigne = (index: number, field: keyof LigneForm, value: any) => {
      const nouvelles = [...editLignes];

      if (field === "articles" && value) {
         const article = value as Article;
         nouvelles[index] = {
            ...nouvelles[index],
            articles: article,
            article_code: article.reference,
            designation: article.designation,
            prix_unitaire_ht: article.prix_vente,
         };
      } else if (field === "articles" && !value) {
         nouvelles[index] = {
            ...nouvelles[index],
            articles: null,
            article_code: "",
            designation: "",
            prix_unitaire_ht: 0,
         };
      } else {
         (nouvelles[index] as any)[field] = value;
      }

      setEditLignes(nouvelles);
   };

   // Validation
   const canSave = useMemo(() => {
      if (!editClient) return false;
      const lignesValides = editLignes.filter((l) => l.article_code);
      return lignesValides.length > 0;
   }, [editClient, editLignes]);

   // Gestion de l'édition
   const handleStartEdit = () => {
      setIsEditing(true);
   };

   const handleCancelEdit = () => {
      setIsEditing(false);
      setError(null);
   };

   const handleSaveEdit = async () => {
      if (!editClient) {
         setError("Veuillez sélectionner un client");
         return;
      }

      const lignesValides = editLignes.filter((l) => l.article_code);
      if (lignesValides.length === 0) {
         setError("Veuillez ajouter au moins un article");
         return;
      }

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

         const payloadUpdate = {
            client_id: editClient.numero,
            date_livraison: editDateLivraison,
            reference: editReference,
            lignes: lignesValides.map((l) => ({
               article_code: l.article_code,
               quantite: l.quantite,
            })),
         };

         await dispatch(
            updateBL({
               numero: bl.numero,
               data: payloadUpdate,
            })
         ).unwrap();

         toast({
            title: "BL mis à jour !",
            description: `Le bon de livraison ${bl.numero} a été mis à jour avec succès.`,
            className: "bg-green-500 text-white border-green-600",
         });

         // Recharger le BL
         const itemUpdated = (await dispatch(getBL(bl.numero)).unwrap()) as BL;
         dispatch(selectBL(itemUpdated));

         setIsEditing(false);
      } catch (err: any) {
         setError(err.message || "Erreur lors de la mise à jour");
         toast({
            title: "Erreur",
            description: "Impossible de mettre à jour le bon de livraison.",
            className: "bg-red-500 text-white border-red-600",
         });
      } finally {
         setIsSaving(false);
      }
   };

   // Transformer les données pour le composant PDFPreview
   const pdfData = {
      numero: bl.numero,
      type: "bl" as const,
      date: bl.date,
      client: {
         code: bl.client_code,
         nom: bl.client_intitule,
         adresse: client?.adresse,
         code_postal: client?.code_postal,
         ville: client?.ville,
         email: client?.email,
         telephone: client?.telephone,
      },
      reference_externe: bl.reference,
      lignes: bl.lignes!.map((l) => ({
         article: l.article_code,
         designation: l.designation,
         quantite: l.quantite,
         prix_unitaire: l.prix_unitaire_ht,
         tva: 20,
         total_ht: l.quantite * l.prix_unitaire_ht!,
      })),
      total_ht: bl.total_ht_calcule,
      total_tva: bl.total_taxes_calcule,
      total_ttc: bl.total_ttc_calcule,
   };

   const handleCreateFacture = async () => {
      setIsTransformOpen(false);
      try {
         setTransforming(true);
         setLoadingTransform(true);
         setError(null);

         const response = await dispatch(blToFacture(bl!.numero)).unwrap();
         const res = (await dispatch(
            getFacture(response.document_cible)
         ).unwrap()) as Facture;
         dispatch(selectfacture(res));
         setLoadingTransform(false);

         toast({
            title: "Facture générée avec succès!",
            description: `Le BL ${bl.numero} a été transformé en facture.`,
            className: "bg-green-500 text-white border-green-600",
         });
         setTimeout(() => navigate(`/home/factures/${res.numero}`), 1000);
      } catch (err: any) {
         setError(err.message);
         setIsTransformOpen(false);
         setLoadingTransform(false);
         toast({
            title: "Impossible de transformer le BL",
            description: `Le BL ${bl.numero} ne peut pas être transformé en facture.`,
            className: "bg-red-500 text-white border-red-600",
         });
      } finally {
         setTransforming(false);
         setLoadingTransform(false);
      }
   };

   const timeline = [
      {
         type: "bl" as const,
         title: "Bon de livraison créé",
         description: `${bl.numero} pour ${bl.total_ttc.toLocaleString("fr-FR")}€`,
         date: bl.date,
         user: bl.statut,
         link: `/home/bons-livraison/${bl.numero}`,
         item: bl,
      },
   ];

   const tabs = [
      { id: "identification", label: "Identification" },
      { id: "lines", label: "Lignes de livraison" },
      { id: "totals", label: "Totaux" },
      { id: "documents", label: "Documents", count: bl.lignes?.length },
      { id: "timeline", label: "Timeline", count: bl.lignes?.length },
   ];

   return (
      <>
         <Helmet>
            <title>{bl.numero} - Bon de livraison</title>
         </Helmet>

         <div className="space-y-6">
            {/* Header */}
            <div className="sticky top-0 z-30 bg-white border-b border-gray-200 shadow-sm dark:bg-gray-950 dark:border-gray-800">
               <div className="px-4 mx-auto max-w-7xl sm:px-6 lg:px-8">
                  <div className="flex justify-between items-center h-16">
                     <div className="flex gap-4 items-center">
                        <button
                           onClick={() => navigate("/home/bons-livraison")}
                           aria-label="Go back to delivery notes"
                           className="p-2 text-gray-500 rounded-full transition-colors hover:bg-gray-100 dark:hover:bg-gray-800"
                           disabled={isEditing}
                        >
                           <ArrowLeft className="w-5 h-5" />
                        </button>
                        <div>
                           <div className="flex gap-3 items-center">
                              <h1 className="text-xl font-bold text-gray-900 dark:text-white">
                                 {bl.numero}
                              </h1>
                              <StatusBadge status={bl.statut} type_doc={30} />
                              {isEditing && (
                                 <span className="px-2 py-1 text-xs font-medium text-amber-800 bg-amber-100 rounded-full">
                                    Mode édition
                                 </span>
                              )}
                           </div>
                           <div className="flex gap-2 items-center text-sm text-gray-500">
                              {bl.client_intitule ? (
                                 <span
                                    className={cn(
                                       "font-medium text-gray-900 dark:text-gray-300",
                                       !isEditing && "cursor-pointer hover:underline"
                                    )}
                                    onClick={() => {
                                       if (isEditing) return;
                                       const clientSelected = clients.find(
                                          (item) => item.numero === bl.client_code
                                       );
                                       if (clientSelected) {
                                          dispatch(selectClient(clientSelected));
                                          navigate(`/home/clients/${bl.client_code}`);
                                       }
                                    }}
                                 >
                                    {bl.client_intitule}
                                 </span>
                              ) : (
                                 <span className="italic text-gray-400">
                                    Client non défini
                                 </span>
                              )}
                              <span>•</span>
                              <span>{formatDateFR(bl.date)}</span>
                           </div>
                        </div>
                     </div>

                     <div className="flex gap-2 items-center">
                        {isEditing ? (
                           <>
                              <button
                                 onClick={handleCancelEdit}
                                 disabled={isSaving}
                                 className="flex gap-2 items-center px-4 py-2 text-sm font-medium text-gray-600 rounded-xl border border-gray-200 transition-colors hover:text-gray-900 dark:text-gray-400 dark:hover:text-white dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800 disabled:opacity-50"
                              >
                                 <X className="w-4 h-4" />
                                 Annuler
                              </button>
                              <button
                                 onClick={handleSaveEdit}
                                 disabled={!canSave || isSaving}
                                 className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-[#007E45] hover:bg-[#006837] rounded-xl transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                              >
                                 {isSaving ? (
                                    <Loader2 className="w-4 h-4 animate-spin" />
                                 ) : (
                                    <Check className="w-4 h-4" />
                                 )}
                                 Enregistrer
                              </button>
                           </>
                        ) : (
                           <>
                              <ActionButton
                                 icon={Eye}
                                 label="Aperçu"
                                 onClick={openPreview}
                              />
                              <button
                                 onClick={handleStartEdit}
                                 className="px-4 py-2 text-sm font-medium text-gray-600 rounded-xl border border-gray-200 transition-colors hover:text-gray-900 dark:text-gray-400 dark:hover:text-white dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800"
                              >
                                 Modifier
                              </button>

                              {bl.statut === 2 ? (
                                 <button
                                    onClick={() => setIsTransformOpen(true)}
                                    style={{
                                       backgroundColor: "#f0fdfa",
                                       color: "#115e59",
                                       border: "1px solid #99f6e4",
                                    }}
                                    className="flex gap-2 items-center px-3 py-2 text-sm font-medium rounded-xl transition-colors hover:bg-teal-100"
                                 >
                                    <FileText className="w-4 h-4" /> Transformer en Facture
                                 </button>
                              ) : (
                                 <button
                                    onClick={() => setOpenStatus(true)}
                                    className="flex gap-2 items-center px-3 py-2 text-sm font-medium text-gray-700 bg-white rounded-xl border border-gray-200 transition-colors hover:bg-gray-50"
                                    title="Changer le statut"
                                 >
                                    <Settings className="w-4 h-4 text-gray-500" />
                                    <span className="hidden lg:inline">
                                       Changer le statut
                                    </span>
                                 </button>
                              )}
                           </>
                        )}
                     </div>
                  </div>
               </div>
            </div>

            {/* Tabs & Content */}
            <div className="px-4 mx-auto mt-6 w-full max-w-7xl sm:px-6 lg:px-8">
               <Tabs tabs={tabs} active={activeTab} onChange={setActiveTab} />

               <div className="mt-6">
                  {/* --- IDENTIFICATION TAB --- */}
                  {activeTab === "identification" && (
                     <div className="space-y-6">
                        <div className="overflow-hidden relative p-6 bg-white rounded-2xl border border-gray-200 dark:bg-gray-950 dark:border-gray-800">
                           <h3 className="mb-4 text-lg font-bold text-gray-900 dark:text-white">
                              Informations Générales
                           </h3>
                           <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
                              <FormField label="Client" required>
                                 {isEditing ? (
                                    <ClientAutocomplete
                                       value={editClient}
                                       onChange={setEditClient}
                                       required
                                    />
                                 ) : (
                                    <Input
                                       type="text"
                                       value={bl.client_code}
                                       disabled
                                       className="bg-gray-50 opacity-50 cursor-not-allowed dark:bg-gray-900"
                                    />
                                 )}
                              </FormField>

                              <div className="grid grid-cols-2 gap-4">
                                 <FormField label="Date de livraison" required>
                                    <Input
                                       type="date"
                                       value={
                                          isEditing
                                             ? formatForDateInput(editDateLivraison)
                                             : formatForDateInput(bl.date_livraison)
                                       }
                                       onChange={(e) =>
                                          isEditing && setEditDateLivraison(e.target.value)
                                       }
                                       disabled={!isEditing}
                                       className={cn(
                                          !isEditing &&
                                          "opacity-50 cursor-not-allowed bg-gray-50 dark:bg-gray-900"
                                       )}
                                    />
                                 </FormField>
                              </div>

                              <FormField label="Référence externe">
                                 <Input
                                    value={isEditing ? editReference : bl.reference || ""}
                                    onChange={(e) =>
                                       isEditing && setEditReference(e.target.value)
                                    }
                                    disabled={!isEditing}
                                    placeholder="Bon de commande client..."
                                    className={cn(
                                       !isEditing &&
                                       "opacity-50 cursor-not-allowed bg-gray-50 dark:bg-gray-900"
                                    )}
                                 />
                              </FormField>

                              <FormField label="Affaire / Deal">
                                 <Input
                                    value="__"
                                    disabled
                                    className="bg-gray-50 opacity-50 cursor-not-allowed dark:bg-gray-900"
                                 />
                              </FormField>

                              <RepresentantInput />

                              <FormField label="Commentaires" fullWidth>
                                 <Textarea
                                    rows={3}
                                    value={
                                       isEditing
                                          ? editCommentaire
                                          : "Commande urgente, merci de vérifier le conditionnement."
                                    }
                                    onChange={(e) =>
                                       isEditing && setEditCommentaire(e.target.value)
                                    }
                                    disabled={!isEditing}
                                    placeholder="Instructions spécifiques..."
                                    className={cn(
                                       !isEditing &&
                                       "opacity-50 cursor-not-allowed bg-gray-50 dark:bg-gray-900"
                                    )}
                                 />
                              </FormField>
                           </div>
                        </div>
                     </div>
                  )}

                  {/* --- LINES TAB --- */}
                  {activeTab === "lines" && (
                     <div className="p-6 bg-white rounded-2xl border border-gray-200 shadow-sm dark:bg-gray-950 dark:border-gray-800">
                        <div className="overflow-x-auto min-h-[200px] mb-8">
                           <table className="w-full">
                              <thead className="text-xs font-semibold tracking-wider text-left text-gray-500 uppercase bg-gray-50 dark:bg-gray-900/50">
                                 <tr>
                                    <th className="px-4 py-3 rounded-l-lg w-[35%]">
                                       Article / Description
                                    </th>
                                    <th className="px-4 py-3 text-right w-[10%]">Qté</th>
                                    <th className="px-4 py-3 text-right w-[12%]">
                                       P.U. HT
                                    </th>
                                    <th className="px-4 py-3 text-right w-[10%]">Remise</th>
                                    <th className="px-4 py-3 text-right w-[8%]">TVA</th>
                                    <th className="px-4 py-3 text-right w-[15%] rounded-r-lg">
                                       Total HT
                                    </th>
                                    {isEditing && <th className="w-[5%]"></th>}
                                 </tr>
                              </thead>
                              <tbody className="divide-y divide-gray-100 dark:divide-gray-800">
                                 {isEditing ? (
                                    editLignes.map((item, i) => (
                                       <tr
                                          key={i}
                                          className="group hover:bg-gray-50/50 dark:hover:bg-gray-900/20"
                                       >
                                          <td
                                             className="px-4 py-3"
                                             style={{ minWidth: "300px" }}
                                          >
                                             <ArticleAutocomplete
                                                value={item.articles}
                                                onChange={(article) =>
                                                   updateLigne(i, "articles", article)
                                                }
                                                required
                                             />
                                          </td>
                                          <td
                                             className="px-4 py-3"
                                             style={{ width: "100px" }}
                                          >
                                             <input
                                                type="number"
                                                value={item.quantite}
                                                onChange={(e) =>
                                                   updateLigne(
                                                      i,
                                                      "quantite",
                                                      parseFloat(e.target.value) || 0
                                                   )
                                                }
                                                min={0}
                                                step={1}
                                                className="w-full text-center px-2 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-[#007E45] focus:border-transparent"
                                             />
                                          </td>
                                          <td
                                             className="px-4 py-3"
                                             style={{ width: "120px" }}
                                          >
                                             <input
                                                type="number"
                                                value={
                                                   item.prix_unitaire_ht ||
                                                   item.articles?.prix_vente ||
                                                   0
                                                }
                                                onChange={(e) =>
                                                   updateLigne(
                                                      i,
                                                      "prix_unitaire_ht",
                                                      parseFloat(e.target.value) || 0
                                                   )
                                                }
                                                min={0}
                                                step={0.01}
                                                className="w-full text-right px-2 py-2 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-[#007E45] focus:border-transparent"
                                             />
                                          </td>
                                          <td className="px-4 py-3 text-sm text-right text-gray-600">
                                             0%
                                          </td>
                                          <td className="px-4 py-3 text-sm text-right text-gray-600">
                                             20%
                                          </td>
                                          <td className="px-4 py-3 font-mono font-bold text-right">
                                             {calculerTotalLigne(item).toFixed(2)} €
                                          </td>
                                          <td className="px-1 py-3 text-center">
                                             <button
                                                onClick={() => supprimerLigne(i)}
                                                disabled={editLignes.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"
                                             >
                                                <Trash2 className="w-4 h-4" />
                                             </button>
                                          </td>
                                       </tr>
                                    ))
                                 ) : bl.lignes ? (
                                    bl.lignes.map((item, i) => (
                                       <tr
                                          key={i}
                                          className="group hover:bg-gray-50/50 dark:hover:bg-gray-900/20"
                                       >
                                          <td className="px-4 py-3 pt-5 font-mono text-sm font-bold align-top">
                                             {item.article_code}
                                             {item.designation && (
                                                <div className="mt-1 text-xs text-gray-400">
                                                   {item.designation}
                                                </div>
                                             )}
                                          </td>
                                          <td
                                             className="px-4 py-3 pt-5 font-mono text-sm font-bold text-right align-top"
                                             style={{ width: "15vh" }}
                                          >
                                             <Input
                                                type="number"
                                                value={item.quantite}
                                                disabled
                                                className="font-mono text-right bg-gray-50 opacity-50 cursor-not-allowed dark:bg-gray-900"
                                             />
                                          </td>
                                          <td
                                             className="px-4 py-3 pt-5 font-mono text-sm font-bold text-right align-top"
                                             style={{ width: "15vh" }}
                                          >
                                             <Input
                                                type="number"
                                                value={item.prix_unitaire_ht}
                                                disabled
                                                className="font-mono text-right bg-gray-50 opacity-50 cursor-not-allowed dark:bg-gray-900"
                                             />
                                          </td>
                                          <td
                                             className="px-4 py-3 pt-5 font-mono text-sm font-bold text-right align-top"
                                             style={{ width: "15vh" }}
                                          >
                                             <Input
                                                type="text"
                                                value="0%"
                                                disabled
                                                className="font-mono text-right bg-gray-50 opacity-50 cursor-not-allowed dark:bg-gray-900"
                                             />
                                          </td>
                                          <td className="px-4 py-3 pt-5 text-sm text-right text-gray-600 align-top">
                                             20%
                                          </td>
                                          <td className="px-4 py-3 pt-5 font-mono font-bold text-right align-top">
                                             {item.montant_ligne_ht} €
                                          </td>
                                       </tr>
                                    ))
                                 ) : (
                                    <tr>
                                       <td
                                          colSpan={6}
                                          className="py-4 text-center text-gray-500"
                                       >
                                          Aucune ligne
                                       </td>
                                    </tr>
                                 )}
                              </tbody>
                           </table>
                        </div>

                        {/* Bouton ajouter ligne en mode édition */}
                        {isEditing && (
                           <div className="mb-6">
                              <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>
                           </div>
                        )}

                        {/* Totals Block */}
                        <div className="flex justify-end">
                           <div
                              style={{ width: "42vh" }}
                              className="p-6 space-y-3 bg-gray-50 rounded-xl border border-gray-100 lg:w-96 dark:bg-gray-900/50 dark:border-gray-800"
                           >
                              <div className="flex justify-between text-sm">
                                 <span className="text-gray-500 dark:text-gray-400">
                                    Total HT
                                 </span>
                                 <span className="font-mono font-semibold text-gray-900 dark:text-white">
                                    {isEditing
                                       ? editTotalHT.toLocaleString()
                                       : bl.total_ht_calcule.toLocaleString()}
                                    €
                                 </span>
                              </div>
                              <div className="flex justify-between text-sm">
                                 <span className="text-gray-500 dark:text-gray-400">
                                    Total TVA
                                 </span>
                                 <span className="font-mono font-semibold text-gray-900 dark:text-white">
                                    {isEditing
                                       ? editTotalTVA.toLocaleString()
                                       : bl.total_taxes_calcule.toLocaleString()}
                                    €
                                 </span>
                              </div>
                              <div className="my-2 h-px bg-gray-200 dark:bg-gray-700" />
                              <div className="flex justify-between text-lg font-bold">
                                 <span className="text-gray-900 dark:text-white">
                                    Net à payer
                                 </span>
                                 <span className="text-[#007E45] font-mono">
                                    {isEditing
                                       ? editTotalTTC.toLocaleString()
                                       : bl.total_ht_net.toLocaleString()}
                                    €
                                 </span>
                              </div>
                           </div>
                        </div>

                        {/* Message d'erreur */}
                        {error && isEditing && (
                           <div className="p-4 mt-4 text-sm text-red-800 bg-red-50 rounded-xl border border-red-200">
                              {error}
                           </div>
                        )}
                     </div>
                  )}

                  {/* --- TOTALS TAB --- */}
                  {activeTab === "totals" && (
                     <div className="grid grid-cols-1 gap-8 md:grid-cols-2">
                        <div className="p-6 bg-white rounded-2xl border border-gray-200 shadow-sm dark:bg-gray-950 dark:border-gray-800 h-fit">
                           <h3 className="mb-4 text-lg font-bold text-gray-900 dark:text-white">
                              Poids & Colisage
                           </h3>
                           <div className="space-y-4">
                              <div className="flex justify-between text-sm">
                                 <span className="text-gray-600 dark:text-gray-400">
                                    Poids Net Estimé
                                 </span>
                                 <span className="text-sm font-medium text-gray-900 dark:text-white">
                                    {totalPoidsNet || 0} kg
                                 </span>
                              </div>
                              <div className="flex justify-between text-sm">
                                 <span className="text-gray-600 dark:text-gray-400">
                                    Poids Brut Estimé
                                 </span>
                                 <span className="text-sm font-medium text-gray-900 dark:text-white">
                                    {totalPoidsBrut || 0} kg
                                 </span>
                              </div>
                              <div className="my-2 h-px bg-gray-100 dark:bg-gray-800"></div>
                              <div className="flex justify-between text-sm">
                                 <span className="text-gray-600 dark:text-gray-400">
                                    Nombre de lignes
                                 </span>
                                 <span className="text-sm font-medium text-gray-900 dark:text-white">
                                    {bl.lignes?.length}
                                 </span>
                              </div>
                           </div>
                        </div>
                     </div>
                  )}

                  {/* --- DOCUMENTS TAB --- */}
                  {activeTab === "documents" && (
                     <div className="space-y-6">
                        <div className="p-12 text-center bg-white rounded-2xl border border-gray-200 border-dashed transition-colors cursor-pointer dark:bg-gray-950 dark:border-gray-800 hover:bg-gray-50 dark:hover:bg-gray-900">
                           <File className="mx-auto mb-4 w-12 h-12 text-gray-300" />
                           <p className="text-sm font-medium text-gray-600 dark:text-gray-400">
                              Glissez-déposez vos fichiers ici
                           </p>
                        </div>

                        <div className="overflow-hidden bg-white rounded-2xl border border-gray-200 shadow-sm dark:bg-gray-950 dark:border-gray-800">
                           <table className="w-full">
                              <thead className="bg-gray-50 border-b border-gray-200 dark:bg-gray-900 dark:border-gray-800">
                                 <tr className="text-xs font-semibold text-left text-gray-500 uppercase">
                                    <th className="px-6 py-3">Fichier</th>
                                    <th className="px-6 py-3">Type</th>
                                    <th className="px-6 py-3">Date</th>
                                    <th className="px-6 py-3 text-right">Actions</th>
                                 </tr>
                              </thead>
                              <tbody className="divide-y divide-gray-100 dark:divide-gray-800">
                                 <tr className="hover:bg-gray-50 dark:hover:bg-gray-900/50">
                                    <td className="flex gap-3 items-center px-6 py-4 text-sm">
                                       <FileText className="w-5 h-5 text-[#007E45]" />
                                       <span className="font-medium text-gray-900 dark:text-white">
                                          BL_{bl.numero}
                                       </span>
                                    </td>
                                    <td className="px-6 py-4 text-sm text-gray-500">PDF</td>
                                    <td className="px-6 py-4 text-sm text-gray-500">
                                       {formatDateFRCourt(bl.date)}
                                    </td>
                                    <td className="px-6 py-4 text-right">
                                       <button className="mr-4 text-sm font-medium text-blue-600 hover:underline">
                                          Télécharger
                                       </button>
                                       <button className="text-[#007E45] hover:text-red-700">
                                          <Trash2 className="w-4 h-4" />
                                       </button>
                                    </td>
                                 </tr>
                              </tbody>
                           </table>
                        </div>
                     </div>
                  )}

                  {activeTab === "timeline" && <Timeline events={timeline} />}
               </div>
            </div>
         </div>

         <ModalStatus
            open={openStatus}
            onClose={() => setOpenStatus(false)}
            type_doc={30}
         />

         <FormModal
            isOpen={isTransformOpen}
            onClose={() => setIsTransformOpen(false)}
            title="Transformer en Facture"
            onSubmit={handleCreateFacture}
            size="xl"
            submitLabel="Créer facture"
         >
            <div
               style={{
                  marginBottom: "1.5rem",
                  padding: "1rem",
                  backgroundColor: "#f0fdfa",
                  color: "#115e59",
                  borderRadius: "0.75rem",
                  fontSize: "0.875rem",
                  display: "flex",
                  gap: "0.75rem",
                  border: "1px solid #99f6e4",
               }}
            >
               <FileText className="w-5 h-5 shrink-0" />
               <div>
                  <p className="mb-1 font-bold">Transformation du BL {bl.numero}</p>
                  <p className="text-sm">
                     Veuillez vérifier les quantités à facturer. Par défaut, le
                     logiciel propose le reliquat non facturé (Mode B).
                  </p>
               </div>
            </div>
            <div className="overflow-hidden mb-6 bg-white rounded-xl border border-gray-200 dark:bg-gray-950 dark:border-gray-800">
               <table className="w-full text-sm">
                  <thead className="bg-gray-50 border-b border-gray-200 dark:bg-gray-900 dark:border-gray-800">
                     <tr>
                        <th className="px-4 py-3 font-semibold text-left text-gray-600">
                           Article
                        </th>
                        <th className="px-4 py-3 font-semibold text-right text-gray-600">
                           Qté BL
                        </th>
                        <th className="px-4 py-3 font-semibold text-right text-gray-600">
                           Déjà Fact.
                        </th>
                        <th className="px-4 py-3 font-semibold text-right text-gray-600">
                           Reste
                        </th>
                        <th className="px-4 py-3 text-right font-semibold text-[#007E45]">
                           À Facturer
                        </th>
                        <th className="px-4 py-3 font-semibold text-right text-gray-600">
                           Total HT
                        </th>
                     </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-100 dark:divide-gray-800">
                     {bl?.lignes ? (
                        bl?.lignes.map((item, i) => (
                           <tr key={i} className="hover:bg-gray-50/50">
                              <td className="px-4 py-3">
                                 <div className="font-medium text-gray-900 dark:text-white">
                                    {item.designation}
                                 </div>
                                 <div className="text-xs text-gray-500">
                                    {item.article_code}
                                 </div>
                              </td>
                              <td className="px-4 py-3 text-right text-gray-600">
                                 {item.quantite}
                              </td>
                              <td className="px-4 py-3 text-right text-gray-600">0</td>
                              <td className="px-4 py-3 font-medium text-right text-gray-900">
                                 {item.montant_ligne_ht}
                              </td>
                              <td className="px-4 py-3 w-32 text-right">
                                 <input
                                    type="number"
                                    min="0"
                                    value={item.montant_ligne_ht}
                                    className={cn(
                                       "w-full text-right px-2 py-1 border rounded focus:ring-2 focus:ring-[#007E45] outline-none transition-colors",
                                       "border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900"
                                    )}
                                 />
                              </td>
                              <td className="px-4 py-3 font-medium text-right text-gray-900 dark:text-white">
                                 {item.montant_ligne_ht!.toLocaleString(undefined, {
                                    minimumFractionDigits: 2,
                                    maximumFractionDigits: 2,
                                 })}{" "}
                                 €
                              </td>
                           </tr>
                        ))
                     ) : (
                        <tr>
                           <td colSpan={6} className="py-4 text-center text-gray-500">
                              Aucune ligne
                           </td>
                        </tr>
                     )}
                  </tbody>
                  <tfoot className="bg-gray-50 border-t border-gray-200 dark:bg-gray-900 dark:border-gray-800">
                     <tr>
                        <td
                           colSpan={5}
                           className="px-4 py-3 font-bold text-right text-gray-900 dark:text-white"
                        >
                           Total HT à générer
                        </td>
                        <td className="px-4 py-3 text-right font-bold text-[#007E45]">
                           {bl?.total_ht_calcule.toFixed(2)} €
                        </td>
                     </tr>
                  </tfoot>
               </table>
            </div>
         </FormModal>

         {loadingTransform && <ModalLoading />}
         {isSaving && <ModalLoading />}

         <PDFPreview
            open={showPreview}
            onClose={closePreview}
            data={pdfData}
            entreprise={CompanyInfo}
         />
      </>
   );
};

export default DeliveryNotesDetailPage;
