import React, { useState, useMemo, useCallback } from "react";
import { Helmet } from "react-helmet";
import { useNavigate } from "react-router-dom";
import {
   ArrowLeft,
   Save,
   Loader2,
   Plus,
   Trash2,
   PenLine,
   Package,
   Lock,
   EyeOff,
   AlertTriangle,
} from "lucide-react";
import { toast } from "@/components/ui/use-toast";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { FactureRequest } from "@/types/factureType";
import { createFacture, getFacture } from "@/store/features/factures/thunk";
import { ModalLoading } from "@/components/modal/ModalLoading";
import { cn, formatForDateInput } from "@/lib/utils";
import { getAllClients } from "@/store/features/client/selectors";
import { Client } from "@/types/clientType";
import { Article } from "@/types/articleType";
import { selectfacture } from "@/store/features/factures/slice";
import { ModalArticle } from "@/components/modal/ModalArticle";
import { getuserConnected } from "@/store/features/user/selectors";
import { UserInterface } from "@/types/userInterface";
import ClientAutocomplete from "@/components/molecules/ClientAutocomplete";
import ArticleAutocomplete from "@/components/molecules/ArticleAutocomplete";
import StatusBadge from "@/components/ui/StatusBadge";
import { Input, Textarea } from "@/components/ui/FormModal";
import { Tooltip, TooltipTrigger, TooltipProvider } from "@/components/ui/tooltip";
import StickyTotals from "@/components/document-entry/StickyTotals";

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

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

export interface Note {
   publique: string;
   prive: string;
}

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

// Créer une ligne vide
const createEmptyLine = (): LigneForm => ({
   id: generateLineId(),
   article_code: "",
   quantite: 1,
   prix_unitaire_ht: 0,
   total_taxes: 0,
   taux_taxe1: 20,
   montant_ligne_ht: 0,
   remise_pourcentage: 0,
   designation: "",
   articles: null,
   isManual: false,
});

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

const InvoiceCreatePage = () => {
   const navigate = useNavigate();
   const dispatch = useAppDispatch();

   const clients = useAppSelector(getAllClients) as Client[];
   const userConnected = useAppSelector(getuserConnected) as UserInterface;

   // États UI
   const [isSaving, setIsSaving] = useState(false);
   const [error, setError] = useState<string | null>(null);

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

   // États des champs éditables
   const [editDateFacture, setEditDateFacture] = useState(() => {
      const d = new Date();
      d.setDate(d.getDate() + 1);
      return d.toISOString().split("T")[0];
   });
   const [editDateEcheance, setEditDateEcheance] = useState(() => {
      const d = new Date();
      d.setDate(d.getDate() + 31); // Échéance à 30 jours
      return d.toISOString().split("T")[0];
   });
   const [editReference, setEditReference] = useState("");
   const [editClient, setEditClient] = useState<Client | null>(null);
   const [editLignes, setEditLignes] = useState<LigneForm[]>([createEmptyLine()]);

   // Notes
   const [note, setNote] = useState<Note>({
      publique: "Paiement à 30 jours fin de mois",
      prive: "",
   });

   const [description, setDescription] = useState<string | null>(null);

   // ============================================
   // VÉRIFIER SI LA DERNIÈRE LIGNE EST VIDE
   // ============================================

   const isLastLineEmpty = useCallback((lignes: LigneForm[]) => {
      if (lignes.length === 0) return false;
      const lastLine = lignes[lignes.length - 1];
      
      if (lastLine.isManual) {
         return !lastLine.designation || lastLine.designation.trim() === "";
      }
      return !lastLine.article_code;
   }, []);

   // ============================================
   // AJOUTER UNE LIGNE SI NÉCESSAIRE
   // ============================================

   const addLineIfNeeded = useCallback((currentLignes: LigneForm[], updatedLineId: string) => {
      const lastLine = currentLignes[currentLignes.length - 1];
      
      if (lastLine && lastLine.id === updatedLineId) {
         const isLineFilled = lastLine.isManual 
            ? lastLine.designation && lastLine.designation.trim() !== ""
            : lastLine.article_code !== "";
         
         if (isLineFilled) {
            return [...currentLignes, createEmptyLine()];
         }
      }
      
      return currentLignes;
   }, []);

   // ============================================
   // CALCULS
   // ============================================

   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 calculerTotalHT = () => {
      return editLignes.reduce((acc, ligne) => acc + calculerTotalLigne(ligne), 0);
   };

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

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

   // ============================================
   // GESTION DES LIGNES
   // ============================================

   const toggleLineMode = (lineId: string) => {
      setEditLignes((prev) =>
         prev.map((ligne) => {
            if (ligne.id === lineId) {
               const newIsManual = !ligne.isManual;
               return {
                  ...ligne,
                  isManual: newIsManual,
                  article_code: newIsManual ? "" : ligne.article_code,
                  articles: newIsManual ? null : ligne.articles,
                  designation: "",
                  prix_unitaire_ht: newIsManual ? 0 : ligne.prix_unitaire_ht,
               };
            }
            return ligne;
         })
      );
   };

   const ajouterLigne = () => {
      if (isLastLineEmpty(editLignes)) return;
      setEditLignes([...editLignes, createEmptyLine()]);
   };

   const supprimerLigne = (lineId: string) => {
      if (editLignes.length > 1) {
         const newLignes = editLignes.filter((l) => l.id !== lineId);
         
         if (!isLastLineEmpty(newLignes)) {
            setEditLignes([...newLignes, createEmptyLine()]);
         } else {
            setEditLignes(newLignes);
         }
      }
   };

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

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

         if (field === "articles" && value) {
            updatedLignes = addLineIfNeeded(updatedLignes, lineId);
         }

         return updatedLignes;
      });
   };

   const handleManualDesignationBlur = (lineId: string, designation: string) => {
      if (designation && designation.trim() !== "") {
         setEditLignes((prev) => {
            const lastLine = prev[prev.length - 1];
            
            if (lastLine && lastLine.id === lineId && lastLine.isManual) {
               if (!isLastLineEmpty(prev)) {
                  return prev;
               }
               return [...prev, createEmptyLine()];
            }
            
            return prev;
         });
      }
   };

   // ============================================
   // VALIDATION
   // ============================================

   const canSave = useMemo(() => {
      if (!editClient) return false;
      const lignesValides = editLignes.filter(
         (l) => l.article_code || (l.isManual && l.designation && l.designation.trim() !== "")
      );
      return lignesValides.length > 0;
   }, [editClient, editLignes]);

   // ============================================
   // HANDLERS
   // ============================================

   const handleCancelEdit = () => {
      navigate("/home/factures");
   };

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

      const lignesValides = editLignes.filter(
         (l) => l.article_code || (l.isManual && l.designation && l.designation.trim() !== "")
      );
      
      if (lignesValides.length === 0) {
         setError("Veuillez ajouter au moins un article ou une ligne");
         return;
      }

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

         const payloadCreate: FactureRequest = {
            client_id: editClient.numero,
            reference: editReference,
            date_facture: editDateFacture,
            date_livraison: editDateEcheance,
            lignes: lignesValides.map((l) => ({
               article_code: l.article_code || "DIVERS",
               quantite: l.quantite,
               prix_unitaire_ht: l.prix_unitaire_ht,
               remise_pourcentage: l.remise_pourcentage,
               ...(l.isManual && l.designation && { designation: l.designation }),
            })),
         };

         const result = await dispatch(createFacture(payloadCreate)).unwrap();

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

         const factureCreated = await dispatch(getFacture(result.data.numero_facture)).unwrap();
         dispatch(selectfacture(factureCreated as any));

         toast({
            title: "Facture créée avec succès !",
            description: `La facture ${result.data.numero_facture} a été créée.`,
            className: "bg-green-500 text-white border-green-600",
         });

         navigate(`/home/factures/${result.data.numero_facture}`);
      } catch (err: any) {
         setError(err.message || "Erreur lors de la création de la facture");
         toast({
            title: "Erreur",
            description: "Impossible de créer la facture.",
            className: "bg-red-500 text-white border-red-600",
         });
      } finally {
         setIsSaving(false);
      }
   };

   const handleOpenArticleModal = (lineId: string) => {
      setCurrentLineId(lineId);
      setIsArticleModalOpen(true);
      setActiveLineId(null);
   };

   // ============================================
   // RENDER
   // ============================================

   return (
      <>
         <Helmet>
            <title>Nouvelle facture - Dataven</title>
         </Helmet>

         {/* Structure principale avec h-screen */}
         <div className="flex flex-col h-[80vh] overflow-hidden">
            {/* HEADER - Reste fixe */}
            <div className="flex-none bg-white dark:bg-gray-950 border-b border-gray-200 dark:border-gray-800 z-30 shadow-[0_1px_3px_rgba(0,0,0,0.05)] py-2">
               <div className="max-w-[1920px] mx-auto px-4 sm:px-6 lg:px-8">
                  <div className="flex flex-col gap-4 justify-between items-start lg:flex-row lg:items-center">
                     {/* Left Section */}
                     <div className="flex flex-col flex-1 gap-3 w-full min-w-0 lg:w-auto">
                        {/* Row 1 */}
                        <div className="flex flex-wrap gap-4 items-center">
                           {/* Back + Title */}
                           <div className="flex gap-3 items-center mr-2 shrink-0">
                              <button
                                 onClick={handleCancelEdit}
                                 className="p-1.5 -ml-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-full transition-colors text-gray-500"
                              >
                                 <ArrowLeft className="w-5 h-5" />
                              </button>
                              <div className="flex flex-col">
                                 <div className="flex gap-2 items-center">
                                    <h1 className="text-xl font-bold tracking-tight text-gray-900 dark:text-white">
                                       NOUVELLE
                                    </h1>
                                    <StatusBadge status={0} type_doc={60} />
                                    <span className="px-2 py-1 text-xs font-medium text-blue-800 bg-blue-100 rounded-full">
                                       Brouillon
                                    </span>
                                 </div>
                              </div>
                           </div>

                           <div className="hidden mx-2 w-px h-8 bg-gray-200 dark:bg-gray-800 sm:block" />

                           {/* Client */}
                           <div className="flex-1 min-w-[250px] max-w-[400px] relative z-20">
                              <ClientAutocomplete
                                 value={editClient}
                                 onChange={setEditClient}
                                 required
                                 placeholder="Client..."
                              />
                           </div>

                           {/* Date + User */}
                           <div className="flex gap-4 shrink-0">
                              <div className="w-auto">
                                 <Input
                                    type="date"
                                    value={formatForDateInput(editDateFacture)}
                                    onChange={(e) => setEditDateFacture(e.target.value)}
                                    className="h-10 text-xs"
                                 />
                              </div>
                              <div className="w-[140px]">
                                 <div className="flex flex-row gap-2 items-center px-1 py-1 w-full text-sm bg-gray-50 rounded-xl border shadow-sm opacity-80 cursor-not-allowed dark:bg-gray-900 border-gray-200 dark:border-gray-800">
                                    <div
                                       className="w-6 h-6 rounded-full bg-[#007E45] text-white flex items-center justify-center text-[10px] font-semibold"
                                       style={{ width: "3vh", height: "3vh" }}
                                    >
                                       {userConnected
                                          ? `${userConnected.prenom?.[0] || ""}${userConnected.nom?.[0] || ""}`
                                          : "JD"}
                                    </div>
                                    <span className="text-sm text-gray-900 dark:text-white">
                                       {userConnected ? `${userConnected.prenom}` : "_"}
                                    </span>
                                 </div>
                              </div>
                           </div>
                        </div>

                        {/* Row 2 - Référence + Date échéance */}
                        <div className="flex flex-wrap gap-4 items-center pt-1">
                           <div className="w-[250px]">
                              <Input
                                 value={editReference}
                                 onChange={(e) => setEditReference(e.target.value)}
                                 placeholder="Référence..."
                                 className="h-9 text-xs"
                              />
                           </div>
                           <div className="flex items-center gap-2">
                              <AlertTriangle className="w-4 h-4 text-red-500" />
                              <span className="text-xs text-gray-500">Date d'échéance:</span>
                              <Input
                                 type="date"
                                 value={formatForDateInput(editDateEcheance)}
                                 onChange={(e) => setEditDateEcheance(e.target.value)}
                                 className="h-9 text-xs w-[140px]"
                              />
                           </div>
                        </div>
                     </div>

                     {/* Right Section - Actions */}
                     <div className="flex gap-3 items-center self-start mt-2 ml-auto shrink-0 lg:self-center lg:mt-0">
                        <button
                           onClick={handleCancelEdit}
                           disabled={isSaving}
                           className="px-4 py-2 text-sm font-medium text-gray-600 transition-colors hover:text-gray-900 disabled:opacity-50"
                        >
                           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 shadow-sm"
                        >
                           {isSaving ? (
                              <Loader2 className="w-4 h-4 animate-spin" />
                           ) : (
                              <Save className="w-4 h-4" />
                           )}
                           Enregistrer
                        </button>
                     </div>
                  </div>
               </div>
            </div>

            {/* CONTENT - Zone scrollable */}
            <div className="flex-1 overflow-y-auto scroll-smooth">
               <div className="px-4 mx-auto w-full sm:px-6 lg:px-8 py-6">
                  <div className="w-full">
                     {/* Tableau des lignes */}
                     <div className="bg-white rounded-2xl border border-gray-200 shadow-sm dark:bg-gray-950 dark:border-gray-800">
                        <div className="overflow-x-auto mb-2">
                           <table className="w-full">
                              <thead className="text-xs font-semibold tracking-wider text-gray-500 uppercase bg-gray-50 border-b dark:bg-gray-900/50">
                                 <tr className="text-[10px]">
                                    <th className="px-2 py-3 w-5 text-center">Mode</th>
                                    <th className="px-4 py-3 text-left w-[25%]">Désignation</th>
                                    <th className="px-4 py-3 text-right w-[20%]">Description détaillée</th>
                                    <th className="px-4 py-3 text-right w-[8%]">Qté</th>
                                    <th className="px-4 py-3 text-right w-[15%]">P.U. HT</th>
                                    <th className="px-4 py-3 text-right w-[8%]">Rem. %</th>
                                    <th className="px-4 py-3 text-right w-[8%]">TVA</th>
                                    <th className="px-4 py-3 text-right w-[15%]">Total HT</th>
                                    <th className="px-2 py-3 w-12"></th>
                                 </tr>
                              </thead>
                              <tbody className="divide-y divide-gray-100 dark:divide-gray-800">
                                 {editLignes.map((item, index) => {
                                    const isLastEmptyLine = index === editLignes.length - 1 && isLastLineEmpty(editLignes);
                                    
                                    return (
                                       <tr 
                                          key={item.id} 
                                          className={cn(
                                             "group hover:bg-gray-50/50 dark:hover:bg-gray-900/20",
                                             isLastEmptyLine && "bg-gray-50/30"
                                          )}
                                       >
                                          {/* ... tout le contenu du tr reste identique ... */}
                                          {/* Mode Toggle */}
                                          <td className="px-2 py-3">
                                             <TooltipProvider>
                                                <Tooltip>
                                                   <TooltipTrigger asChild>
                                                      <button
                                                         onClick={() => toggleLineMode(item.id)}
                                                         className={cn(
                                                            "p-1.5 rounded-md transition-all duration-200",
                                                            item.isManual
                                                               ? "text-amber-600 bg-amber-50 hover:bg-amber-100"
                                                               : "text-[#007E45] bg-green-50 hover:bg-green-100"
                                                         )}
                                                      >
                                                         {item.isManual ? (
                                                            <PenLine className="w-4 h-4" />
                                                         ) : (
                                                            <Package className="w-4 h-4" />
                                                         )}
                                                      </button>
                                                   </TooltipTrigger>
                                                </Tooltip>
                                             </TooltipProvider>
                                          </td>

                                          {/* Article / Désignation */}
                                          <td className="px-4 py-3 min-w-[280px]">
                                             {item.isManual ? (
                                                <div className="relative">
                                                   <input
                                                      type="text"
                                                      value={item.designation}
                                                      onChange={(e) => {
                                                         updateLigne(item.id, "designation", e.target.value);
                                                      }}
                                                      onFocus={() => setActiveLineId(item.id)}
                                                      onBlur={(e) => {
                                                         setTimeout(() => setActiveLineId(null), 150);
                                                         handleManualDesignationBlur(item.id, e.target.value);
                                                      }}
                                                      className="w-full border-0 text-sm focus:outline-none bg-transparent text-gray-900"
                                                      placeholder={isLastEmptyLine ? "Saisir une désignation..." : "Désignation..."}
                                                   />
                                                   {activeLineId === item.id && item.designation && (
                                                      <div className="overflow-hidden mt-1 w-full bg-white rounded-xl border border-gray-200 shadow-lg absolute z-10">
                                                         <button
                                                            type="button"
                                                            onMouseDown={(e) => e.preventDefault()}
                                                            onClick={() => handleOpenArticleModal(item.id)}
                                                            className="flex gap-3 items-center px-4 py-3 w-full text-left transition-colors hover:bg-green-50"
                                                         >
                                                            <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]">{item.designation}</span>"
                                                            </span>
                                                         </button>
                                                         <div className="border-t border-gray-100" />
                                                         <div className="flex flex-row gap-3 justify-center items-center py-2 w-full text-xs text-center text-gray-400">
                                                            <PenLine className="w-4 h-4" />
                                                            <span className="text-xs font-medium">Texte libre accepté</span>
                                                         </div>
                                                      </div>
                                                   )}
                                                </div>
                                             ) : (
                                                <ArticleAutocomplete
                                                   value={item.articles}
                                                   onChange={(article) => updateLigne(item.id, "articles", article)}
                                                   required
                                                   className="text-sm"
                                                   placeholder={isLastEmptyLine ? "Rechercher un article..." : "Article..."}
                                                />
                                             )}
                                          </td>

                                          {/* Description */}
                                          <td className="px-1">
                                             <input
                                                type="text"
                                                value={item.isManual ? description || "" : item.designation || ""}
                                                onChange={(e) =>
                                                   item.isManual
                                                      ? setDescription(e.target.value)
                                                      : updateLigne(item.id, "designation", e.target.value)
                                                }
                                                placeholder="Description détaillée..."
                                                className="w-full border-0 text-sm focus:outline-none bg-transparent text-gray-900 text-right"
                                             />
                                          </td>

                                          {/* Quantité */}
                                          <td className="px-1" style={{ width: "100px" }}>
                                             <input
                                                type="number"
                                                value={item.quantite}
                                                onChange={(e) =>
                                                   updateLigne(item.id, "quantite", parseFloat(e.target.value) || 0)
                                                }
                                                min={0}
                                                className="w-full border-0 text-sm focus:outline-none bg-transparent text-gray-900 text-right"
                                             />
                                          </td>

                                          {/* Prix Unitaire */}
                                          <td className="px-1 text-center" style={{ width: "60px" }}>
                                             <input
                                                type="number"
                                                value={item.prix_unitaire_ht || item.articles?.prix_vente || 0}
                                                onChange={(e) =>
                                                   updateLigne(item.id, "prix_unitaire_ht", parseFloat(e.target.value) || 0)
                                                }
                                                min={0}
                                                step={0.01}
                                                className="w-full border-0 text-sm focus:outline-none bg-transparent text-gray-900 text-right"
                                             />
                                          </td>

                                          {/* Remise */}
                                          <td className="px-1 text-center" style={{ width: "60px" }}>
                                             <input
                                                type="number"
                                                value={item.remise_pourcentage || 0}
                                                onChange={(e) =>
                                                   updateLigne(item.id, "remise_pourcentage", parseFloat(e.target.value) || 0)
                                                }
                                                min={0}
                                                step={1}
                                                className="w-full border-0 text-sm focus:outline-none bg-transparent text-gray-900 text-right"
                                             />
                                          </td>

                                          {/* TVA */}
                                          <td className="px-1 text-center text-gray-500 text-right text-sm">
                                             {item.taux_taxe1}%
                                          </td>

                                          {/* Total */}
                                          <td className="px-1 text-right">
                                             <span className={cn(
                                                "font-bold font-mono text-sm",
                                                isLastEmptyLine ? "text-gray-300" : "text-gray-900"
                                             )}>
                                                {calculerTotalLigne(item).toFixed(2)} €
                                             </span>
                                          </td>

                                          {/* Delete */}
                                          <td className="px-1 text-center">
                                             <button
                                                onClick={() => supprimerLigne(item.id)}
                                                disabled={editLignes.length <= 1}
                                                className={cn(
                                                   "p-1.5 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors disabled:opacity-30",
                                                   isLastEmptyLine && "invisible"
                                                )}
                                             >
                                                <Trash2 className="w-4 h-4" />
                                             </button>
                                          </td>
                                       </tr>
                                    );
                                 })}
                              </tbody>
                           </table>
                        </div>

                        {/* Bouton ajouter ligne */}
                        {!isLastLineEmpty(editLignes) && (
                           <div className="m-6">
                              <button
                                 onClick={ajouterLigne}
                                 className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-[#2A6F4F] bg-white border border-[#2A6F4F] rounded-lg hover:bg-green-50 transition-all shadow-sm"
                              >
                                 <Plus className="w-4 h-4" /> Ajouter une ligne
                              </button>
                           </div>
                        )}

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

                     {/* Section Notes */}
                     <div className="grid grid-cols-1 gap-6 p-6 mt-8 bg-gray-50 rounded-2xl border border-gray-100 md:grid-cols-2 dark:bg-gray-900/30 dark:border-gray-800">
                        {/* Notes publiques */}
                        <div className="space-y-3">
                           <div className="flex justify-between items-center">
                              <label className="flex gap-2 items-center text-sm font-semibold text-gray-900 dark:text-white">
                                 Notes publiques <Lock className="w-3 h-3 text-gray-400" />
                              </label>
                              <span className="text-xs text-gray-500">Visible sur le PDF</span>
                           </div>
                           <Textarea
                              rows={4}
                              placeholder="Conditions de paiement, délais de livraison, modalités particulières..."
                              className="bg-white resize-none dark:bg-gray-950"
                              value={note.publique}
                              onChange={(e) => setNote({ ...note, publique: e.target.value })}
                           />
                        </div>

                        {/* Notes privées */}
                        <div className="space-y-3">
                           <div className="flex justify-between items-center">
                              <label className="flex gap-2 items-center text-sm font-semibold text-gray-900 dark:text-white">
                                 Notes privées <EyeOff className="w-3 h-3 text-gray-400" />
                              </label>
                              <span className="text-xs text-gray-500">Interne uniquement</span>
                           </div>
                           <Textarea
                              rows={4}
                              placeholder="Notes internes, marge de négociation, contexte client..."
                              className="bg-white border-yellow-200 resize-none dark:bg-gray-950 focus:border-yellow-400"
                              value={note.prive}
                              onChange={(e) => setNote({ ...note, prive: e.target.value })}
                           />
                        </div>
                     </div>
                  </div>
               </div>
            </div>

            {/* Footer Totaux - Reste fixe en bas */}
            <div className="flex-none bg-white dark:bg-gray-950 border-t border-gray-200 dark:border-gray-800 shadow-[0_-4px_6px_-1px_rgba(0,0,0,0.1)] z-20">
               <div className="px-4 mx-auto w-full sm:px-6 lg:px-8">
                  <StickyTotals
                     total_ht_calcule={editTotalHT}
                     total_taxes_calcule={editTotalTVA}
                     total_ttc_calcule={editTotalTTC}
                  />
               </div>
            </div>
         </div>

         {/* Modal création article */}
         <ModalArticle
            open={isArticleModalOpen}
            onClose={() => setIsArticleModalOpen(false)}
         />

         {isSaving && <ModalLoading />}
      </>
   );
};

export default InvoiceCreatePage;