import React, { ReactNode, useEffect, useMemo, useState } from 'react';
import { Helmet } from 'react-helmet';
import { Plus, ShoppingCart, CheckSquare, AlertCircle, Euro, Eye, Copy, X } from 'lucide-react';
import KPIBar, { PeriodType } from '@/components/KPIBar';
import PrimaryButton_v2 from '@/components/PrimaryButton_v2';
import DataTable from '@/components/DataTable';
import { Commande, CommandeRequest, CommandeResponse } from '@/types/commandeTypes';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { useNavigate } from 'react-router-dom';
import { commandeStatus, getAllcommandes, getcommandeSelected } from '@/store/features/commande/selectors';
import { createCommande, getCommande, getCommandes, selectCommandeAsync } from '@/store/features/commande/thunk';
import { cn, formatDateFRCourt } from '@/lib/utils';
import { filterItemByPeriod, getPreviousPeriodItems } from '@/components/filter/ItemsFilter';
import { DropdownMenuTable } from '@/components/DropdownMenu';
import { ModalCommande } from '@/components/modal/ModalCommande';
import { clientStatus, getAllClients } from '@/store/features/client/selectors';
import { Client } from '@/types/clientType';
import { selectcommande } from '@/store/features/commande/slice';
import { toast } from '@/components/ui/use-toast';
import FormModal from '@/components/ui/FormModal';
import { ModalLoading } from '@/components/modal/ModalLoading';
import PeriodSelector from '@/components/common/PeriodSelector';
import AdvancedFilters from '@/components/common/AdvancedFilters';
import { articleStatus } from '@/store/features/article/selectors';
import { getArticles } from '@/store/features/article/thunk';
import { getClients } from '@/store/features/client/thunk';
import ModalStatus from '@/components/modal/ModalStatus';
import StatusBadge from '@/components/ui/StatusBadge';
import { SageDocumentType } from '@/types/sageTypes';
import ColumnSelector, { ColumnConfig } from '@/components/common/ColumnSelector';
import ExportDropdown from '@/components/common/ExportDropdown';
import { Commercial } from '@/types/commercialType';
import { commercialsStatus, getAllcommercials } from '@/store/features/commercial/selectors';
import { getCommercials } from '@/store/features/commercial/thunk';
import { useDashboardData } from '@/store/hooks/useAppData';

export const STATUS_LABELS_COMMANDE = {
  0: { label: 'Saisi', color: 'bg-gray-400' },
  1: { label: 'Confirmé', color: 'bg-yellow-400' },
  2: { label: 'A préparer', color: 'bg-green-400' },
  5: { label: 'Préparé', color: 'bg-gray-500' },
} as const;

export type StatusCodeCommande = keyof typeof STATUS_LABELS_COMMANDE;

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

type FilterType = 'all' | 'count' | 'delivered' | 'pending' | 'deliveredAmount';

interface KPIConfig {
  id: FilterType;
  title: string;
  icon: React.ElementType;
  color: string;
  getValue: (commandes: Commande[]) => number;
  getSubtitle: (commandes: Commande[], value: number) => string;
  getChange: (commandes: Commande[], value: number, period: PeriodType, allCommandes: Commande[]) => string;
  getTrend: (commandes: Commande[], value: number, period: PeriodType, allCommandes: Commande[]) => 'up' | 'down' | 'neutral';
  filter: (commandes: Commande[]) => Commande[];
  tooltip?: { content: string; source: string };
}

// ============================================
// CONFIGURATION DES COLONNES
// ============================================

const DEFAULT_COLUMNS: ColumnConfig[] = [
  { key: 'numero', label: 'Numéro', visible: true, locked: true },
  { key: 'client_code', label: 'Client', visible: true },
  { key: 'date', label: 'Date', visible: true },
  { key: 'total_ht_calcule', label: 'Montant HT', visible: true },
  { key: 'total_taxes_calcule', label: 'Montant TVA', visible: true },
  { key: 'total_ttc_calcule', label: 'Montant TTC', visible: true },
  { key: 'statut', label: 'Statut', visible: true },
];

// ============================================
// CONFIGURATION DES KPIs
// ============================================

const KPI_CONFIG: KPIConfig[] = [
  {
    id: 'all',
    title: 'Total HT',
    icon: Euro,
    color: 'blue',
    getValue: (commandes) => Math.round(commandes.reduce((sum, item) => sum + item.total_ht, 0)),
    getSubtitle: (commandes) => {
      const totalTTC = commandes.reduce((sum, item) => sum + item.total_ttc, 0);
      return `${totalTTC.toLocaleString('fr-FR')}€ TTC`;
    },
    getChange: (commandes, value, period, allCommandes) => {
      const previousPeriodCommandes = getPreviousPeriodItems(allCommandes, period);
      const previousTotalHT = previousPeriodCommandes.reduce((sum, item) => sum + item.total_ht, 0);
      return previousTotalHT > 0 ? (((value - previousTotalHT) / previousTotalHT) * 100).toFixed(1) : '0';
    },
    getTrend: (commandes, value, period, allCommandes) => {
      const previousPeriodCommandes = getPreviousPeriodItems(allCommandes, period);
      const previousTotalHT = previousPeriodCommandes.reduce((sum, item) => sum + item.total_ht, 0);
      return value >= previousTotalHT ? 'up' : 'down';
    },
    filter: (commandes) => commandes,
    tooltip: { content: "Total des commandes sur la période.", source: "Ventes > Commandes" }
  },
  {
    id: 'count',
    title: 'Nombre Commandes',
    icon: ShoppingCart,
    color: 'purple',
    getValue: (commandes) => commandes.length,
    getSubtitle: (commandes) => {
      const avgCommande = commandes.length > 0 
        ? commandes.reduce((sum, item) => sum + item.total_ht, 0) / commandes.length 
        : 0;
      return `${avgCommande.toLocaleString('fr-FR', { maximumFractionDigits: 0 })}€ moyen`;
    },
    getChange: (commandes, value, period, allCommandes) => {
      const previousPeriodCommandes = getPreviousPeriodItems(allCommandes, period);
      const countChange = value - previousPeriodCommandes.length;
      return countChange !== 0 ? `${countChange > 0 ? '+' : ''}${countChange}` : '0';
    },
    getTrend: (commandes, value, period, allCommandes) => {
      const previousPeriodCommandes = getPreviousPeriodItems(allCommandes, period);
      return value >= previousPeriodCommandes.length ? 'up' : 'down';
    },
    filter: (commandes) => commandes,
  },
  {
    id: 'delivered',
    title: 'Commandes à préparer',
    icon: CheckSquare,
    color: 'green',
    getValue: (commandes) => commandes.filter(c => c.statut === 2).length,
    getSubtitle: (commandes) => {
      const delivered = commandes.filter(c => c.statut === 2);
      const deliveredAmount = delivered.reduce((sum, item) => sum + item.total_ht, 0);
      return `${deliveredAmount.toLocaleString('fr-FR', { maximumFractionDigits: 0 })}€`;
    },
    getChange: (commandes, value, period, allCommandes) => {
      const previousPeriodCommandes = getPreviousPeriodItems(allCommandes, period);
      const previousDelivered = previousPeriodCommandes.filter(c => c.statut === 2);
      const deliveredChange = value - previousDelivered.length;
      return deliveredChange !== 0 ? `${deliveredChange > 0 ? '+' : ''}${deliveredChange}` : '';
    },
    getTrend: (commandes, value, period, allCommandes) => {
      const previousPeriodCommandes = getPreviousPeriodItems(allCommandes, period);
      const previousDelivered = previousPeriodCommandes.filter(c => c.statut === 2);
      return value >= previousDelivered.length ? 'up' : 'down';
    },
    filter: (commandes) => commandes.filter(c => c.statut === 2),
  },
  {
    id: 'pending',
    title: 'Commandes à confirmer',
    icon: AlertCircle,
    color: 'orange',
    getValue: (commandes) => commandes.filter(c => c.statut === 1).length,
    getSubtitle: (commandes) => {
      const pending = commandes.filter(c => c.statut === 1);
      const pendingAmount = pending.reduce((sum, item) => sum + item.total_ht, 0);
      return `${pendingAmount.toLocaleString('fr-FR', { maximumFractionDigits: 0 })}€`;
    },
    getChange: (commandes, value, period, allCommandes) => {
      const previousPeriodCommandes = getPreviousPeriodItems(allCommandes, period);
      const previousPending = previousPeriodCommandes.filter(c => c.statut === 1);
      const pendingChange = value - previousPending.length;
      return pendingChange !== 0 ? `${pendingChange > 0 ? '+' : ''}${pendingChange}` : '';
    },
    getTrend: (commandes, value, period, allCommandes) => {
      const previousPeriodCommandes = getPreviousPeriodItems(allCommandes, period);
      const previousPending = previousPeriodCommandes.filter(c => c.statut === 1);
      // Pour les en cours, moins c'est mieux
      return value <= previousPending.length ? 'up' : 'down';
    },
    filter: (commandes) => commandes.filter(c => c.statut === 1),
  },
  {
    id: 'deliveredAmount',
    title: 'Montant Livré',
    icon: CheckSquare,
    color: 'green',
    getValue: (commandes) => {
      const delivered = commandes.filter(c => c.statut === 2);
      return Math.round(delivered.reduce((sum, item) => sum + item.total_ht, 0));
    },
    getSubtitle: (commandes) => {
      const delivered = commandes.filter(c => c.statut === 2);
      return `${delivered.length} commande${delivered.length > 1 ? 's' : ''}`;
    },
    getChange: (commandes, value, period, allCommandes) => {
      const previousPeriodCommandes = getPreviousPeriodItems(allCommandes, period);
      const previousDelivered = previousPeriodCommandes.filter(c => c.statut === 2);
      const previousDeliveredValue = previousDelivered.reduce((sum, item) => sum + item.total_ht, 0);
      return previousDeliveredValue > 0 ? (((value - previousDeliveredValue) / previousDeliveredValue) * 100).toFixed(1) : '0';
    },
    getTrend: (commandes, value, period, allCommandes) => {
      const previousPeriodCommandes = getPreviousPeriodItems(allCommandes, period);
      const previousDelivered = previousPeriodCommandes.filter(c => c.statut === 2);
      const previousDeliveredValue = previousDelivered.reduce((sum, item) => sum + item.total_ht, 0);
      return value >= previousDeliveredValue ? 'up' : 'down';
    },
    filter: (commandes) => commandes.filter(c => c.statut === 2),
    tooltip: { content: "Total des commandes livrées sur la période.", source: "Ventes > Commandes" }
  },
];

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

const OrdersPage = () => {
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const [period, setPeriod] = useState<PeriodType>('all');
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const [openStatus, setOpenStatus] = useState(false);
  const [activeFilters, setActiveFilters] = useState<Record<string, string[] | undefined>>({});
  const [activeFilter, setActiveFilter] = useState<FilterType>('all');

  const [columnConfig, setColumnConfig] = useState<ColumnConfig[]>(DEFAULT_COLUMNS);

  const commandes = useAppSelector(getAllcommandes) as Commande[];
  const commercials = useAppSelector(getAllcommercials) as Commercial[];
  const statusCommande = useAppSelector(commandeStatus);
  const commandeSelected = useAppSelector(getcommandeSelected) as Commande;
  const [editing, setEditing] = useState<Commande | null>(null);

  const [isDuplicate, setIsDuplicate] = useState(false);
  const [loading, setLoading] = useState(false);

  const clients = useAppSelector(getAllClients) as Client[];
  const statusClient = useAppSelector(clientStatus);
  const statusArticle = useAppSelector(articleStatus);
  const statusCommercial = useAppSelector(commercialsStatus);

  useEffect(() => {
    const load = async () => {
      try {
        if (statusArticle === 'idle') await dispatch(getArticles()).unwrap();
        if (statusClient === 'idle' || statusClient === 'failed') await dispatch(getClients()).unwrap();
        if (statusCommercial === 'idle') await dispatch(getCommercials()).unwrap();
      } catch (error) {
        console.error(error);
      }
    };
    load();
  }, [statusArticle, statusClient, statusCommercial, dispatch]);

  const isLoading = statusCommande === 'loading' && commandes.length === 0 && statusClient === 'loading';

  useEffect(() => {
    const load = async () => {
      if (statusCommande === 'idle') await dispatch(getCommandes()).unwrap();
    };
    load();
  }, [statusCommande, dispatch]);

  const { refresh } = useDashboardData();

  const commercialOptions = useMemo(() => {
    return commercials.map(c => ({
      value: c.numero.toString(),
      label: `${c.prenom || ''} ${c.nom || ''}`.trim() || `Commercial ${c.numero}`,
    }));
  }, [commercials]);

  const filterDefinitions = [
    {
      key: 'status',
      label: 'Statut',
      options: (Object.entries(STATUS_LABELS_COMMANDE) as [string, (typeof STATUS_LABELS_COMMANDE)[StatusCodeCommande]][]).map(
        ([value, { label, color }]) => ({
          value: value.toString(),
          label,
          color,
        })
      ),
    },
    {
      key: 'rep',
      label: 'Commercial',
      options: commercialOptions,
    },
  ];

  const clientCommercialMap = useMemo(() => {
    const map = new Map<string, string>();
    clients.forEach(client => {
      if (client.commercial?.numero) {
        map.set(client.numero, client.commercial.numero.toString());
      }
    });
    return map;
  }, [clients]);

  // ============================================
  // KPIs avec onClick
  // ============================================

  const kpis = useMemo(() => {
    const periodFilteredCommandes = filterItemByPeriod(commandes, period, 'date');

    return KPI_CONFIG.map(config => {
      const value = config.getValue(periodFilteredCommandes);
      return {
        id: config.id,
        title: config.title,
        value: config.id === 'all' || config.id === 'deliveredAmount' ? `${value.toLocaleString('fr-FR')}€` : value,
        change: config.getChange(periodFilteredCommandes, value, period, commandes),
        trend: config.getTrend(periodFilteredCommandes, value, period, commandes),
        icon: config.icon,
        subtitle: config.getSubtitle(periodFilteredCommandes, value),
        color: config.color,
        tooltip: config.tooltip,
        isActive: activeFilter === config.id,
        onClick: () => setActiveFilter(prev => (prev === config.id ? 'all' : config.id)),
      };
    });
  }, [commandes, period, activeFilter]);

  // ============================================
  // Filtrage combiné : Période + KPI + Filtres avancés
  // ============================================

  const filteredCommandes = useMemo(() => {
    // 1. Filtrer par période
    let result = filterItemByPeriod(commandes, period, 'date');

    // 2. Filtrer par KPI actif
    const kpiConfig = KPI_CONFIG.find(k => k.id === activeFilter);
    if (kpiConfig && activeFilter !== 'all') {
      result = kpiConfig.filter(result);
    }

    // 3. Filtres avancés (statut)
    if (activeFilters.status && activeFilters.status.length > 0) {
      result = result.filter(item => activeFilters.status!.includes(item.statut.toString()));
    }

    // 4. Filtre par commercial
    if (activeFilters.rep && activeFilters.rep.length > 0) {
      result = result.filter(item => {
        const commercialCode = clientCommercialMap.get(item.client_code);
        return commercialCode && activeFilters.rep!.includes(commercialCode);
      });
    }

    // 5. Tri par date décroissante
    return [...result].sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
  }, [commandes, period, activeFilter, activeFilters, clientCommercialMap]);

  // ============================================
  // Label du filtre actif
  // ============================================

  const activeFilterLabel = useMemo(() => {
    const config = KPI_CONFIG.find(k => k.id === activeFilter);
    return config?.title || 'Tous';
  }, [activeFilter]);

  // ... reste du code inchangé (allColumnsDefinition, visibleColumns, columnFormatters, onDuplicate, actions, etc.)

  const allColumnsDefinition = useMemo(() => {
    const clientsMap = new Map(clients.map(c => [c.numero, c]));

    return {
      numero: { key: 'numero', label: 'Numéro', sortable: true },
      client_code: {
        key: 'client_code',
        label: 'Client',
        sortable: true,
        render: (clientCode: string) => {
          const client = clientsMap.get(clientCode);
          if (!client) return <span className="text-gray-400">{clientCode}</span>;
          const avatar = client.intitule?.charAt(0).toUpperCase() || '?';
          return (
            <div className="flex items-center gap-3">
              <div className="w-9 h-9 rounded-full bg-gray-100 dark:bg-gray-800 flex items-center justify-center text-xs font-bold text-gray-600 dark:text-gray-300">
                {avatar}
              </div>
              <div>
                <p className="text-sm font-medium text-gray-900 dark:text-white">{client.intitule}</p>
                <p className="text-xs text-gray-500">{client.email || client.telephone || clientCode}</p>
              </div>
            </div>
          );
        },
      },
      date: {
        key: 'date',
        label: 'Date',
        sortable: true,
        render: (date: string) => <span>{formatDateFRCourt(date)}</span>,
      },
      total_ht_calcule: {
        key: 'total_ht_calcule',
        label: 'Montant HT',
        sortable: true,
        render: (value: number) => `${value.toLocaleString()}€`,
      },
      total_taxes_calcule: {
        key: 'total_taxes_calcule',
        label: 'Montant TVA',
        sortable: true,
        render: (value: number) => `${value.toLocaleString()}€`,
      },
      total_ttc_calcule: {
        key: 'total_ttc_calcule',
        label: 'Montant TTC',
        sortable: true,
        render: (value: number) => <span className="font-medium text-[#007E45]">{value.toLocaleString()}€</span>,
      },
      statut: {
        key: 'statut',
        label: 'Statut',
        sortable: true,
        render: (value: number) => <StatusBadge status={value} type_doc={SageDocumentType.BON_COMMANDE} />,
      },
    };
  }, [clients]);

  const visibleColumns = useMemo(() => {
    return columnConfig
      .filter(col => col.visible)
      .map(col => allColumnsDefinition[col.key as keyof typeof allColumnsDefinition])
      .filter(Boolean);
  }, [columnConfig, allColumnsDefinition]);

  const columnFormatters: Record<string, (value: any, row: any) => string> = {
    date: value => (value ? formatDateFRCourt(value) : ''),
    total_ht_calcule: value => (value === null || value === undefined ? '0 €' : `${value.toLocaleString('fr-FR', { minimumFractionDigits: 2 })} €`),
    total_taxes_calcule: value => (value === null || value === undefined ? '0 €' : `${value.toLocaleString('fr-FR', { minimumFractionDigits: 2 })} €`),
    total_ttc_calcule: value => (value === null || value === undefined ? '0 €' : `${value.toLocaleString('fr-FR', { minimumFractionDigits: 2 })} €`),
    statut: value => STATUS_LABELS_COMMANDE[value as StatusCodeCommande]?.label || 'Inconnu',
    client_intitule: (value, row) => value || row.client_code || '',
  };

  const onDuplicate = async () => {
    try {
      setLoading(true);
      const payloadCreate: CommandeRequest = {
        client_id: commandeSelected.client_code,
        date_commande: (() => {
          const d = new Date();
          d.setDate(d.getDate() + 1);
          return d.toISOString().split('T')[0];
        })(),
        lignes: commandeSelected.lignes!.map(ligne => ({
          article_code: ligne.article_code,
          quantite: ligne.quantite,
        })),
        reference: commandeSelected.reference,
      };
      const result = (await dispatch(createCommande(payloadCreate)).unwrap()) as CommandeResponse;
      const data = result.data;
      await new Promise(resolve => setTimeout(resolve, 1500));
      const itemCreated = (await dispatch(getCommande(data.numero_commande)).unwrap()) as any;
      const res = itemCreated as Commande;
      dispatch(selectcommande(res));
      toast({
        title: 'Commande dupliquée avec succès !',
        description: `La commande ${commandeSelected.numero} a été dupliquée avec succès.`,
        className: 'bg-green-500 text-white border-green-600',
      });
      setLoading(false);
      setIsDuplicate(false);
      navigate(`/home/commandes/${data.numero_commande}`);
    } catch (err: any) {
      setLoading(false);
      setIsDuplicate(false);
    }
  };

  const actions = (row: Commande) => {
    const handleStatus =
      row.statut !== 2 && row.statut !== 3 && row.statut !== 4
        ? async () => {
            await dispatch(selectCommandeAsync(row)).unwrap();
            setOpenStatus(true);
          }
        : undefined;

    return (
      <>
        <button
          onClick={async () => {
            await dispatch(selectCommandeAsync(row)).unwrap();
            navigate(`/home/commandes/${row.numero}`);
          }}
          className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors text-gray-600 dark:text-gray-400"
          title="Voir"
        >
          <Eye className="w-4 h-4" />
        </button>
        <DropdownMenuTable
          row={row}
          onEdit={() => handleEdit(row)}
          onStatus={handleStatus}
          onDulipcate={async () => {
            await dispatch(selectCommandeAsync(row)).unwrap();
            setIsDuplicate(true);
          }}
        />
      </>
    );
  };

  const handleCreate = () => {
    setEditing(null);
    setIsCreateModalOpen(true);
  };

  const handleEdit = (row: Commande) => {
    setEditing(row);
    setIsCreateModalOpen(true);
  };

  return (
    <>
      <Helmet>
        <title>Commandes - Dataven</title>
        <meta name="description" content="Gestion de vos commandes" />
      </Helmet>
      <div className="space-y-6">
        <KPIBar kpis={kpis} period={period} loading={statusCommande} onRefresh={refresh} />

        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div className="flex items-center gap-4">
            <div>
              <div className="flex items-center gap-3">
                <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Commandes</h1>
                {/* Badge filtre actif */}
                {activeFilter !== 'all' && (
                  <button
                    onClick={() => setActiveFilter('all')}
                    className={cn(
                      'inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-medium transition-colors',
                      'bg-[#007E45]/10 text-[#007E45] hover:bg-[#007E45]/20'
                    )}
                  >
                    {activeFilterLabel}
                    <X className="w-3 h-3" />
                  </button>
                )}
              </div>
              <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
                {filteredCommandes.length} commande{filteredCommandes.length > 1 ? 's' : ''}
                {activeFilter !== 'all' && ` (${activeFilterLabel.toLowerCase()})`}
              </p>
            </div>
            <PeriodSelector value={period} onChange={setPeriod} />
          </div>
          <div className="flex gap-3 flex-wrap items-center">
            <ColumnSelector columns={columnConfig} onChange={setColumnConfig} />
            <ExportDropdown data={filteredCommandes} columns={columnConfig} columnFormatters={columnFormatters} filename="commande" />
            <AdvancedFilters
              filters={filterDefinitions}
              activeFilters={activeFilters}
              onFilterChange={(key, values) => {
                setActiveFilters(prev => ({ ...prev, [key]: values }));
              }}
              onReset={() => setActiveFilters({})}
            />
            <PrimaryButton_v2 icon={Plus} onClick={handleCreate}>
              Nouvelle commande
            </PrimaryButton_v2>
          </div>
        </div>

        <DataTable
          columns={visibleColumns}
          data={filteredCommandes}
          onRowClick={async (row: Commande) => {
            await dispatch(selectCommandeAsync(row)).unwrap();
            navigate(`/home/commandes/${row.numero}`);
          }}
          actions={actions}
          status={isLoading}
        />
      </div>

      <ModalCommande
        open={isCreateModalOpen}
        onClose={() => setIsCreateModalOpen(false)}
        title={editing ? `Mettre à jour la commande ${editing.numero}` : 'Créer une commande'}
        editing={editing}
      />

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

      <FormModal
        isOpen={isDuplicate}
        onClose={() => setIsDuplicate(false)}
        title={`Dupliquer la commande ${commandeSelected?.numero}`}
        onSubmit={onDuplicate}
        submitLabel="Dupliquer"
      >
        <div className="mb-6 p-4 bg-teal-50 text-teal-800 rounded-xl text-sm flex gap-3 border border-teal-200">
          <Copy className="w-5 h-5 shrink-0" />
          <p>Vous allez dupliquer cette commande</p>
        </div>
        <div className="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-xl overflow-hidden mb-6">
          <table className="w-full text-sm">
            <thead className="bg-gray-50 dark:bg-gray-900 border-b border-gray-200 dark:border-gray-800">
              <tr>
                <th className="px-4 py-3 text-left font-semibold text-gray-600">Article</th>
                <th className="px-4 py-3 text-right font-semibold text-gray-600">Qté Commande</th>
                <th className="px-4 py-3 text-right font-semibold text-gray-600">TVA</th>
                <th className="px-4 py-3 text-right font-semibold text-gray-600">Total HT</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100 dark:divide-gray-800">
              {commandeSelected?.lignes ? (
                commandeSelected?.lignes.map((item, i) => (
                  <tr key={i} className="hover:bg-gray-50/50">
                    <td className="px-4 py-3">
                      <div className="font-medium text-gray-900 dark:text-white">{item.designation}</div>
                      <div className="text-xs text-gray-500">{item.article_code}</div>
                    </td>
                    <td className="px-4 py-3 text-right text-gray-600">{item.quantite}</td>
                    <td className="px-4 py-3 text-right font-medium text-gray-900">20%</td>
                    <td className="px-4 py-3 text-right font-medium text-gray-900 dark:text-white">
                      {item.montant_ligne_ht!.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })} €
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={4} className="py-4 text-center text-gray-500">
                    Aucune ligne
                  </td>
                </tr>
              )}
            </tbody>
            <tfoot className="bg-gray-50 dark:bg-gray-900 border-t border-gray-200 dark:border-gray-800">
              <tr>
                <td colSpan={3} className="px-4 py-3 text-right font-bold text-gray-900 dark:text-white">
                  Total HT à générer
                </td>
                <td className="px-4 py-3 text-right font-bold text-[#007E45]">{commandeSelected?.total_ht_calcule?.toFixed(2)} €</td>
              </tr>
            </tfoot>
          </table>
        </div>
      </FormModal>

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

export default OrdersPage;