import { useEffect, useMemo, useState } from "react";
import { Helmet } from "react-helmet";
import { useNavigate } from "react-router-dom";
import {
  ArrowLeft,
  CircleDot,
  File,
  FileText,
  Hash,
  Plus,
  Save,
  Settings,
  ShoppingCart,
  Trash2,
  X,
} 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 {
  commandeStatus,
  getcommandeSelected,
} from "@/store/features/commande/selectors";
import { Commande, LigneCommande } from "@/types/commandeTypes";
import {
  formatDateFR,
  formatDateFRCourt,
  formatForDateInput,
} from "@/lib/utils";
import {
  commandeToFacture,
  getCommande,
  updateCommande,
} from "@/store/features/commande/thunk";
import { getFacture } from "@/store/features/factures/thunk";
import { ModalLoading } from "@/components/modal/ModalLoading";
import { usePDFPreview } from "@/components/modal/ModalPDFPreview";
import Tabs from "@/components/Tabs";
import Timeline from "@/components/Timeline";
import { Section } from "@/components/ui/Section";
import { getAllClients } from "@/store/features/client/selectors";
import { Client } from "@/types/clientType";
import { selectClient } from "@/store/features/client/slice";
import { selectfacture } from "@/store/features/factures/slice";
import ModalStatus from "@/components/modal/ModalStatus";
import { ActionButton } from "@/components/ribbons/ActionButton";
import ClientAutocomplete from "@/components/molecules/ClientAutocomplete";
import ArticleAutocomplete from "@/components/molecules/ArticleAutocomplete";
import { Article } from "@/types/articleType";
import { selectcommande } from "@/store/features/commande/slice";
import { SageDocumentType } from "@/types/sageTypes";
import StatusBadge from "@/components/ui/StatusBadge";
import ModalWorkflowToBL from "@/components/modal/ModalWorkflowToBL";
import ModalCommandetoFacture from "@/components/modal/ModalCommandetoFacture";

interface LigneForm extends LigneCommande {
  articles?: Article | null;
}

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

  const [error, setError] = useState<string | null>(null);
  const [loadingTransform, setLoadingTransform] = useState(false);
  const [activeTab, setActiveTab] = useState("identification");

  const clients = useAppSelector(getAllClients) as Client[];
  const commande = useAppSelector(getcommandeSelected) as Commande;
  const statusCommande = useAppSelector(commandeStatus);

  const [openStatus, setOpenStatus] = useState(false);

  const [isEditing, setIsEditing] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [isOpenWorkflowToBL, setIsOpenWorkflowToBL] = useState(false);
  const [isOpenBLToFacture, setIsOpenBLToFacture] = useState(false);

  // États pour l'édition
  const [editClient, setEditClient] = useState<Client | null>(null);
  const [editDateCommande, setEditDateCommande] = useState("");
  const [editDateLivraison, setEditDateLivraison] = useState("");
  const [editReference, setEditReference] = useState("");
  const [editCommentaire, setEditCommentaire] = useState("");
  const [editLignes, setEditLignes] = useState<LigneForm[]>([]);

  const {
    openPreview,
    closePreview,
    isOpen,
    pdfUrl,
    fileName,
    PDFPreviewModal,
  } = usePDFPreview();

  useEffect(() => {
    if (isEditing && commande) {
      const client = clients.find((c) => c.numero === commande.client_code);
      setEditClient(client || null);
      setEditDateCommande(commande.date || "");
      setEditDateLivraison(commande.date_livraison || "");
      setEditReference(commande.reference || "");
      setEditCommentaire("");

      const lignesInitiales: LigneForm[] =
        commande.lignes?.map((ligne) => ({
          ...ligne,
          article: {
            reference: ligne.article_code,
            designation: ligne.designation,
            prix_vente: ligne.prix_unitaire_ht,
          } as Article,
        })) || [];

      setEditLignes(
        lignesInitiales.length > 0
          ? lignesInitiales
          : [{ article_code: "", quantite: 1, articles: null }]
      );
    }
  }, [isEditing, commande, clients]);

  if (!commande) return <div>Commande introuvable</div>;

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

  const ajouterLigne = () => {
    setEditLignes([
      ...editLignes,
      { article_code: "", quantite: 1, 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) {
      nouvelles[index].articles = value;
      nouvelles[index].article_code = value.reference;
      nouvelles[index].prix_unitaire_ht = value.prix_vente;
      nouvelles[index].designation = value.designation;
    } else {
      (nouvelles[index] as any)[field] = value;
    }

    setEditLignes(nouvelles);
  };

  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 = commande.valeur_frais;
    return taxesParLignes + valeur_frais * (commande.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 + commande.valeur_frais;
    return totalHtNet;
  };

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

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

  const handleSave = async () => {
    if (!canSave) return;

    const lignesValides = editLignes.filter((l) => l.article_code);

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

      const payload = {
        client_id: editClient!.numero,
        reference: editReference,
        date_livraison: (() => {
          const d = new Date(editDateLivraison);
          d.setDate(d.getDate() + 1);
          return d.toISOString().split("T")[0];
        })(),
        date_commande: (() => {
          const d = new Date(editDateCommande);
          d.setDate(d.getDate() + 1);
          return d.toISOString().split("T")[0];
        })(),
        lignes: lignesValides.map((l) => ({
          article_code: l.articles?.reference || "",
          quantite: l.quantite,
        })),
      };

      const result = (await dispatch(
        updateCommande({
          numero: commande.numero,
          data: payload,
        })
      ).unwrap()) as any;

      const numero = result.commande.numero;

      toast({
        title: "Commande mise à jour !",
        description: `La commande ${numero} a été mise à jour avec succès.`,
        className: "bg-green-500 text-white border-green-600",
      });

      // Recharger la commande
      const updatedCommande = (await dispatch(
        getCommande(numero)
      ).unwrap()) as Commande;
      dispatch(selectcommande(updatedCommande));

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

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

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

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

  // Totaux pour l'affichage (mode lecture ou édition)
  const displayTotalHT = isEditing ? editTotalHT : commande.total_ht_calcule;
  const displayTotalTVA = isEditing
    ? editTotalTVA
    : commande.total_taxes_calcule;
  const displayTotalTTC = isEditing ? editTotalTTC : commande.total_ttc_calcule;

  return (
    <>
      <Helmet>
        <title>{commande.numero} - Commande</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/commandes")}
                  title="Retour à la liste des commandes"
                  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">
                      {commande.numero}
                    </h1>
                    <StatusBadge status={commande.statut} type_doc={10} />
                    {isEditing && (
                      <span className="px-2 py-1 text-xs font-medium text-amber-700 bg-amber-100 rounded-lg">
                        Mode édition
                      </span>
                    )}
                  </div>
                  <div className="flex gap-2 items-center text-sm text-gray-500">
                    {commande.client_intitule ? (
                      <span
                        className="font-medium text-gray-900 cursor-pointer dark:text-gray-300 hover:underline"
                        onClick={() => {
                          if (isEditing) return;
                          const clientSelected = clients.find(
                            (item) => item.numero === commande.client_code
                          );
                          if (clientSelected) {
                            dispatch(selectClient(clientSelected));
                            navigate(`/home/clients/${commande.client_code}`);
                          }
                        }}
                      >
                        {commande.client_intitule}
                      </span>
                    ) : (
                      <span className="italic text-gray-400">
                        Client non défini
                      </span>
                    )}
                    <span>•</span>
                    <span>{formatDateFR(commande.date)}</span>
                  </div>
                </div>
              </div>

              {/* ACTIONS */}
              <div className="flex gap-2 items-center">
                {isEditing ? (
                  <>
                    <button
                      onClick={handleCancelEdit}
                      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"
                    >
                      <X className="w-4 h-4" />
                      Annuler
                    </button>
                    <button
                      onClick={handleSave}
                      disabled={!canSave || isSaving}
                      className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-[#007E45] rounded-xl hover:bg-[#006838] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      <Save className="w-4 h-4" />
                      {isSaving ? "Enregistrement..." : "Enregistrer"}
                    </button>
                  </>
                ) : (
                  <>
                    {commande.statut === 2 ? (
                      <>
                        <button
                          onClick={() => setIsOpenWorkflowToBL(true)}
                          className="flex gap-2 items-center px-3 py-2 text-sm font-medium text-teal-700 bg-teal-50 rounded-xl border border-teal-100 transition-colors hover:bg-teal-100 dark:bg-teal-900/20 dark:border-teal-900 dark:text-teal-300 dark:hover:bg-teal-900/40"
                        >
                          <ShoppingCart className="w-4 h-4" />
                          <span className="hidden sm:inline">
                            Transformer en BL
                          </span>
                        </button>
                        <button
                          onClick={() => setIsOpenBLToFacture(true)}
                          className="flex gap-2 items-center px-3 py-2 text-sm font-medium text-teal-700 bg-teal-50 rounded-xl border border-teal-100 transition-colors hover:bg-teal-100 dark:bg-teal-900/20 dark:border-teal-900 dark:text-teal-300 dark:hover:bg-teal-900/40"
                        >
                          <FileText className="w-4 h-4" /> Créer 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>
                    )}
                    <button
                      onClick={() => setIsEditing(true)}
                      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>

        {/* 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">
                    {isEditing ? (
                      <>
                        <FormField label="Client" required fullWidth>
                          <ClientAutocomplete
                            value={editClient}
                            onChange={setEditClient}
                            required
                          />
                        </FormField>
                        <div className="grid grid-cols-2 gap-4">
                          <FormField label="Date commande" required>
                            <Input
                              type="date"
                              value={formatForDateInput(editDateCommande)}
                              onChange={(e) =>
                                setEditDateCommande(e.target.value)
                              }
                            />
                          </FormField>
                          <FormField label="Livraison prévue" required>
                            <Input
                              type="date"
                              value={formatForDateInput(editDateLivraison)}
                              onChange={(e) =>
                                setEditDateLivraison(e.target.value)
                              }
                            />
                          </FormField>
                        </div>
                        <FormField label="Référence externe">
                          <Input
                            value={editReference}
                            onChange={(e) => setEditReference(e.target.value)}
                            placeholder="Bon de commande client..."
                          />
                        </FormField>
                        <FormField label="Affaire / Deal">
                          <Input
                            value=""
                            disabled
                            placeholder="Non disponible"
                            className="bg-gray-50 opacity-50 cursor-not-allowed dark:bg-gray-900"
                          />
                        </FormField>
                      </>
                    ) : (
                      <>
                        <FormField label="Client" required>
                          <Input
                            type="text"
                            value={commande.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 commande" required>
                            <Input
                              type="date"
                              value={formatForDateInput(commande.date)}
                              disabled
                              className="bg-gray-50 opacity-50 cursor-not-allowed dark:bg-gray-900"
                            />
                          </FormField>
                          <FormField label="Livraison prévue" required>
                            <Input
                              type="date"
                              value={formatForDateInput(
                                commande.date_livraison
                              )}
                              disabled
                              className="bg-gray-50 opacity-50 cursor-not-allowed dark:bg-gray-900"
                            />
                          </FormField>
                        </div>
                        <FormField label="Référence externe">
                          <Input
                            value={commande.reference}
                            disabled
                            placeholder="Bon de commande client..."
                            className="bg-gray-50 opacity-50 cursor-not-allowed 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={
                          isEditing
                            ? (e) => setEditCommentaire(e.target.value)
                            : undefined
                        }
                        disabled={!isEditing}
                        placeholder="Instructions spécifiques..."
                        className={
                          !isEditing
                            ? "bg-gray-50 opacity-50 cursor-not-allowed 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%]">
                          Total HT
                        </th>
                        {isEditing && <th className="w-[5%] rounded-r-lg"></th>}
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-100 dark:divide-gray-800">
                      {isEditing
                        ? editLignes.map((ligne, index) => (
                          <tr
                            key={index}
                            className="group hover:bg-gray-50/50 dark:hover:bg-gray-900/20"
                          >
                            <td className="px-4 py-2">
                              <ArticleAutocomplete
                                value={ligne.articles!}
                                onChange={(article) =>
                                  updateLigne(index, "articles", article)
                                }
                                required
                              />
                            </td>
                            <td
                              className="px-4 py-2"
                              style={{ width: "12vh" }}
                            >
                              <input
                                type="number"
                                value={ligne.quantite}
                                onChange={(e) =>
                                  updateLigne(
                                    index,
                                    "quantite",
                                    parseFloat(e.target.value) || 0
                                  )
                                }
                                min={0}
                                step={1}
                                className="w-full text-right px-3 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-2"
                              style={{ width: "12vh" }}
                            >
                              <input
                                type="number"
                                value={
                                  ligne.prix_unitaire_ht ||
                                  ligne.articles?.prix_vente ||
                                  0
                                }
                                onChange={(e) =>
                                  updateLigne(
                                    index,
                                    "prix_unitaire_ht",
                                    parseFloat(e.target.value) || 0
                                  )
                                }
                                min={0}
                                step={0.01}
                                className="w-full text-right px-3 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(ligne).toFixed(2)} €
                            </td>
                            <td className="px-1 py-3 text-center">
                              <button
                                onClick={() => supprimerLigne(index)}
                                disabled={editLignes.length === 1}
                                className="p-2 text-gray-400 rounded-lg transition-colors hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 disabled:opacity-30 disabled:cursor-not-allowed"
                              >
                                <Trash2 className="w-4 h-4" />
                              </button>
                            </td>
                          </tr>
                        ))
                        : commande.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 text-right align-top">
                              {item.article_code}
                              {item.designation && (
                                <div className="mt-1 ml-9 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">
                              {item.quantite}
                            </td>
                            <td className="px-4 py-3 pt-5 font-mono text-sm font-bold text-right align-top">
                              {item.prix_unitaire_ht?.toFixed(2)} €
                            </td>
                            <td className="px-4 py-3 pt-5 text-sm text-right text-gray-600 align-top">
                              0%
                            </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?.toFixed(2)} €
                            </td>
                          </tr>
                        )) || (
                          <tr>
                            <td
                              colSpan={6}
                              className="py-4 text-center text-gray-500"
                            >
                              Aucune ligne
                            </td>
                          </tr>
                        )}
                    </tbody>
                  </table>
                </div>

                {/* Bouton ajouter ligne + Totaux */}
                <div className="flex justify-between items-start">
                  {isEditing && (
                    <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>
                  )}
                  {!isEditing && <div />}

                  <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">
                        {displayTotalHT.toLocaleString("fr-FR", {
                          minimumFractionDigits: 2,
                        })}
                        €
                      </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">
                        {displayTotalTVA.toLocaleString("fr-FR", {
                          minimumFractionDigits: 2,
                        })}
                        €
                      </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">
                        {displayTotalTTC.toLocaleString("fr-FR", {
                          minimumFractionDigits: 2,
                        })}
                        €
                      </span>
                    </div>
                  </div>
                </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">
                        {commande.lignes?.length}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            )}

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

            {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">
                            Bon_Commande_Client_{commande.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(commande.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>
            )}
          </div>
        </div>
      </div>

      {/* MODALS */}

      <ModalCommandetoFacture
        open={isOpenBLToFacture}
        onClose={() => setIsOpenBLToFacture(false)}
      />

      <ModalWorkflowToBL
        open={isOpenWorkflowToBL}
        onClose={() => setIsOpenWorkflowToBL(false)}
      />

      <PDFPreviewModal
        isOpen={isOpen}
        onClose={closePreview}
        pdfUrl={pdfUrl}
        fileName={fileName}
      />

      <ModalStatus
        open={openStatus}
        onClose={() => setOpenStatus(false)}
        type_doc={SageDocumentType.BON_COMMANDE}
      />

      {(loadingTransform || isSaving) && <ModalLoading />}
    </>
  );
};

export default OrderDetailPage;
