import React, { useEffect, useMemo, useState } from 'react';
import { Helmet } from 'react-helmet';
import DataTable from '@/components/DataTable';
import {
  Eye,
  Send,
  FileText,
  CheckCircle2,
  Clock,
  XCircle,
  AlertTriangle,
  RefreshCw,
  ExternalLink,
  Users,
  Mail,
} from 'lucide-react';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { getAlluniversign, universignStatus } from '@/store/features/universign/selectors';
import { getUniversigns } from '@/store/features/universign/thunk';
import { UniversignType, Signer } from '@/types/sageTypes';
import { toast } from '@/components/ui/use-toast';
import ColumnSelector, { ColumnConfig } from '@/components/common/ColumnSelector';
import AdvancedFilters from '@/components/common/AdvancedFilters';
import ExportDropdown from '@/components/common/ExportDropdown';
import { cn, formatDateFRCourt } from '@/lib/utils';
import PeriodSelector from '@/components/common/PeriodSelector';
import { PeriodType } from '@/components/KPIBar';
import { filterItemByPeriod } from '@/components/filter/ItemsFilter';

// ============================================
// STATUS CONFIGURATION
// ============================================

const UNIVERSIGN_STATUS = {
  draft: { label: 'Brouillon', color: 'bg-gray-100 text-gray-700', icon: FileText },
  sent: { label: 'Envoyé', color: 'bg-blue-100 text-blue-700', icon: Send },
  viewed: { label: 'Vu', color: 'bg-purple-100 text-purple-700', icon: Eye },
  signed: { label: 'Signé', color: 'bg-green-100 text-green-700', icon: CheckCircle2 },
  refused: { label: 'Refusé', color: 'bg-red-100 text-red-700', icon: XCircle },
  expired: { label: 'Expiré', color: 'bg-orange-100 text-orange-700', icon: AlertTriangle },
  pending: { label: 'En attente', color: 'bg-yellow-100 text-yellow-700', icon: Clock },
  cancelled: { label: 'Annulé', color: 'bg-gray-100 text-gray-600', icon: XCircle },
} as const;

type UniversignStatusKey = keyof typeof UNIVERSIGN_STATUS;

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

const DEFAULT_COLUMNS: ColumnConfig[] = [
  { key: 'sage_document_id', label: 'Document', visible: true, locked: true },
  { key: 'sage_document_type', label: 'Type', visible: true },
  { key: 'signers', label: 'Signataires', visible: true },
  { key: 'sent_at', label: 'Envoyé le', visible: true },
  { key: 'signed_at', label: 'Signé le', visible: false },
  { key: 'local_status', label: 'Statut', visible: true },
  { key: 'needs_sync', label: 'Sync', visible: false },
  { key: 'transaction_id', label: 'Transaction ID', visible: false },
];

// ============================================
// COMPOSANT STATUS BADGE
// ============================================

const SignatureStatusBadge: React.FC<{ status: string }> = ({ status }) => {
  const statusKey = status?.toLowerCase() as UniversignStatusKey;
  const config = UNIVERSIGN_STATUS[statusKey] || UNIVERSIGN_STATUS.pending;
  const Icon = config.icon;

  return (
    <span className={cn('inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium', config.color)}>
      <Icon className="w-3 h-3" />
      {config.label}
    </span>
  );
};

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

const SignatureTracking = () => {
  const dispatch = useAppDispatch();

  const [period, setPeriod] = useState<PeriodType>('all');
  const [columnConfig, setColumnConfig] = useState<ColumnConfig[]>(DEFAULT_COLUMNS);
  const [activeFilters, setActiveFilters] = useState<Record<string, string[] | undefined>>({});

  const universign = useAppSelector(getAlluniversign) as UniversignType[];
  const statusUniversign = useAppSelector(universignStatus);

  const isLoading = statusUniversign === 'loading' && universign.length === 0;

  // Chargement initial
  useEffect(() => {
    const load = async () => {
      if (statusUniversign === 'idle') {
        await dispatch(getUniversigns()).unwrap();
      }
    };
    load();
  }, [statusUniversign, dispatch]);

  // Rafraîchir
  const handleRefresh = async () => {
    try {
      await dispatch(getUniversigns()).unwrap();
      toast({
        title: 'Actualisé',
        description: 'Les signatures ont été mises à jour.',
        className: 'bg-green-500 text-white border-green-600',
      });
    } catch (error) {
      toast({
        title: 'Erreur',
        description: "Impossible d'actualiser les signatures.",
        variant: 'destructive',
      });
    }
  };

  // ============================================
  // FILTRES
  // ============================================

  const filterDefinitions = useMemo(
    () => [
      {
        key: 'status',
        label: 'Statut',
        options: Object.entries(UNIVERSIGN_STATUS).map(([value, { label, color }]) => ({
          value,
          label,
          color: color.split(' ')[0], // Extraire juste bg-xxx
        })),
      },
      {
        key: 'type',
        label: 'Type de document',
        options: [
          { value: 'devis', label: 'Devis', color: 'bg-blue-400' },
          { value: 'facture', label: 'Facture', color: 'bg-green-400' },
          { value: 'bon_commande', label: 'Bon de commande', color: 'bg-purple-400' },
          { value: 'bon_livraison', label: 'Bon de livraison', color: 'bg-orange-400' },
        ],
      },
      {
        key: 'sync',
        label: 'Synchronisation',
        options: [
          { value: 'true', label: 'À synchroniser', color: 'bg-yellow-400' },
          { value: 'false', label: 'Synchronisé', color: 'bg-green-400' },
        ],
      },
    ],
    []
  );

  // ============================================
  // DONNÉES FILTRÉES
  // ============================================

  // const filteredSignatures = useMemo(() => {
  //   let result = filterItemByPeriod(universign, period, 'sent_at');

  //   // Filtre par statut
  //   if (activeFilters.status && activeFilters.status.length > 0) {
  //     result = result.filter(item => activeFilters.status!.includes(item.local_status?.toLowerCase() || ''));
  //   }

  //   // Filtre par type de document
  //   if (activeFilters.type && activeFilters.type.length > 0) {
  //     result = result.filter(item => activeFilters.type!.includes(item.sage_document_type?.toLowerCase() || ''));
  //   }

  //   // Filtre par sync
  //   if (activeFilters.sync && activeFilters.sync.length > 0) {
  //     result = result.filter(item => activeFilters.sync!.includes(item.needs_sync?.toString() || 'false'));
  //   }

  //   return [...result].sort((a, b) => new Date(b.sent_at || b.created_at).getTime() - new Date(a.sent_at || a.created_at).getTime());
  // }, [universign, period, activeFilters]);

  // ============================================
  // COLONNES
  // ============================================

  const allColumnsDefinition = useMemo(
    () => ({
      sage_document_id: {
        key: 'sage_document_id',
        label: 'Document',
        sortable: true,
        render: (value: string, row: UniversignType) => (
          <div className="flex items-center gap-2">
            <div className="w-8 h-8 rounded-lg bg-[#007E45]/10 flex items-center justify-center">
              <FileText className="w-4 h-4 text-[#007E45]" />
            </div>
            <div>
              <p className="font-medium text-[#007E45]">{value}</p>
              <p className="text-[10px] text-gray-400 font-mono">{row.transaction_id?.slice(0, 8)}...</p>
            </div>
          </div>
        ),
      },
      sage_document_type: {
        key: 'sage_document_type',
        label: 'Type',
        sortable: true,
        render: (value: string) => {
          const typeLabels: Record<string, string> = {
            devis: 'Devis',
            facture: 'Facture',
            bon_commande: 'Bon de commande',
            bon_livraison: 'Bon de livraison',
          };
          return (
            <span className="text-sm text-gray-700 dark:text-gray-300 capitalize">
              {typeLabels[value?.toLowerCase()] || value || '-'}
            </span>
          );
        },
      },
      signers: {
        key: 'signers',
        label: 'Signataires',
        sortable: false,
        render: (signers: Signer[]) => {
          if (!signers || signers.length === 0) {
            return <span className="text-gray-400">-</span>;
          }

          const mainSigner = signers[0];
          const otherCount = signers.length - 1;

          return (
            <div className="flex items-center gap-2">
              <div className="w-7 h-7 rounded-full bg-gray-100 dark:bg-gray-800 flex items-center justify-center text-[10px] font-bold text-gray-600">
                {mainSigner.name?.charAt(0)?.toUpperCase() || <Mail className="w-3 h-3" />}
              </div>
              <div className="min-w-0">
                <p className="text-sm font-medium text-gray-900 dark:text-white truncate max-w-[150px]">
                  {mainSigner.name || mainSigner.email}
                </p>
                {otherCount > 0 && <p className="text-[10px] text-gray-500">+{otherCount} autre{otherCount > 1 ? 's' : ''}</p>}
              </div>
              {mainSigner.status === 'signed' && <CheckCircle2 className="w-4 h-4 text-green-500 shrink-0" />}
            </div>
          );
        },
      },
      sent_at: {
        key: 'sent_at',
        label: 'Envoyé le',
        sortable: true,
        render: (value: string) =>
          value ? (
            <div className="flex items-center gap-1.5 text-sm text-gray-600 dark:text-gray-400">
              <Send className="w-3 h-3" />
              {formatDateFRCourt(value)}
            </div>
          ) : (
            <span className="text-gray-400">-</span>
          ),
      },
      signed_at: {
        key: 'signed_at',
        label: 'Signé le',
        sortable: true,
        render: (value: string) =>
          value ? (
            <div className="flex items-center gap-1.5 text-sm text-green-600">
              <CheckCircle2 className="w-3 h-3" />
              {formatDateFRCourt(value)}
            </div>
          ) : (
            <span className="text-gray-400">-</span>
          ),
      },
      local_status: {
        key: 'local_status',
        label: 'Statut',
        sortable: true,
        render: (value: string, row: UniversignType) => <SignatureStatusBadge status={value || row.universign_status} />,
      },
      needs_sync: {
        key: 'needs_sync',
        label: 'Sync',
        sortable: true,
        render: (value: boolean) =>
          value ? (
            <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-medium bg-yellow-100 text-yellow-700">
              <RefreshCw className="w-3 h-3" />À sync
            </span>
          ) : (
            <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-medium bg-green-100 text-green-700">
              <CheckCircle2 className="w-3 h-3" />
              OK
            </span>
          ),
      },
      transaction_id: {
        key: 'transaction_id',
        label: 'Transaction ID',
        sortable: true,
        render: (value: string) => <span className="font-mono text-xs text-gray-500">{value || '-'}</span>,
      },
    }),
    []
  );

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

  // ============================================
  // FORMATEURS EXPORT
  // ============================================

  const columnFormatters: Record<string, (value: any, row: UniversignType) => string> = {
    signers: (signers: Signer[]) => {
      if (!signers || signers.length === 0) return '-';
      return signers.map(s => `${s.name || ''} <${s.email}>`).join(', ');
    },
    sent_at: value => (value ? formatDateFRCourt(value) : '-'),
    signed_at: value => (value ? formatDateFRCourt(value) : '-'),
    local_status: (value, row) => UNIVERSIGN_STATUS[value?.toLowerCase() as UniversignStatusKey]?.label || value || row.universign_status || '-',
    needs_sync: value => (value ? 'À synchroniser' : 'Synchronisé'),
  };

  // ============================================
  // ACTIONS
  // ============================================

  const actions = (row: UniversignType) => (
    <>
      {/* Voir le document */}
      {row.document_url && (
        <a
          href={row.document_url}
          target="_blank"
          rel="noopener noreferrer"
          onClick={e => e.stopPropagation()}
          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 le document"
        >
          <Eye className="w-4 h-4" />
        </a>
      )}

      {/* Lien signataire */}
      {row.signer_url && ['sent', 'viewed', 'pending'].includes(row.local_status?.toLowerCase()) && (
        <a
          href={row.signer_url}
          target="_blank"
          rel="noopener noreferrer"
          onClick={e => e.stopPropagation()}
          className="p-2 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-lg transition-colors text-blue-600"
          title="Ouvrir lien de signature"
        >
          <ExternalLink className="w-4 h-4" />
        </a>
      )}

      {/* Relancer */}
      {['sent', 'viewed'].includes(row.local_status?.toLowerCase()) && (
        <button
          onClick={e => {
            e.stopPropagation();
            toast({
              title: 'Relance envoyée',
              description: `Relance pour ${row.sage_document_id}`,
            });
          }}
          className="p-2 hover:bg-purple-50 dark:hover:bg-purple-900/20 rounded-lg transition-colors text-purple-600"
          title="Relancer le signataire"
        >
          <Send className="w-4 h-4" />
        </button>
      )}
    </>
  );

  // ============================================
  // STATS RAPIDES
  // ============================================

  // const stats = useMemo(() => {
  //   const total = filteredSignatures.length;
  //   const signed = filteredSignatures.filter(s => s.local_status?.toLowerCase() === 'signed').length;
  //   const pending = filteredSignatures.filter(s => ['sent', 'viewed', 'pending'].includes(s.local_status?.toLowerCase())).length;
  //   const refused = filteredSignatures.filter(s => ['refused', 'expired', 'cancelled'].includes(s.local_status?.toLowerCase())).length;

  //   return { total, signed, pending, refused };
  // }, [filteredSignatures]);

  return (
    <>
      <Helmet>
        <title>Suivi des signatures - Dataven</title>
        <meta name="description" content="Historique et statut de vos demandes de signature" />
      </Helmet>

      <div className="space-y-6">
        {/* Header */}
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div>
            <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Suivi des Signatures</h1>
            <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
              Historique et statut de toutes vos demandes de signature
            </p>
          </div>

          <button
            onClick={handleRefresh}
            disabled={statusUniversign === 'loading'}
            className="inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors disabled:opacity-50"
          >
            <RefreshCw className={cn('w-4 h-4', statusUniversign === 'loading' && 'animate-spin')} />
            Actualiser
          </button>
        </div>

        {/* Stats rapides */}
        {/* <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
          <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 p-4">
            <p className="text-sm text-gray-500">Total</p>
            <p className="text-2xl font-bold text-gray-900 dark:text-white">{stats.total}</p>
          </div>
          <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 p-4">
            <p className="text-sm text-green-600">Signés</p>
            <p className="text-2xl font-bold text-green-600">{stats.signed}</p>
          </div>
          <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 p-4">
            <p className="text-sm text-yellow-600">En attente</p>
            <p className="text-2xl font-bold text-yellow-600">{stats.pending}</p>
          </div>
          <div className="bg-white dark:bg-gray-900 rounded-xl border border-gray-200 dark:border-gray-800 p-4">
            <p className="text-sm text-red-600">Refusés/Expirés</p>
            <p className="text-2xl font-bold text-red-600">{stats.refused}</p>
          </div>
        </div> */}

        {/* Toolbar */}
        {/* <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div className="flex items-center gap-3">
            <span className="text-sm text-gray-600 dark:text-gray-400">{filteredSignatures.length} signature{filteredSignatures.length > 1 ? 's' : ''}</span>
            <PeriodSelector value={period} onChange={setPeriod} />
          </div>

          <div className="flex flex-wrap items-center gap-3">
            <ColumnSelector columns={columnConfig} onChange={setColumnConfig} />

            <ExportDropdown data={filteredSignatures} columns={columnConfig} columnFormatters={columnFormatters} filename="signatures" />

            <AdvancedFilters
              filters={filterDefinitions}
              activeFilters={activeFilters}
              onFilterChange={(key, values) => {
                setActiveFilters(prev => ({ ...prev, [key]: values }));
              }}
              onReset={() => setActiveFilters({})}
            />
          </div>
        </div> */}

        {/* DataTable */}
        <DataTable
          columns={visibleColumns}
          data={universign}
          onRowClick={(row: UniversignType) => {
            toast({
              title: 'Détails',
              description: `Document: ${row.sage_document_id} - Statut: ${row.local_status_label || row.local_status}`,
            });
          }}
          actions={actions}
          status={isLoading}
          searchLabel="Rechercher par: document, email, transaction..."
        />
      </div>
    </>
  );
};

export default SignatureTracking;