import React, { useState, useMemo, useEffect } from 'react';
import { Helmet } from 'react-helmet';
import { useNavigate } from 'react-router-dom';
import { Plus, Eye, FileText, Euro, Percent, CheckCircle, TrendingUp, Edit, X } from 'lucide-react';
import DataTable from '@/components/DataTable';
import KPIBar, { PeriodType } from '@/components/KPIBar';
import { toast } from '@/components/ui/use-toast';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { devisStatus, getAllDevis, getDevisSelected } from '@/store/features/devis/selectors';
import { createDevis, getDevisById, getDevisList, selectDevisAsync } from '@/store/features/devis/thunk';
import PrimaryButton_v2 from '@/components/PrimaryButton_v2';
import { DevisListItem, DevisRequest, DevisResponse } from '@/types/devisType';
import { ModalQuote } from '@/components/modal/ModalQuote';
import { cn, formatDateFRCourt } from '@/lib/utils';
import { filterItemByPeriod, getPreviousPeriodItems } from '@/components/filter/ItemsFilter';
import { DropdownMenuTable } from '@/components/DropdownMenu';
import { ModalStatus } from '@/components/modal/ModalStatus';
import { ModalLoading } from '@/components/modal/ModalLoading';
import { selectDevis } from '@/store/features/devis/slice';
import { Client } from '@/types/clientType';
import { clientStatus, getAllClients } from '@/store/features/client/selectors';
import FormModal from '@/components/ui/FormModal';
import PeriodSelector from '@/components/common/PeriodSelector';
import AdvancedFilters from '@/components/common/AdvancedFilters';
import { usePDFPreview } from '@/components/ui/PDFActionButtons';
import PDFPreview, { DocumentData } from '@/components/modal/PDFPreview';
import { CompanyInfo } from '@/data/mockData';
import StatusBadge from '@/components/ui/StatusBadge';
import { SageDocumentType, UniversignType } from '@/types/sageTypes';
import ColumnSelector, { ColumnConfig } from '@/components/common/ColumnSelector';
import { articleStatus, getAllArticles } from '@/store/features/article/selectors';
import { familleStatus } from '@/store/features/famille/selectors';
import { getArticles } from '@/store/features/article/thunk';
import { getfamilles } from '@/store/features/famille/thunk';
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 { getAlluniversign, universignStatus } from '@/store/features/universign/selectors';
import { getUniversigns } from '@/store/features/universign/thunk';
import { useDashboardData } from '@/store/hooks/useAppData';

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

export const STATUS_LABELS = {
  0: { label: 'Saisi', color: 'bg-gray-400' },
  1: { label: 'Confirmé', color: 'bg-yellow-400' },
  2: { label: 'Accepté', color: 'bg-green-400' },
  3: { label: 'Perdu', color: 'bg-red-400' },
  4: { label: 'Archivé', color: 'bg-orange-400' },
} as const;

export type StatusCode = keyof typeof STATUS_LABELS;

type FilterType = 'all' | 'accepted' | 'pending' | 'signed' | 'lost';

interface KPIConfig {
  id: FilterType;
  title: string;
  icon: React.ElementType;
  color: string;
  getValue: (devis: DevisListItem[], universign: UniversignType[]) => number;
  getSubtitle: (devis: DevisListItem[], value: number, universign?: UniversignType[]) => string;
  getChange: (devis: DevisListItem[], value: number, period: PeriodType, allDevis: DevisListItem[]) => string;
  getTrend: (devis: DevisListItem[], value: number, period: PeriodType, allDevis: DevisListItem[]) => 'up' | 'down' | 'neutral';
  filter: (devis: DevisListItem[], universign: UniversignType[]) => DevisListItem[];
  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: (devis) => Math.round(devis.reduce((sum, item) => sum + item.total_ht, 0)),
    getSubtitle: (devis) => {
      const totalTTC = devis.reduce((sum, item) => sum + item.total_ttc, 0);
      return `${totalTTC.toLocaleString('fr-FR', { minimumFractionDigits: 2 })}€ TTC`;
    },
    getChange: (devis, value, period, allDevis) => {
      const previousPeriodDevis = getPreviousPeriodItems(allDevis, period);
      const previousTotalHT = previousPeriodDevis.reduce((sum, item) => sum + item.total_ht, 0);
      return previousTotalHT > 0 ? ((value - previousTotalHT) / previousTotalHT * 100).toFixed(1) : '0';
    },
    getTrend: (devis, value, period, allDevis) => {
      const previousPeriodDevis = getPreviousPeriodItems(allDevis, period);
      const previousTotalHT = previousPeriodDevis.reduce((sum, item) => sum + item.total_ht, 0);
      return value >= previousTotalHT ? 'up' : 'down';
    },
    filter: (devis) => devis,
    tooltip: { content: "Total des devis sur la période.", source: "Ventes > Devis" }
  },
  {
    id: 'accepted',
    title: 'Devis Acceptés',
    icon: CheckCircle,
    color: 'green',
    getValue: (devis) => devis.filter(d => d.statut === 2).length,
    getSubtitle: (devis) => {
      const accepted = devis.filter(d => d.statut === 2);
      const acceptedAmount = accepted.reduce((sum, item) => sum + item.total_ht, 0);
      return `${acceptedAmount.toLocaleString('fr-FR', { maximumFractionDigits: 0 })}€`;
    },
    getChange: (devis, value, period, allDevis) => {
      const previousPeriodDevis = getPreviousPeriodItems(allDevis, period);
      const previousAccepted = previousPeriodDevis.filter(d => d.statut === 2);
      const acceptedChange = value - previousAccepted.length;
      return acceptedChange !== 0 ? `${acceptedChange > 0 ? '+' : ''}${acceptedChange}` : '';
    },
    getTrend: (devis, value, period, allDevis) => {
      const previousPeriodDevis = getPreviousPeriodItems(allDevis, period);
      const previousAccepted = previousPeriodDevis.filter(d => d.statut === 2);
      return value >= previousAccepted.length ? 'up' : 'down';
    },
    filter: (devis) => devis.filter(d => d.statut === 2),
  },
  {
    id: 'pending',
    title: 'Nombre de confirmé',
    icon: FileText,
    color: 'orange',
    // getValue: (devis) => {
    //    const avgDevis = devis.length > 0 
    //     ? devis.reduce((sum, item) => sum + item.total_ht, 0) / devis.length 
    //     : 0;
    //     return avgDevis.toString().length;

    // },
    getValue: (devis) => {
      const devisConfirmed = devis.filter(d => d.statut === 1);
      return devisConfirmed.length
    },
    getSubtitle: (devis) => {
      const avgDevis = devis.length > 0 
        ? devis.reduce((sum, item) => sum + item.total_ht, 0) / devis.length 
        : 0;
      return `${avgDevis.toLocaleString('fr-FR', { maximumFractionDigits: 0 })}€ moyen`;
    },
    getChange: (devis, value, period, allDevis) => {
      const previousPeriodDevis = getPreviousPeriodItems(allDevis, period);
      const countChange = value - previousPeriodDevis.length;
      return countChange !== 0 ? `${countChange > 0 ? '+' : ''}${countChange}` : '0';
    },
    getTrend: (devis, value, period, allDevis) => {
      const previousPeriodDevis = getPreviousPeriodItems(allDevis, period);
      return value >= previousPeriodDevis.length ? 'up' : 'down';
    },
    filter: (devis) => devis.filter(d => d.statut === 1),
  },
 {
  id: 'signed',
  title: 'Devis Signés',
  icon: Percent,
  color: 'purple',
  getValue: (devis, universign) => {
    // Créer un Set des IDs de documents signés
    const signedDocIds = new Set(
      universign
        .filter(u => u.local_status === "SIGNE")
        .map(u => u.sage_document_id)
    );
    // Compter uniquement les devis de la période qui sont signés
    return devis.filter(d => signedDocIds.has(d.numero)).length;
  },
  getSubtitle: (devis, value, universign) => {
    const pending = devis.filter(d => d.statut === 1).length;
    return `${pending} en attente`;
  },
  getChange: (devis, value) => {
    return `${value}/${devis.length}`;
  },
  getTrend: (devis, value) => {
    const acceptanceRate = devis.length > 0 ? (value / devis.length) * 100 : 0;
    return acceptanceRate >= 50 ? 'up' : 'down';
  },
  filter: (devis, universign) => {
    const signedDocIds = new Set(
      universign
        .filter(u => u.local_status === "SIGNE")
        .map(u => u.sage_document_id)
    );
    return devis.filter(d => signedDocIds.has(d.numero));
  },
},
];

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

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

  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const { showPreview, openPreview, closePreview } = usePDFPreview();
  const [openStatusDevis, setOpenStatusDevis] = useState(false);
  const [loadingPdf, setLoadingPdf] = useState(false);
  const [period, setPeriod] = useState<PeriodType>('all');
  const [isDuplicate, setIsDuplicate] = useState(false);
  const [loading, setLoading] = useState(false);

  // État du filtre actif
  const [activeFilter, setActiveFilter] = useState<FilterType>('all');

  const clients = useAppSelector(getAllClients) as Client[];
  const commercials = useAppSelector(getAllcommercials) as Commercial[];  
  const universign = useAppSelector(getAlluniversign) as UniversignType[];

  const statusClient = useAppSelector(clientStatus);
  const statusArticle = useAppSelector(articleStatus);
  const statusFamille = useAppSelector(familleStatus);
  const statusCommercial = useAppSelector(commercialsStatus);
  const statusUniversign = useAppSelector(universignStatus);

  const [activeFilters, setActiveFilters] = useState<Record<string, string[] | undefined>>({});

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

  const devis = useAppSelector(getAllDevis) as DevisListItem[];
  const devisSelected = useAppSelector(getDevisSelected) as DevisListItem;
  const statusDevis = useAppSelector(devisStatus);
  const [editing, setEditing] = useState<DevisListItem | null>(null);

  const isLoading = statusDevis === 'loading' && devis.length === 0 && statusClient === 'loading';

  const { refresh } = useDashboardData();

  useEffect(() => {
    const load = async () => {
      if (statusDevis === 'idle') await dispatch(getDevisList()).unwrap();
      if (statusFamille === 'idle') await dispatch(getfamilles()).unwrap();
      if (statusUniversign === "idle") await dispatch(getUniversigns()).unwrap();
      if (statusArticle === 'idle') await dispatch(getArticles()).unwrap();
      if (statusCommercial === "idle") await dispatch(getCommercials()).unwrap();
    };
    load();
  }, [statusDevis, statusFamille, statusArticle, statusCommercial, statusUniversign, dispatch]);

  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) as [
        string,
        typeof STATUS_LABELS[StatusCode]
      ][]).map(([value, { label, color }]) => ({
        value: value.toString(),
        label,
        color,
      })),
    },
    {
      key: 'rep',
      label: 'Commercial',
      options: commercialOptions,
    },
  ];

  // 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]);

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

  const kpis = useMemo(() => {
    // Filtrer d'abord par période
    const periodFilteredDevis = filterItemByPeriod(devis, period, 'date')
      .filter(item => item.numero !== 'DE00126');

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

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

  const filteredDevis = useMemo(() => {
    // 1. Filtrer par période
    let result = filterItemByPeriod(devis, period, 'date');
    result = result.filter(item => item.numero !== 'DE00126');

    
    // 2. Filtrer par KPI actif
    const kpiConfig = KPI_CONFIG.find(k => k.id === activeFilter);
    if (kpiConfig && activeFilter !== 'all') {
      result = kpiConfig.filter(result, universign);
    }
    
    // 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()
    );
  }, [devis, period, activeFilter, activeFilters, clientCommercialMap, universign]);

  
  // ============================================
  // 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 (!devisSelected) return null;

    return {
      numero: devisSelected.numero,
      type: 'devis' as const,
      date: devisSelected.date,
      client: {
        code: devisSelected.client_code,
        nom: devisSelected.client_intitule,
        adresse: devisSelected.client_adresse,
        code_postal: devisSelected.client_code_postal,
        ville: devisSelected.client_ville,
        email: devisSelected.client_email,
        telephone: devisSelected.client_telephone,
      },
      reference_externe: devisSelected.reference,
      lignes: (devisSelected.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),
        remise: l.remise_valeur1
      })),
      total_ht: devisSelected.total_ht_calcule,
      total_tva: devisSelected.total_taxes_calcule,
      total_ttc: devisSelected.total_ttc_calcule,
    };
  }, [devisSelected]) as DocumentData;

  const handleCreate = () => {
    navigate('/home/devis/nouveau');
  };

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

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

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

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

    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: any, row: DevisListItem) => {
          const signature = universignMap.get(row.numero);
          
          return (
            <StatusBadge status={signature?.local_status === "SIGNE" ? 6 : value} type_doc={SageDocumentType.DEVIS} />
          );
        },
      },
    };
  }, [clients, universign]);

  // Colonnes filtrées selon la config
  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 STATUS_LABELS[value as StatusCode]?.label || 'Inconnu';
    },
    client_intitule: (value, row) => {
      return value || row.client_code || '';
    },
  };

  const onDuplicate = async () => {
    try {
      setLoading(true);

      const payloadCreate: DevisRequest = {
        client_id: devisSelected.client_code,
        reference: devisSelected.reference,
        date_devis: (() => {
          const d = new Date();
          d.setDate(d.getDate() + 1);
          return d.toISOString().split('T')[0];
        })(),
        lignes: devisSelected.lignes.map(ligne => ({
          article_code: ligne.article_code,
          quantite: ligne.quantite,
          prix_unitaire_ht: ligne.prix_unitaire_ht,
        })),
      };

      const result = (await dispatch(createDevis(payloadCreate)).unwrap()) as DevisResponse;

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

      const devisCreated = (await dispatch(getDevisById(result.id)).unwrap()) as any;

      const res = devisCreated.data as DevisListItem;
      dispatch(selectDevis(res));

      toast({
        title: 'Devis dupliqué avec succès !',
        description: `Le devis ${devisSelected.numero} a été dupliqué avec succès.`,
        className: 'bg-green-500 text-white border-green-600',
      });
      setLoading(false);
      setIsDuplicate(false);
      navigate(`/home/devis/${result.id}`);
    } catch (err: any) {
      setLoading(false);
      setIsDuplicate(false);
    }
  };

  const actions = (row: DevisListItem) => {
    const handleStatus =
      row.statut !== 2 && row.statut !== 3 && row.statut !== 4
        ? () => {
            dispatch(selectDevis(row));
            setOpenStatusDevis(true);
          }
        : undefined;

    return (
      <>
        <button
          onClick={async () => 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>
        <button
          onClick={() => handleEdit(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="Éditer"
        >
          <Edit className="w-4 h-4" />
        </button>
        <DropdownMenuTable
          row={row}
          onDulipcate={() => {
            dispatch(selectDevis(row));
            setIsDuplicate(true);
          }}
          onStatus={handleStatus}
          onDownload={() => {
            dispatch(selectDevis(row));
            openPDF(row);
          }}
        />
      </>
    );
  };

  return (
    <>
      <Helmet>
        <title>Devis - Dataven</title>
        <meta name="description" content="Gestion de vos devis" />
      </Helmet>

      <div className="space-y-6">
        <KPIBar kpis={kpis} period={period} loading={statusDevis} onRefresh={refresh} />

        {loadingPdf && <ModalLoading />}

        <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">Devis</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">
                {activeFilter === 'all' ? (
                  `${filteredDevis.length} devis`
                ) : (
                  <>
                    {filteredDevis.length} devis{' '}
                    ({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={filteredDevis}
              columns={columnConfig}
              columnFormatters={columnFormatters}
              filename="devis"
            />
            <AdvancedFilters
              filters={filterDefinitions}
              activeFilters={activeFilters}
              onFilterChange={(key, values) => {
                setActiveFilters(prev => ({
                  ...prev,
                  [key]: values,
                }));
              }}
              onReset={() => setActiveFilters({})}
            />
            <PrimaryButton_v2 icon={Plus} onClick={handleCreate}>
              Nouveau devis
            </PrimaryButton_v2>
          </div>
        </div>

        <DataTable
          columns={visibleColumns}
          data={filteredDevis}
          onRowClick={(row: DevisListItem) => {
            dispatch(selectDevis(row));
            navigate(`/home/devis/${row.numero}`);
          }}
          actions={actions}
          status={isLoading}
          searchLabel={'Rechercher par: nom, n° devis, email, ...'}
        />
      </div>

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

      <ModalStatus open={openStatusDevis} onClose={() => setOpenStatusDevis(false)} type_doc={SageDocumentType.DEVIS} />

      <FormModal isOpen={isDuplicate} onClose={() => setIsDuplicate(false)} title="Dupliquer le devis" onSubmit={onDuplicate}>
        <div className="mb-6 p-4 bg-green-50 text-green-800 rounded-xl text-sm flex gap-3">
          <FileText className="w-5 h-5 shrink-0" />
          <p>Vous allez dupliquer le devis</p>
        </div>
      </FormModal>

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

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

export default QuotesPage;