import { useState, useMemo, useEffect } from "react";
import { Helmet } from "react-helmet";
import { useNavigate } from "react-router-dom";
import {
   ArrowLeft,
   Download,
   Eye,
   File,
   Trash2,
   FileText,
   Plus,
   X,
   Check,
   Loader2,
} from "lucide-react";
import StatusBadge from "@/components/StatusBadget";
import Tabs from "@/components/Tabs";
import { toast } from "@/components/ui/use-toast";
import {
   cn,
   formatDateFR,
   formatDateFRCourt,
   formatForDateInput,
} from "@/lib/utils";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import {
   getavoirSelected,
   avoirStatus,
} from "@/store/features/avoir/selectors";
import { Avoir } from "@/types/avoirType";
import { FormField, Input, RepresentantInput } from "@/components/ui/FormModal";
import Timeline from "@/components/Timeline";
import { getAllClients } from "@/store/features/client/selectors";
import { Client } from "@/types/clientType";
import { Article } from "@/types/articleType";
import { getAvoir, updateAvoir } from "@/store/features/avoir/thunk";
import { selectavoir } from "@/store/features/avoir/slice";
import ClientAutocomplete from "@/components/molecules/ClientAutocomplete";
import ArticleAutocomplete from "@/components/molecules/ArticleAutocomplete";
import { ModalLoading } from "@/components/modal/ModalLoading";

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 CreditNotesDetailPage = () => {
   const navigate = useNavigate();
   const dispatch = useAppDispatch();
   const clients = useAppSelector(getAllClients) as Client[];
   const statusAvoir = useAppSelector(avoirStatus);

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

   // États pour l'édition inline
   const [isEditing, setIsEditing] = useState(false);
   const [isSaving, setIsSaving] = useState(false);
   const [error, setError] = useState<string | null>(null);

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

   const avoir = useAppSelector(getavoirSelected) as Avoir;

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

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

         const lignesInitiales: LigneForm[] =
            avoir.lignes?.map((ligne) => ({
               article_code: ligne.article_code,
               quantite: ligne.quantite,
               prix_unitaire_ht: ligne.prix_unitaire_ht ?? 0,
               designation: ligne.designation ?? "",
               total_taxes: ligne.total_taxes ?? 0,
               taux_taxe1: ligne.taux_taxe1 ?? 0,
               montant_ligne_ht: ligne.montant_ligne_ht ?? 0,
               remise_pourcentage: ligne.remise_pourcentage ?? 0,
               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,
                  },
               ]
         );
      }
   }, [avoir, isEditing, clients]);

   if (!avoir) return <div className="p-8 text-center">Avoir introuvable</div>;

   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 = avoir.valeur_frais;
      return taxesParLignes + valeur_frais * (avoir.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 + avoir.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_avoir: editDateAvoir,
            date_livraison: editDateLivraison,
            reference: editReference,
            lignes: lignesValides.map((l) => ({
               article_code: l.article_code,
               quantite: l.quantite,
            })),
         };

         await dispatch(
            updateAvoir({
               numero: avoir.numero,
               data: payloadUpdate,
            })
         ).unwrap();

         toast({
            title: "Avoir mis à jour !",
            description: `L'avoir ${avoir.numero} a été mis à jour avec succès.`,
            className: "bg-green-500 text-white border-green-600",
         });

         // Recharger l'avoir
         const itemUpdated = (await dispatch(
            getAvoir(avoir.numero)
         ).unwrap()) as Avoir;
         dispatch(selectavoir(itemUpdated));

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

   const tabs = [
      { id: "identification", label: "Identification" },
      { id: "lines", label: "Lignes de l'avoir" },
      { id: "totals", label: "Totaux" },
      { id: "documents", label: "Documents", count: avoir.lignes?.length },
      { id: "historique", label: "Historique", count: avoir.lignes?.length },
   ];

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

   return (
      <>
         <Helmet>
            <title>{avoir.numero} - Avoir</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/avoirs")}
                           className="p-2 text-gray-500 rounded-full transition-colors hover:bg-gray-100 dark:hover:bg-gray-800"
                           aria-label="Retour à la liste des avoirs"
                           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">
                                 {avoir.numero}
                              </h1>
                              <StatusBadge status={avoir.statut} />
                              {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">
                              {avoir.client_intitule ? (
                                 <span className="font-medium text-gray-900 dark:text-gray-300">
                                    {avoir.client_intitule}
                                 </span>
                              ) : (
                                 <span className="italic text-gray-400">
                                    Client non défini
                                 </span>
                              )}
                              <span>•</span>
                              <span>{formatDateFR(avoir.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-[#007E45] 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>
                           </>
                        ) : (
                           <>
                              <button 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 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-200 dark:hover:bg-gray-700">
                                 <Eye className="w-4 h-4" />
                                 <span className="hidden sm:inline">Aperçu</span>
                              </button>
                              <button
                                 className="p-2 text-gray-600 rounded-xl border border-gray-200 dark:border-gray-800 hover:bg-gray-50 dark:hover:bg-gray-900 dark:text-gray-400"
                                 title="Download"
                              >
                                 <Download className="w-5 h-5" />
                              </button>
                              <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>
                           </>
                        )}
                     </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={avoir.client_intitule}
                                       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 d'émission" required>
                                    <Input
                                       type="date"
                                       value={
                                          isEditing
                                             ? formatForDateInput(editDateAvoir)
                                             : formatForDateInput(avoir.date)
                                       }
                                       onChange={(e) =>
                                          isEditing && setEditDateAvoir(e.target.value)
                                       }
                                       disabled={!isEditing}
                                       className={cn(
                                          !isEditing &&
                                          "opacity-50 cursor-not-allowed bg-gray-50 dark:bg-gray-900"
                                       )}
                                    />
                                 </FormField>
                                 <FormField label="Dû le" required>
                                    <Input
                                       type="date"
                                       value={
                                          isEditing
                                             ? formatForDateInput(editDateLivraison)
                                             : formatForDateInput(avoir.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 : avoir.reference || ""
                                    }
                                    onChange={(e) =>
                                       isEditing && setEditReference(e.target.value)
                                    }
                                    disabled={!isEditing}
                                    placeholder="Référence..."
                                    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 />
                           </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 text-red-600">
                                             - {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>
                                    ))
                                 ) : avoir.lignes ? (
                                    avoir.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 text-red-600 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-[#941403] 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-red-50 rounded-xl border border-red-100 lg:w-96 dark:bg-red-900/20 dark:border-red-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-red-600 dark:text-red-400">
                                    -{" "}
                                    {isEditing
                                       ? editTotalHT.toLocaleString()
                                       : avoir.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-red-600 dark:text-red-400">
                                    -{" "}
                                    {isEditing
                                       ? editTotalTVA.toLocaleString()
                                       : avoir.total_taxes_calcule.toLocaleString()}
                                    €
                                 </span>
                              </div>
                              <div className="my-2 h-px bg-red-200 dark:bg-red-700" />
                              <div className="flex justify-between text-lg font-bold">
                                 <span className="text-gray-900 dark:text-white">
                                    Total à rembourser
                                 </span>
                                 <span className="text-[#941403] font-mono">
                                    -{" "}
                                    {isEditing
                                       ? editTotalTTC.toLocaleString()
                                       : avoir.total_ttc_calcule.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">
                              Détails
                           </h3>
                           <div className="space-y-4">
                              <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">
                                    {avoir.lignes?.length || 0}
                                 </span>
                              </div>
                           </div>
                        </div>
                     </div>
                  )}

                  {/* --- HISTORIQUE TAB --- */}
                  {activeTab === "historique" && <Timeline events={timeline} />}

                  {/* --- 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-[#941403]" />
                                       <span className="font-medium text-gray-900 dark:text-white">
                                          AV_{avoir.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(avoir.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-[#941403] hover:text-green-700">
                                          <Trash2 className="w-4 h-4" />
                                       </button>
                                    </td>
                                 </tr>
                              </tbody>
                           </table>
                        </div>
                     </div>
                  )}
               </div>
            </div>
         </div>

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

export default CreditNotesDetailPage;
