import { CheckCircle, Clock, Copy, Euro, Eye, FileText, Plus, TrendingUp, X } from 'lucide-react';
import { toast } from '@/components/ui/use-toast';
import { CompanyInfo } from '@/data/mockData';
import PrimaryButton_v2 from '@/components/PrimaryButton_v2';
import { useNavigate } from 'react-router-dom';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { useEffect, useMemo, useState } from 'react';
import { BLStatus, getAllBLs, getBLSelected } from '@/store/features/bl/selectors';
import { BL, BLRequest, BLResponse } from '@/types/BL_Types';
import { createBL, getAllBL, getBL, selectBLAsync } from '@/store/features/bl/thunk';
import { filterItemByPeriod, getPreviousPeriodItems } from '@/components/filter/ItemsFilter';
import { cn, formatDateFRCourt } from '@/lib/utils';
import { Helmet } from 'react-helmet';
import KPIBar, { PeriodType } from '@/components/KPIBar';
import DataTable from '@/components/DataTable';
import { ModalBL } from '@/components/modal/ModalBL';
import { DropdownMenuTable } from '@/components/DropdownMenu';
import { Client } from '@/types/clientType';
import { clientStatus, getAllClients } from '@/store/features/client/selectors';
import { articleStatus } from '@/store/features/article/selectors';
import { getArticles } from '@/store/features/article/thunk';
import { getClients } from '@/store/features/client/thunk';
import PDFPreview, { DocumentData } from '@/components/modal/PDFPreview';
import { usePDFPreview } from '@/components/ui/PDFActionButtons';
import { selectBL } from '@/store/features/bl/slice';
import { ModalLoading } from '@/components/modal/ModalLoading';
import FormModal from '@/components/ui/FormModal';
import ModalStatus from '@/components/modal/ModalStatus';
import StatusBadge, { STATUS_LABELS } from '@/components/ui/StatusBadge';
import { SageDocumentType } from '@/types/sageTypes';
import ColumnSelector, { ColumnConfig } from '@/components/common/ColumnSelector';
import PeriodSelector from '@/components/common/PeriodSelector';
import ExportDropdown from '@/components/common/ExportDropdown';
import { useDashboardData } from '@/store/hooks/useAppData';
import AdvancedFilters from '@/components/common/AdvancedFilters';
import { Commercial } from '@/types/commercialType';
import { commercialsStatus, getAllcommercials } from '@/store/features/commercial/selectors';
import { getCommercials } from '@/store/features/commercial/thunk';

// ============================================
// CONSTANTES
// ============================================

const COLORS = {
  gray: 'bg-gray-400',
  yellow: 'bg-yellow-400',
  orange: 'bg-orange-400',
  green: 'bg-green-400',
  purple: 'bg-purple-400',
  blue: 'bg-blue-400',
};

// Labels de statut pour les BL
const BL_STATUS_LABELS = {
  0: { label: 'Saisi', color: COLORS.gray },
  1: { label: 'Confirmé', color: COLORS.yellow },
  2: { label: 'A Facturer', color: COLORS.blue },
  // 3: { label: 'Facturé', color: COLORS.green },
  // 4: { label: 'Soldé', color: COLORS.purple },
} as const;

export type StatusCode = keyof typeof BL_STATUS_LABELS;
type FilterType = 'all' | 'delivered' | 'pending' | 'toInvoice' | 'invoiced';

interface KPIConfig {
  id: FilterType;
  title: string;
  icon: React.ElementType;
  color: string;
  getValue: (bls: BL[]) => number | string;
  getSubtitle: (bls: BL[], value: number | string) => string;
  getChange: (bls: BL[], value: number | string, period: PeriodType, allBLs: BL[]) => string;
  getTrend: (bls: BL[], value: number | string, period: PeriodType, allBLs: BL[]) => 'up' | 'down' | 'neutral';
  filter: (bls: BL[]) => BL[];
  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: (bls) => Math.round(bls.reduce((sum, item) => sum + item.total_ht, 0)),
    getSubtitle: (bls) => {
      const totalTTC = bls.reduce((sum, item) => sum + item.total_ttc, 0);
      return `${totalTTC.toLocaleString('fr-FR', { minimumFractionDigits: 2 })}€ TTC`;
    },
    getChange: (bls, value, period, allBLs) => {
      const previousPeriodBL = getPreviousPeriodItems(allBLs, period);
      const previousTotalHT = previousPeriodBL.reduce((sum, item) => sum + item.total_ht, 0);
      return previousTotalHT > 0 ? (((Number(value) - previousTotalHT) / previousTotalHT) * 100).toFixed(1) : '0';
    },
    getTrend: (bls, value, period, allBLs) => {
      const previousPeriodBL = getPreviousPeriodItems(allBLs, period);
      const previousTotalHT = previousPeriodBL.reduce((sum, item) => sum + item.total_ht, 0);
      return Number(value) >= previousTotalHT ? 'up' : 'down';
    },
    filter: (bls) => bls,
    tooltip: { content: 'Total des BL sur la période.', source: 'Ventes > Bon de livraisons' },
  },
  {
    id: 'pending',
    title: 'Nombre de BL',
    icon: FileText,
    color: 'orange',
    getValue: (bls) => bls.length,
    getSubtitle: (bls) => {
      const delivered = bls.filter(b => b.statut === 3 || b.statut === 4);
      const deliveryRate = bls.length > 0 ? ((delivered.length / bls.length) * 100).toFixed(1) : '0';
      return `${deliveryRate}% livrés`;
    },
    getChange: (bls, value, period, allBLs) => {
      const previousPeriodBL = getPreviousPeriodItems(allBLs, period);
      const countChange = Number(value) - previousPeriodBL.length;
      return countChange !== 0 ? `${countChange > 0 ? '+' : ''}${countChange}` : '0';
    },
    getTrend: (bls, value, period, allBLs) => {
      const previousPeriodBL = getPreviousPeriodItems(allBLs, period);
      return Number(value) >= previousPeriodBL.length ? 'up' : 'down';
    },
    filter: (bls) => bls,
  },
  {
    id: 'delivered',
    title: 'BL à facturer',
    icon: CheckCircle,
    color: 'green',
    getValue: (bls) => bls.filter(b => b.statut === 2).length,
    getSubtitle: (bls) => {
      const delivered = bls.filter(b => b.statut === 3 || b.statut === 4);
      const deliveredAmount = delivered.reduce((sum, item) => sum + item.total_ht, 0);
      return `${deliveredAmount.toLocaleString('fr-FR', { maximumFractionDigits: 0 })}€`;
    },
    getChange: (bls, value, period, allBLs) => {
      const previousPeriodBL = getPreviousPeriodItems(allBLs, period);
      const previousDelivered = previousPeriodBL.filter(b => b.statut === 3 || b.statut === 4);
      const deliveredChange = Number(value) - previousDelivered.length;
      return deliveredChange !== 0 ? `${deliveredChange > 0 ? '+' : ''}${deliveredChange}` : '';
    },
    getTrend: (bls, value, period, allBLs) => {
      const previousPeriodBL = getPreviousPeriodItems(allBLs, period);
      const previousDelivered = previousPeriodBL.filter(b => b.statut === 3 || b.statut === 4);
      return Number(value) >= previousDelivered.length ? 'up' : 'down';
    },
    filter: (bls) => bls.filter(b => b.statut === 2),
  },
  {
    id: 'invoiced',
    title: 'Montant Facturé',
    icon: TrendingUp,
    color: 'blue',
    getValue: (bls) => {
      const invoiced = bls.filter(b => b.statut === 2);
      return Math.round(invoiced.reduce((sum, item) => sum + item.total_ht, 0));
    },
    getSubtitle: (bls) => {
      const invoiced = bls.filter(b => b.statut === 2);
      return `${invoiced.length} BL facturé${invoiced.length > 1 ? 's' : ''}`;
    },
    getChange: (bls, value, period, allBLs) => {
      const previousPeriodBL = getPreviousPeriodItems(allBLs, period);
      const previousInvoiced = previousPeriodBL.filter(b => b.statut === 2);
      const previousInvoicedAmount = previousInvoiced.reduce((sum, item) => sum + item.total_ht, 0);
      return previousInvoicedAmount > 0
        ? (((Number(value) - previousInvoicedAmount) / previousInvoicedAmount) * 100).toFixed(1)
        : '0';
    },
    getTrend: (bls, value, period, allBLs) => {
      const previousPeriodBL = getPreviousPeriodItems(allBLs, period);
      const previousInvoiced = previousPeriodBL.filter(b => b.statut === 2);
      const previousInvoicedAmount = previousInvoiced.reduce((sum, item) => sum + item.total_ht, 0);
      return Number(value) >= previousInvoicedAmount ? 'up' : 'down';
    },
    filter: (bls) => bls.filter(b => b.statut === 2),
    tooltip: { content: 'Total des BL facturés sur la période.', source: 'Ventes > Bon de livraisons' },
  },
];

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

const DeliveryNotesPage = () => {
  const navigate = useNavigate();
  const { showPreview, openPreview, closePreview } = usePDFPreview();
  const dispatch = useAppDispatch();
  const [period, setPeriod] = useState<PeriodType>('all');
  const [activeFilter, setActiveFilter] = useState<FilterType>('all');
  const [activeFilters, setActiveFilters] = useState<Record<string, string[] | undefined>>({});

  // État des colonnes visibles
  const [columnConfig, setColumnConfig] = useState<ColumnConfig[]>(DEFAULT_COLUMNS);

  const BLs = useAppSelector(getAllBLs) as BL[];
  const clients = useAppSelector(getAllClients) as Client[];
  const commercials = useAppSelector(getAllcommercials) as Commercial[];
  const [openStatus, setOpenStatus] = useState(false);
  const bl = useAppSelector(getBLSelected) as BL;
  const statusBL = useAppSelector(BLStatus);
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const [editing, setEditing] = useState<BL | null>(null);

  const isLoading = statusBL === 'loading' && BLs.length === 0;

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

  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 { refresh } = useDashboardData();

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

  // ============================================
  // OPTIONS POUR LES FILTRES
  // ============================================

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

  // Map pour retrouver le commercial d'un client rapidement
  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]);

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

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

  const kpis = useMemo(() => {
    const periodFilteredBL = filterItemByPeriod(BLs, period, 'date');

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

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

  const filteredBL = useMemo(() => {
    // 1. Filtrer par période
    let result = filterItemByPeriod(BLs, 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());
  }, [BLs, 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]);

  const pdfData = useMemo(() => {
    if (!bl) return null;
    return {
      numero: bl.numero,
      type: 'bl' as const,
      date: bl.date,
      client: {
        code: bl.client_code,
        nom: bl.client_intitule,
        adresse: bl.client_adresse,
        code_postal: bl.client_code_postal,
        ville: bl.client_ville,
        email: bl.client_email,
        telephone: bl.client_telephone,
      },
      reference_externe: bl.reference,
      lignes: (bl.lignes ?? []).map(l => ({
        article: l.article_code,
        designation: l.designation,
        quantite: l.quantite,
        prix_unitaire: l.prix_unitaire_ht ?? 0,
        tva: 20,
        total_ht: l.quantite * (l.prix_unitaire_ht ?? 0),
      })),
      total_ht: bl.total_ht_calcule,
      total_tva: bl.total_taxes_calcule,
      total_ttc: bl.total_ttc_calcule,
    };
  }, [bl]) as DocumentData;

  // ============================================
  // COLONNES DYNAMIQUES
  // ============================================

  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">{value.toLocaleString()}€</span>,
      },
      statut: {
        key: 'statut',
        label: 'Statut',
        sortable: true,
        render: (value: number) => <StatusBadge status={value} type_doc={SageDocumentType.BON_LIVRAISON} />,
      },
    };
  }, [clients]);

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

  // Formateurs personnalisés pour transformer les valeurs à l'export
  const columnFormatters: Record<string, (value: any, row: any) => string> = {
    date: value => {
      if (!value) return '';
      return formatDateFRCourt(value);
    },
    total_ht_calcule: value => {
      if (value === null || value === undefined) return '0 €';
      return `${value.toLocaleString('fr-FR', { minimumFractionDigits: 2 })} €`;
    },
    total_taxes_calcule: value => {
      if (value === null || value === undefined) return '0 €';
      return `${value.toLocaleString('fr-FR', { minimumFractionDigits: 2 })} €`;
    },
    total_ttc_calcule: value => {
      if (value === null || value === undefined) return '0 €';
      return `${value.toLocaleString('fr-FR', { minimumFractionDigits: 2 })} €`;
    },
    statut: value => {
      return BL_STATUS_LABELS[value as StatusCode]?.label || 'Inconnu';
    },
    client_intitule: (value, row) => {
      return value || row.client_code || '';
    },
  };

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

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

  const openPDF = async (row: BL) => {
    await dispatch(selectBLAsync(row)).unwrap();
    openPreview();
  };

  const onDuplicate = async () => {
    try {
      setLoading(true);
      const payloadCreate: BLRequest = {
        client_id: bl.client_code,
        date_livraison: (() => {
          const d = new Date();
          d.setDate(d.getDate() + 1);
          return d.toISOString().split('T')[0];
        })(),
        reference: bl.reference,
        lignes: bl.lignes!.map(ligne => ({
          article_code: ligne.article_code,
          quantite: ligne.quantite,
        })),
      };

      const result = (await dispatch(createBL(payloadCreate)).unwrap()) as BLResponse;
      const data = result.data;

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

      const itemCreated = (await dispatch(getBL(data.numero_livraison)).unwrap()) as any;
      const res = itemCreated as BL;
      dispatch(selectBL(res));

      toast({
        title: 'BL dupliqué avec succès !',
        description: `Un nouveau BL ${itemCreated.numero_livraison} a été créé avec succès.`,
        className: 'bg-green-500 text-white border-green-600',
      });

      setLoading(false);
      setIsDuplicate(false);
      navigate(`/home/bons-livraison/${data.numero_livraison}`);
    } catch (err: any) {
      setLoading(false);
      setIsDuplicate(false);
    }
  };

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

    return (
      <>
        <button
          onClick={() => openPDF(row)}
          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(selectBLAsync(row)).unwrap();
            setIsDuplicate(true);
          }}
        />
      </>
    );
  };

  return (
    <>
      <Helmet>
        <title>Bons de livraison - {CompanyInfo.name}</title>
        <meta name="description" content="Gestion des bons de livraison" />
      </Helmet>
      <div className="space-y-6">
        <KPIBar kpis={kpis} period={period} loading={statusBL} 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">Bons de livraison</h1>
                {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">
                {filteredBL.length} bon{filteredBL.length > 1 ? 's' : ''} de livraison
                {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={filteredBL} columns={columnConfig} columnFormatters={columnFormatters} filename="BL" />
            <AdvancedFilters
              filters={filterDefinitions}
              activeFilters={activeFilters}
              onFilterChange={(key, values) => {
                setActiveFilters(prev => ({
                  ...prev,
                  [key]: values,
                }));
              }}
              onReset={() => setActiveFilters({})}
            />
            <PrimaryButton_v2 icon={Plus} onClick={handleCreate}>
              Nouveau bon de livraison
            </PrimaryButton_v2>
          </div>
        </div>

        <DataTable
          columns={visibleColumns}
          data={filteredBL}
          onRowClick={async (row: BL) => {
            await dispatch(selectBLAsync(row)).unwrap();
            navigate(`/home/bons-livraison/${row.numero}`);
          }}
          actions={actions}
          status={isLoading}
        />
      </div>

      <ModalBL
        open={isCreateModalOpen}
        onClose={() => setIsCreateModalOpen(false)}
        title={editing ? `Mettre à jour le bon de livraison ${editing.numero}` : 'Créer un bon de livraison'}
        editing={editing}
      />

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

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

      <FormModal
        isOpen={isDuplicate}
        onClose={() => setIsDuplicate(false)}
        title={`Dupliquer le BL ${bl?.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 ce bon de livraison</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é BL</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">
              {bl?.lignes ? (
                bl?.lignes.map((item, i) => (
                  <tr key={i} className="hover:bg-gray-50/50">
                    <td className="px-4 py-3">
                      <div className="font-medium text-gray-900 dark:text-white">{item.designation}</div>
                      <div className="text-xs text-gray-500">{item.article_code}</div>
                    </td>
                    <td className="px-4 py-3 text-right text-gray-600">{item.quantite}</td>
                    <td className="px-4 py-3 text-right 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]">{bl?.total_ht_calcule?.toFixed(2)} €</td>
              </tr>
            </tfoot>
          </table>
        </div>
      </FormModal>

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

export default DeliveryNotesPage;