import { useState, useMemo, useEffect } from 'react';
import { Helmet } from 'react-helmet';
import { useNavigate } from 'react-router-dom';
import { 
  Eye, Download, CheckCircle, Euro, X, Wallet, 
  Clock, AlertTriangle, Calendar, Receipt
} from 'lucide-react';
import KPIBar, { PeriodType } from '@/components/KPIBar';
import { toast } from '@/components/ui/use-toast';
import { cn, formatDateFRCourt } from '@/lib/utils';
import { Facture } from '@/types/factureType';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import PrimaryButton_v2 from '@/components/PrimaryButton_v2';
import { filterItemByPeriod, getPreviousPeriodItems } from '@/components/filter/ItemsFilter';
import ColumnSelector, { ColumnConfig } from '@/components/common/ColumnSelector';
import PeriodSelector from '@/components/common/PeriodSelector';
import ExportDropdown from '@/components/common/ExportDropdown';
import DataTable from '@/components/DataTable';
import { getAllReglements, getReglementStats, reglementStatus } from '@/store/features/reglement/selectors';
import { loadAllReglementData } from '@/store/features/reglement/thunk';
import ModalPaymentPanel from '@/components/modal/ModalPaymentPanel';
import { FacturesReglement, Statistique } from '@/types/reglementType';
import { selectReglement } from '@/store/features/reglement/slice';

// ============================================
// CONSTANTES - STATUTS DE RÈGLEMENT
// ============================================

const STATUT_REGLEMENT = {
  SOLDE: 'Soldé',
  PARTIEL: 'Partiellement réglé',
  NON_REGLE: 'Non réglé',
} as const;

type StatutReglement = typeof STATUT_REGLEMENT[keyof typeof STATUT_REGLEMENT];

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

type FilterType = 'all' | 'paid' | 'partial' | 'unpaid';

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

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

const DEFAULT_COLUMNS: ColumnConfig[] = [
  { key: 'rg_no', label: 'N° Règlement', visible: true, locked: true },
  { key: 'numero', label: 'N° Pièce', visible: true, locked: true },
  { key: 'client', label: 'Client', visible: true },
  { key: 'date', label: 'Date', visible: true },
  { key: 'total_ttc', label: 'Montant TTC', visible: true },
  { key: 'montant_regle', label: 'Montant Réglé', visible: true },
  { key: 'reste_a_regler', label: 'Reste à Régler', visible: true },
  { key: 'statut_reglement', label: 'Statut', visible: true },
  { key: 'nb_echeances', label: 'Échéances', visible: false },
  { key: 'nb_reglements', label: 'Règlements', visible: false },
];

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

const KPI_CONFIG: KPIConfig[] = [
  {
    id: 'all',
    title: 'Total Facturé',
    icon: Euro,
    color: 'blue',
    getValue: (factures, stats) => stats?.total_factures || factures.reduce((sum, f) => sum + (f.montants?.total_ttc || 0), 0),
    getSubtitle: (factures, _, stats) => {
      const totalRegle = stats?.total_regle || factures.reduce((sum, f) => sum + (f.montants?.montant_regle || 0), 0);
      return `${totalRegle.toLocaleString('fr-FR')}€ réglés`;
    },
    getChange: (factures, value, period, allFactures) => {
      const previousPeriodFactures = getPreviousPeriodItems(allFactures, period, 'date');
      const previousTotal = previousPeriodFactures.reduce((sum, f) => sum + (f.montants?.total_ttc || 0), 0);
      return previousTotal > 0 ? (((Number(value) - previousTotal) / previousTotal) * 100).toFixed(1) : '0';
    },
    getTrend: (factures, value, period, allFactures) => {
      const previousPeriodFactures = getPreviousPeriodItems(allFactures, period, 'date');
      const previousTotal = previousPeriodFactures.reduce((sum, f) => sum + (f.montants?.total_ttc || 0), 0);
      return Number(value) >= previousTotal ? 'up' : 'down';
    },
    filter: (factures) => factures,
    tooltip: { content: "Total des factures sur la période.", source: "Règlements > Factures" }
  },
  {
    id: 'paid',
    title: 'Factures Soldées',
    icon: CheckCircle,
    color: 'green',
    getValue: (factures, stats) => stats?.nb_soldees || factures.filter(f => f.statut_reglement === STATUT_REGLEMENT.SOLDE).length,
    getSubtitle: (factures) => {
      const soldees = factures.filter(f => f.statut_reglement === STATUT_REGLEMENT.SOLDE);
      const total = soldees.reduce((sum, f) => sum + (f.montants?.total_ttc || 0), 0);
      return `${total.toLocaleString('fr-FR')}€`;
    },
    getChange: (factures, value) => {
      const total = factures.length;
      return total > 0 ? `${((Number(value) / total) * 100).toFixed(0)}%` : '0%';
    },
    getTrend: () => 'up',
    filter: (factures) => factures.filter(f => f.statut_reglement === STATUT_REGLEMENT.SOLDE),
    tooltip: { content: "Factures entièrement réglées.", source: "Règlements > Factures" }
  },
  {
    id: 'partial',
    title: 'Partiellement Réglées',
    icon: Clock,
    color: 'orange',
    getValue: (factures, stats) => stats?.nb_partiellement_reglees || factures.filter(f => f.statut_reglement === STATUT_REGLEMENT.PARTIEL).length,
    getSubtitle: (factures) => {
      const partielles = factures.filter(f => f.statut_reglement === STATUT_REGLEMENT.PARTIEL);
      const reste = partielles.reduce((sum, f) => sum + (f.montants?.reste_a_regler || 0), 0);
      return `${reste.toLocaleString('fr-FR')}€ restant`;
    },
    getChange: (factures, value) => {
      const total = factures.length;
      return total > 0 ? `${((Number(value) / total) * 100).toFixed(0)}%` : '0%';
    },
    getTrend: (_, value) => Number(value) > 0 ? 'down' : 'neutral',
    filter: (factures) => factures.filter(f => f.statut_reglement === STATUT_REGLEMENT.PARTIEL),
    tooltip: { content: "Factures avec règlement partiel.", source: "Règlements > Factures" }
  },
  {
    id: 'unpaid',
    title: 'Non Réglées',
    icon: AlertTriangle,
    color: 'red',
    getValue: (factures, stats) => stats?.nb_non_reglees || factures.filter(f => f.statut_reglement === STATUT_REGLEMENT.NON_REGLE).length,
    getSubtitle: (factures, _, stats) => {
      const reste = stats?.total_reste || factures
        .filter(f => f.statut_reglement === STATUT_REGLEMENT.NON_REGLE)
        .reduce((sum, f) => sum + (f.montants?.reste_a_regler || 0), 0);
      return `${reste.toLocaleString('fr-FR')}€ à encaisser`;
    },
    getChange: (factures, value) => {
      const total = factures.length;
      return total > 0 ? `${((Number(value) / total) * 100).toFixed(0)}%` : '0%';
    },
    getTrend: (_, value) => Number(value) > 0 ? 'down' : 'up',
    filter: (factures) => factures.filter(f => f.statut_reglement === STATUT_REGLEMENT.NON_REGLE),
    tooltip: { content: "Factures sans aucun règlement.", source: "Règlements > Factures" }
  },
];

// ============================================
// STATUT BADGE POUR RÈGLEMENTS
// ============================================

const ReglementStatusBadge = ({ status }: { status: string }) => {
  const config: Record<string, { label: string; className: string; icon: React.ElementType }> = {
    [STATUT_REGLEMENT.SOLDE]: { 
      label: 'Soldé', 
      className: 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400',
      icon: CheckCircle
    },
    [STATUT_REGLEMENT.PARTIEL]: { 
      label: 'Partiel', 
      className: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
      icon: Clock
    },
    [STATUT_REGLEMENT.NON_REGLE]: { 
      label: 'Non réglé', 
      className: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400',
      icon: AlertTriangle
    },
  };

  const statusConfig = config[status] || config[STATUT_REGLEMENT.NON_REGLE];
  const Icon = statusConfig.icon;

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

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

const PaymentsPage = () => {
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const [period, setPeriod] = useState<PeriodType>('all');
  const [activeFilter, setActiveFilter] = useState<FilterType>('all');
  const [columnConfig, setColumnConfig] = useState<ColumnConfig[]>(DEFAULT_COLUMNS);
  const [selectedInvoiceIds, setSelectedInvoiceIds] = useState<string[]>([]);
  const [isPaymentPanelOpen, setIsPaymentPanelOpen] = useState(false);

  // Redux
  const reglements = useAppSelector(getAllReglements) as FacturesReglement[];
  const stats = useAppSelector(getReglementStats) as Statistique;
  const statusReglement = useAppSelector(reglementStatus);

  const isLoading = statusReglement === 'loading' && reglements.length === 0;

  
  useEffect(() => {
    const load = async () => {
      try {
        if (statusReglement === 'idle' || statusReglement === 'failed') {
          await dispatch(loadAllReglementData()).unwrap();
        }
      } catch (error) {
        console.error(error);
      }
    };
    load();
  }, [statusReglement, dispatch]);

  // ============================================
  // KPIs
  // ============================================

  const kpis = useMemo(() => {
    const periodFilteredFactures = filterItemByPeriod(reglements, period, 'date');

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

  // ============================================
  // Filtrage
  // ============================================

  const filteredReglements = useMemo(() => {
    let result = filterItemByPeriod(reglements, period, 'date');

    const kpiConfig = KPI_CONFIG.find(k => k.id === activeFilter);
    if (kpiConfig && activeFilter !== 'all') {
      result = kpiConfig.filter(result);
    }

    return [...result].sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
  }, [reglements, period, activeFilter]);

  // Factures sélectionnables (non soldées)
  const selectableFactures = useMemo(() => {
    return filteredReglements.filter(f => f.statut_reglement !== STATUT_REGLEMENT.SOLDE);
  }, [filteredReglements]);

  // Factures sélectionnées
  const selectedFactures = useMemo(() => {
    return reglements.filter(f => selectedInvoiceIds.includes(f.numero));
  }, [selectedInvoiceIds, reglements]);

  // Total sélectionné (reste à régler)
  const totalSelectedBalance = useMemo(() => {
    return selectedInvoiceIds.reduce((sum, id) => {
      const facture = reglements.find(f => f.numero === id);
      return sum + (facture?.montants?.reste_a_regler || 0);
    }, 0);
  }, [selectedInvoiceIds, reglements]);

  const formatCurrency = (amount: number) => {
    return `${amount.toLocaleString('fr-FR', { minimumFractionDigits: 2 })}€`;
  };

  // ============================================
  // Handlers
  // ============================================

  const handlePayment = () => {
    setIsPaymentPanelOpen(true);
  };


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

  // ============================================
  // Colonnes
  // ============================================

  const allColumnsDefinition = useMemo(() => ({
    rg_no: {
      key: 'rg_no',
      label: 'N° règlement',
      sortable: true,
      render: (value: string, row: FacturesReglement) => {
        // Vérifier si les données existent avant d'y accéder
        const firstReglement = row.echeances?.[0]?.reglements?.[0];
        const reglementNo = firstReglement?.rg_no;

        return (
          <div>
            <span className="font-bold text-gray-900 dark:text-white">
              {reglementNo ? `REG_${reglementNo}` : '-'}
            </span>
            <div className="text-xs text-gray-500">
              {reglementNo ? 'Règlement' : 'Non réglé'}
            </div>
          </div>
        );
      },
    },
    numero: {
      key: 'numero',
      label: 'N° Pièce',
      sortable: true,
      render: (value: string, row: FacturesReglement) => (
        <div>
          <span className="font-bold text-gray-900 dark:text-white">{value}</span>
          <div className="text-xs text-gray-500">{row.type_libelle}</div>
        </div>
      ),
    },
    client: {
      key: 'client',
      label: 'Client',
      sortable: true,
      render: (_: any, row: FacturesReglement) => {
        const client = row.client;
        if (!client) return <span className="text-gray-400">-</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.numero}</p>
            </div>
          </div>
        );
      },
    },
    date: {
      key: 'date',
      label: 'Date',
      sortable: true,
      render: (date: string) => <span>{formatDateFRCourt(date)}</span>,
    },
    total_ttc: {
      key: 'montants.total_ttc',
      label: 'Montant TTC',
      sortable: true,
      render: (_: any, row: FacturesReglement) => (
        <span className="font-semibold">{formatCurrency(row.montants?.total_ttc || 0)}</span>
      ),
    },
    montant_regle: {
      key: 'montants.montant_regle',
      label: 'Montant Réglé',
      sortable: true,
      render: (_: any, row: FacturesReglement) => (
        <span className={cn(
          "font-medium",
          row.montants?.montant_regle > 0 ? "text-green-600 dark:text-green-400" : "text-gray-400"
        )}>
          {formatCurrency(row.montants?.montant_regle || 0)}
        </span>
      ),
    },
    reste_a_regler: {
      key: 'montants.reste_a_regler',
      label: 'Reste à Régler',
      sortable: true,
      render: (_: any, row: FacturesReglement) => (
        <span className={cn(
          "font-bold",
          row.montants?.reste_a_regler > 0 ? "text-red-600 dark:text-red-400" : "text-gray-400"
        )}>
          {formatCurrency(row.montants?.reste_a_regler || 0)}
        </span>
      ),
    },
    statut_reglement: {
      key: 'statut_reglement',
      label: 'Statut',
      sortable: true,
      render: (status: string) => <ReglementStatusBadge status={status} />,
    },
    nb_echeances: {
      key: 'nb_echeances',
      label: 'Échéances',
      sortable: true,
      render: (value: number) => (
        <div className="flex items-center gap-1.5">
          <Calendar className="w-4 h-4 text-gray-400" />
          <span>{value || 0}</span>
        </div>
      ),
    },
    nb_reglements: {
      key: 'nb_reglements',
      label: 'Règlements',
      sortable: true,
      render: (value: number) => (
        <div className="flex items-center gap-1.5">
          <Receipt className="w-4 h-4 text-gray-400" />
          <span>{value || 0}</span>
        </div>
      ),
    },
  }), []);

  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) : '',
    'montants.total_ttc': (_, row) => formatCurrency(row.montants?.total_ttc || 0),
    'montants.montant_regle': (_, row) => formatCurrency(row.montants?.montant_regle || 0),
    'montants.reste_a_regler': (_, row) => formatCurrency(row.montants?.reste_a_regler || 0),
    statut_reglement: (value) => value || '',
    client: (_, row) => row.client?.intitule || '',
  };

  const actions = (row: FacturesReglement) => (
    <>
      <button
        onClick={() => navigate(`/home/reglements/${row.numero}`)}
        className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg text-gray-500"
        title="Voir détails"
      >
        <Eye className="w-4 h-4" />
      </button>
      <button
        onClick={() => toast({ title: 'Téléchargement', description: 'Génération du PDF...' })}
        className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg text-gray-500"
        title="Télécharger"
      >
        <Download className="w-4 h-4" />
      </button>
    </>
  );

  // Convertir FacturesReglement en Facture pour le modal
  const selectedFacturesForModal = useMemo((): Facture[] => {
    return selectedFactures.map(f => ({
      numero: f.numero,
      date: f.date,
      reference: f.reference || '',
      client_code: f.client?.numero || '',
      client_intitule: f.client?.intitule || '',
      client_adresse: f.client?.adresse || '',
      client_code_postal: f.client?.code_postal || '',
      client_ville: f.client?.ville || '',
      client_email: f.client?.email || '',
      client_telephone: f.client?.telephone || '',
      valide: 1,
      statut: f.statut_reglement === STATUT_REGLEMENT.SOLDE ? 4 : (f.statut_reglement === STATUT_REGLEMENT.PARTIEL ? 2 : 1),
      total_ht: f.montants?.total_ttc || 0,
      total_ttc: f.montants?.total_ttc || 0,
      total_ht_net: f.montants?.total_ttc || 0,
      total_ht_calcule: f.montants?.total_ttc || 0,
      total_ttc_calcule: f.montants?.reste_a_regler || 0,
      total_taxes_calcule: 0,
      valeur_frais: 0,
    }));
  }, [selectedFactures]);

  return (
    <>
      <Helmet>
        <title>Règlements - Dataven</title>
      </Helmet>

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

        <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">Règlements</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">
                {filteredReglements.length} facture{filteredReglements.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={filteredReglements}
              columns={columnConfig}
              columnFormatters={columnFormatters}
              filename="Reglements"
            />
            {selectedInvoiceIds.length > 0 && (
              <PrimaryButton_v2 
                onClick={handlePayment}
                className="bg-[#338660] hover:bg-[#2A6F4F] shadow-lg shadow-green-900/20 animate-in fade-in zoom-in duration-200"
              >
                <Wallet className="w-4 h-4 mr-2" />
                Régler ({selectedInvoiceIds.length}) · {formatCurrency(totalSelectedBalance)}
              </PrimaryButton_v2>
            )}
          </div>
        </div>

        <DataTable
          columns={visibleColumns}
          data={filteredReglements}
          actions={actions}
          status={isLoading}
          // selectable={true}
          // selectableFactures={selectableFactures}
          // selectedIds={selectedInvoiceIds}
          // onSelectRow={handleSelectInvoice}
          // onSelectAll={handleSelectAll}
          onRowClick={async(row: FacturesReglement) => {
            console.log("Row clicked:", row.numero);
            dispatch(selectReglement(row))
            navigate(`/home/reglements/${row.numero}`);
          }}
        />
      </div>

      <ModalPaymentPanel
        isOpen={isPaymentPanelOpen}
        onClose={() => setIsPaymentPanelOpen(false)}
        selectedInvoices={selectedFacturesForModal}
        totalAmount={totalSelectedBalance}
      />
    </>
  );
};

export default PaymentsPage;