import React, { useState, useEffect, useMemo } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X, Calendar, Wallet, CheckCircle, AlertTriangle, Coins, AlertCircle, Building, CreditCard } from 'lucide-react';
import { cn, formatCurrency } from '@/lib/utils';
import { Checkbox } from '@/components/ui/checkbox';
import { toast } from '@/components/ui/use-toast';
import { Facture } from '@/types/factureType';
import PrimaryButton_v2 from '../PrimaryButton_v2';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { getAllModes, getAllDevises, getAllTresoreries, getAllEncaissements, reglementStatus } from '@/store/features/reglement/selectors';
import { ReglementRequest } from '@/types/reglementType';
import { useNavigate } from 'react-router-dom';
import { getReglementId, reglerFacture } from '@/store/features/reglement/thunk';

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

type PaymentStep = 'input' | 'confirmation';

interface Allocation {
  [invoiceId: string]: number;
}

interface ModalPaymentPanelProps {
  isOpen: boolean;
  onClose: () => void;
  selectedInvoices: Facture[];
  totalAmount: number;
}

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

const ModalPaymentPanel: React.FC<ModalPaymentPanelProps> = ({ 
  isOpen, 
  onClose, 
  selectedInvoices, 
  totalAmount
}) => {
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  // Redux selectors
  const modes = useAppSelector(getAllModes);
  const devises = useAppSelector(getAllDevises);
  const tresoreries = useAppSelector(getAllTresoreries);
  const encaissements = useAppSelector(getAllEncaissements);
  const statsReglement = useAppSelector(reglementStatus);


  const [step, setStep] = useState<PaymentStep>('input');
  const [allocations, setAllocations] = useState<Allocation>({});

  // Form state pour ReglementRequest
  const [reglementData, setReglementData] = useState<ReglementRequest>({
    client_id: '',
    code_journal: '',
    cours_devise: 1,
    date_echeance: new Date().toISOString().split('T')[0],
    date_reglement: new Date().toISOString().split('T')[0],
    devise_code: 0,
    libelle: 'Reglement multiple',
    mode_reglement: 2,
    montant_total: 0,
    numeros_factures: [],
    reference: '',
    tva_encaissement: false
  });

  // Devises triées avec Euro en priorité
  const sortedDevises = useMemo(() => {
    if (!devises) return [];
    return [...devises].sort((a, b) => {
      // Euro en premier (vérifie sigle EUR ou €, ou intitulé contenant "Euro")
      const isEuroA = a.sigle?.toUpperCase() === 'EUR' || a.sigle === '€' || a.intitule?.toLowerCase().includes('euro');
      const isEuroB = b.sigle?.toUpperCase() === 'EUR' || b.sigle === '€' || b.intitule?.toLowerCase().includes('euro');
      
      if (isEuroA && !isEuroB) return -1;
      if (!isEuroA && isEuroB) return 1;
      
      // Ensuite devise principale
      if (a.est_principale && !b.est_principale) return -1;
      if (!a.est_principale && b.est_principale) return 1;
      
      return 0;
    });
  }, [devises]);

  // Devise par défaut : Euro si disponible, sinon principale, sinon première
  const deviseParDefaut = useMemo(() => {
    if (!devises || devises.length === 0) return null;
    
    // Chercher l'Euro
    const euro = devises.find(d => 
      d.sigle?.toUpperCase() === 'EUR' || 
      d.sigle === '€' || 
      d.intitule?.toLowerCase().includes('euro')
    );
    if (euro) return euro;
    
    // Sinon devise principale
    const principale = devises.find(d => d.est_principale);
    if (principale) return principale;
    
    // Sinon première devise
    return devises[0];
  }, [devises]);

  // Initial setup when modal opens
  useEffect(() => {
    if (isOpen && selectedInvoices.length > 0) {
      const totalDue = selectedInvoices.reduce((sum, inv) => sum + (inv.total_ttc_calcule || 0), 0);
      
      // Auto-allocate full amounts initially
      const initialAllocations: Allocation = {};
      const numerosFactures: string[] = [];
      selectedInvoices.forEach(inv => {
        initialAllocations[inv.numero] = inv.total_ttc_calcule || 0;
        numerosFactures.push(inv.numero);
      });
      setAllocations(initialAllocations);

      // Initialize reglement data
      const clientId = selectedInvoices[0]?.client_code || selectedInvoices[0]?.client_code || '';
      
      setReglementData({
        client_id: clientId,
        code_journal: tresoreries?.[0]?.code || '',
        cours_devise: deviseParDefaut?.cours_actuel || 1,
        date_echeance: new Date().toISOString().split('T')[0],
        date_reglement: new Date().toISOString().split('T')[0],
        devise_code: deviseParDefaut?.code || 0,
        libelle: 'Reglement multiple',
        mode_reglement: modes?.[0]?.code || 2,
        montant_total: totalDue,
        numeros_factures: numerosFactures,
        reference: '',
        tva_encaissement: encaissements?.tva_encaissement_actif || false
      });
      
      setStep('input');
    }
  }, [isOpen, selectedInvoices, modes, devises, tresoreries, encaissements, deviseParDefaut]);

  // Update numeros_factures based on allocations
  useEffect(() => {
    const activeInvoices = Object.entries(allocations)
      .filter(([_, amount]) => amount > 0)
      .map(([numero]) => numero);
    
    setReglementData(prev => ({
      ...prev,
      numeros_factures: activeInvoices
    }));
  }, [allocations]);

  const totalSelectedAmount = useMemo(() => {
    return selectedInvoices.reduce((sum, inv) => sum + (inv.total_ttc_calcule || 0), 0);
  }, [selectedInvoices]);

  const totalAllocated = useMemo(() => {
    return Object.values(allocations).reduce((sum, val) => sum + (parseFloat(val.toString()) || 0), 0);
  }, [allocations]);

  const remainingToAllocate = reglementData.montant_total - totalAllocated;
  const isUnderAllocated = remainingToAllocate > 0.01;

  // Handlers
  const handleFieldChange = <K extends keyof ReglementRequest>(field: K, value: ReglementRequest[K]) => {
    setReglementData(prev => ({ ...prev, [field]: value }));
  };

  const handleDeviseChange = (deviseCode: number) => {
    const devise = devises?.find(d => d.code === deviseCode);
    setReglementData(prev => ({
      ...prev,
      devise_code: deviseCode,
      cours_devise: devise?.cours_actuel || 1
    }));
  };

  const handleAllocationChange = (invoiceId: string, value: string) => {
    const numValue = parseFloat(value) || 0;
    const invoice = selectedInvoices.find(inv => inv.numero === invoiceId);
    const maxAllocation = invoice?.total_ttc_calcule || 0;
    const finalValue = Math.min(Math.max(0, numValue), maxAllocation);

    setAllocations(prev => ({ ...prev, [invoiceId]: finalValue }));
  };

  const toggleFullAllocation = (invoiceId: string, isChecked: boolean) => {
    const invoice = selectedInvoices.find(inv => inv.numero === invoiceId);
    if (!invoice) return;

    setAllocations(prev => ({
      ...prev,
      [invoiceId]: isChecked ? (invoice.total_ttc_calcule || 0) : 0
    }));
  };

  const handleValidateClick = () => {
    if(!reglementData.reference){
      toast({
        title: "Champ requis",
        description: "Veuillez ajouter la référence.",
        variant: "destructive"
      });
      return;
    }
    if (!reglementData.code_journal) {
      toast({
        title: "Champ requis",
        description: "Veuillez sélectionner un journal de trésorerie.",
        variant: "destructive"
      });
      return;
    }
    setStep('confirmation');
  };

  const handlePaymentValidate = async() => {
      try {
        console.log('Règlement validé:', reglementData);
        const result = await dispatch(reglerFacture(reglementData)).unwrap();

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

        const success = result.success
        const data = result.data

        if(success){
          for (let index = 0; index < data.reglements.length; index++) {
            const numero_facture = data.reglements[index].numero_facture
            const factureRegle = await dispatch(getReglementId(numero_facture)).unwrap();

            toast({
              title: `Règlement du facture ${numero_facture} effectué`,
              description: "Les factures ont été réglées avec succès.",
              className: "bg-green-500 text-white border-green-600"
            });
          }
          if(data.reglements.length > 1) navigate(`/home/reglements`);
          else navigate(`/home/reglements`);
        }

       
      } catch (error) {
        toast({
          title: "Erreur",
          description: "Impossible de réglé ces factures.",
          className: "bg-red-500 text-white border-red-600",
        });
      }
  };


  const clientName = selectedInvoices[0]?.client_intitule || "Client Inconnu";
  const selectedMode = modes?.find(m => m.code === reglementData.mode_reglement);
  const selectedDevise = devises?.find(d => d.code === reglementData.devise_code);
  const selectedTresorerie = tresoreries?.find(t => t.code === reglementData.code_journal);

  return (
    <AnimatePresence>
      {isOpen && (
        <>
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={onClose}
            className="fixed inset-0 bg-black/40 backdrop-blur-sm z-[60]"
          />
          <motion.div
            initial={{ x: "100%" }}
            animate={{ x: 0 }}
            exit={{ x: "100%" }}
            transition={{ type: "spring", damping: 25, stiffness: 200 }}
            className="fixed inset-y-0 right-0 w-full max-w-2xl bg-white dark:bg-gray-950 shadow-2xl z-[70] flex flex-col border-l border-gray-200 dark:border-gray-800"
          >
            {/* Header */}
            <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-800 bg-white/80 dark:bg-gray-950/80 backdrop-blur-md">
              <div>
                <h2 className="text-lg font-bold text-gray-900 dark:text-white flex items-center gap-2">
                  <Wallet className="w-5 h-5 text-[#338660]" />
                  Saisie du règlement
                </h2>
                <p className="text-sm text-gray-500 dark:text-gray-400">
                  Client : <span className="font-medium text-gray-900 dark:text-white">{clientName}</span>
                  <span className="ml-2 text-xs bg-gray-100 dark:bg-gray-800 px-2 py-0.5 rounded">{reglementData.client_id}</span>
                </p>
              </div>
              <button onClick={onClose} className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-full transition-colors">
                <X className="w-5 h-5 text-gray-500" />
              </button>
            </div>

            <div className="flex-1 overflow-y-auto custom-scrollbar p-6 bg-gray-50/50 dark:bg-black/20">
              
              {/* STEP 1: INPUT */}
              {step === 'input' && (
                <div className="space-y-6">
                  
                  {/* General Info Card */}
                  <div className="bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-xl p-5 shadow-sm space-y-4">
                    <h3 className="text-sm font-semibold text-gray-900 dark:text-white flex items-center gap-2 mb-3">
                      <Calendar className="w-4 h-4 text-gray-500" /> Informations générales
                    </h3>
                    <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-1.5">
                        <label className="text-xs font-medium text-gray-600 dark:text-gray-400">Date de règlement *</label>
                        <input 
                          type="date" 
                          value={reglementData.date_reglement}
                          onChange={(e) => handleFieldChange('date_reglement', e.target.value)}
                          className="w-full px-3 py-2 bg-gray-50 dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#338660]"
                        />
                      </div>
                      <div className="space-y-1.5">
                        <label className="text-xs font-medium text-gray-600 dark:text-gray-400">Date d'échéance *</label>
                        <input 
                          type="date" 
                          value={reglementData.date_echeance}
                          onChange={(e) => handleFieldChange('date_echeance', e.target.value)}
                          className="w-full px-3 py-2 bg-gray-50 dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#338660]"
                        />
                      </div>
                      <div className="space-y-1.5">
                        <label className="text-xs font-medium text-gray-600 dark:text-gray-400">Mode de paiement *</label>
                        <select 
                          value={reglementData.mode_reglement}
                          onChange={(e) => handleFieldChange('mode_reglement', Number(e.target.value))}
                          className="w-full px-3 py-2 bg-gray-50 dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#338660]"
                        >
                          {modes?.map(mode => (
                            <option key={mode.code} value={mode.code}>
                              {mode.intitule}
                            </option>
                          ))}
                        </select>
                      </div>
                      <div className="space-y-1.5">
                        <label className="text-xs font-medium text-gray-600 dark:text-gray-400">Journal de trésorerie *</label>
                        <select 
                          value={reglementData.code_journal}
                          onChange={(e) => handleFieldChange('code_journal', e.target.value)}
                          className="w-full px-3 py-2 bg-gray-50 dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#338660]"
                        >
                          <option value="">Sélectionner...</option>
                          {tresoreries?.map(tres => (
                            <option key={tres.code} value={tres.code}>
                              {tres.code} - {tres.intitule}
                            </option>
                          ))}
                        </select>
                      </div>
                      <div className="space-y-1.5">
                        <label className="text-xs font-medium text-gray-600 dark:text-gray-400">Devise</label>
                        <select 
                          value={reglementData.devise_code}
                          onChange={(e) => handleDeviseChange(Number(e.target.value))}
                          className="w-full px-3 py-2 bg-gray-50 dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#338660]"
                        >
                          {sortedDevises.map(devise => (
                            <option key={devise.code} value={devise.code}>
                              {devise.intitule} ({devise.sigle}) {devise.est_principale && '★'}
                            </option>
                          ))}
                        </select>
                      </div>
                      <div className="space-y-1.5">
                        <label className="text-xs font-medium text-gray-600 dark:text-gray-400">Cours devise</label>
                        <input 
                          type="number"
                          step="0.0001"
                          value={reglementData.cours_devise}
                          onChange={(e) => handleFieldChange('cours_devise', parseFloat(e.target.value) || 1)}
                          className="w-full px-3 py-2 bg-gray-50 dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#338660]"
                        />
                      </div>
                      <div className="col-span-2 space-y-1.5">
                        <label className="text-xs font-medium text-gray-600 dark:text-gray-400">Libellé</label>
                        <input 
                          type="text" 
                          placeholder="Reglement multiple"
                          value={reglementData.libelle}
                          onChange={(e) => handleFieldChange('libelle', e.target.value)}
                          className="w-full px-3 py-2 bg-gray-50 dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#338660]"
                        />
                      </div>
                      <div className="col-span-2 space-y-1.5">
                        <label className="text-xs font-medium text-gray-600 dark:text-gray-400">Référence <span className='font-bold'>*</span></label>
                        <input 
                          type="text" 
                          placeholder="Ex: CHQ-001, VIR-2025-00123"
                          required
                          value={reglementData.reference}
                          onChange={(e) => handleFieldChange('reference', e.target.value)}
                          className="w-full px-3 py-2 bg-gray-50 dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#338660]"
                        />
                      </div>
                      <div className="col-span-2 flex items-center gap-3 pt-2">
                        <Checkbox 
                          id="tva_encaissement"
                          checked={reglementData.tva_encaissement}
                          onCheckedChange={(checked) => handleFieldChange('tva_encaissement', checked as boolean)}
                        />
                        <label htmlFor="tva_encaissement" className="text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
                          TVA sur encaissement
                        </label>
                      </div>
                    </div>
                  </div>

                  {/* Amounts & Ventilation Card */}
                  <div className="bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-xl p-5 shadow-sm space-y-4">
                    <div className="flex items-center justify-between mb-2">
                       <h3 className="text-sm font-semibold text-gray-900 dark:text-white flex items-center gap-2">
                         <Coins className="w-4 h-4 text-gray-500" /> Montants & Ventilation
                       </h3>
                       <div className="text-xs text-gray-500">
                          Total sélectionné : {formatCurrency(totalSelectedAmount)}
                       </div>
                    </div>
                    
                    {/* Main Payment Amount Input */}
                    <div className="bg-[#338660]/5 dark:bg-[#338660]/10 border border-[#338660]/20 rounded-lg p-4 flex items-center justify-between">
                       <div>
                         <label className="block text-sm font-bold text-[#338660]">Montant total du règlement *</label>
                         <div className="text-xs text-gray-500 mt-1">
                           Saisissez le montant total reçu
                         </div>
                       </div>
                       <div className="relative w-40">
                         <input 
                           type="number"
                           step="0.01"
                           value={reglementData.montant_total}
                           onChange={(e) => handleFieldChange('montant_total', parseFloat(e.target.value) || 0)}
                           className="w-full pl-4 pr-8 py-2 bg-white dark:bg-gray-950 border border-[#338660]/30 rounded-lg text-lg font-bold text-right focus:outline-none focus:ring-2 focus:ring-[#338660]"
                         />
                         <span className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 font-medium">
                           {selectedDevise?.sigle || '€'}
                         </span>
                       </div>
                    </div>

                    {/* Status Indicators */}
                    <div className="grid grid-cols-2 gap-4">
                      <div className="bg-gray-50 dark:bg-gray-800/50 rounded-lg p-3 border border-gray-100 dark:border-gray-800">
                        <span className="text-xs text-gray-500 block">Montant ventilé</span>
                        <span className={cn(
                          "text-lg font-bold block text-gray-900 dark:text-white",
                        )}>
                          {formatCurrency(totalAllocated)}
                        </span>
                      </div>
                      <div className="bg-gray-50 dark:bg-gray-800/50 rounded-lg p-3 border border-gray-100 dark:border-gray-800">
                        <span className="text-xs text-gray-500 block">Reste à ventiler</span>
                        <span className={cn(
                          "text-lg font-bold block",
                          remainingToAllocate < 0 ? "text-red-500" : (remainingToAllocate === 0 ? "text-green-500" : "text-amber-500")
                        )}>
                          {formatCurrency(remainingToAllocate)}
                        </span>
                      </div>
                    </div>

                    {/* Error Messages */}
                    {isUnderAllocated && (
                       <div className="flex items-start gap-2 p-3 bg-amber-50 dark:bg-amber-900/20 text-amber-600 text-sm rounded-lg border border-amber-100 dark:border-amber-900/50">
                        <AlertTriangle className="w-5 h-5 shrink-0" />
                        <p>Note : Une partie du règlement n'est pas affectée ({formatCurrency(remainingToAllocate)}).</p>
                      </div>
                    )}

                    {/* Ventilation Table */}
                    <div className="mt-4 border rounded-lg border-gray-200 dark:border-gray-800 overflow-hidden">
                      <table className="w-full text-sm">
                        <thead className="bg-gray-50 dark:bg-gray-950 text-gray-500 font-medium border-b border-gray-200 dark:border-gray-800">
                          <tr>
                            <th className="px-4 py-2 text-left">Facture</th>
                            <th className="px-4 py-2 text-right">Solde Dû</th>
                            <th className="px-4 py-2 text-center w-24">Tout régler</th>
                            <th className="px-4 py-2 text-right w-40">Montant affecté</th>
                          </tr>
                        </thead>
                        <tbody className="divide-y divide-gray-100 dark:divide-gray-800">
                          {selectedInvoices.map(invoice => (
                            <tr key={invoice.numero} className="group hover:bg-gray-50/50 dark:hover:bg-gray-900/20">
                              <td className="px-4 py-3">
                                <div className="font-medium text-gray-900 dark:text-white">{invoice.numero}</div>
                                <div className="text-xs text-gray-500">{new Date(invoice.date).toLocaleDateString()}</div>
                              </td>
                              <td className="px-4 py-3 text-right text-gray-600 dark:text-gray-300">
                                {formatCurrency(invoice.total_ttc_calcule || 0)}
                              </td>
                              <td className="px-4 py-3 text-center">
                                <div className="flex justify-center">
                                  <Checkbox 
                                    checked={Math.abs((allocations[invoice.numero] || 0) - (invoice.total_ttc_calcule || 0)) < 0.01 && (invoice.total_ttc_calcule > 0)}
                                    onCheckedChange={(checked) => toggleFullAllocation(invoice.numero, checked as boolean)}
                                  />
                                </div>
                              </td>
                              <td className="px-4 py-3 text-right">
                                <div className="relative">
                                  <input 
                                    type="number"
                                    step="0.01"
                                    min="0"
                                    max={invoice.total_ttc_calcule}
                                    value={allocations[invoice.numero] || 0}
                                    onChange={(e) => handleAllocationChange(invoice.numero, e.target.value)}
                                    className="w-full text-right bg-transparent border-b border-gray-200 dark:border-gray-700 focus:border-[#338660] focus:ring-0 px-1 py-1 font-mono text-sm"
                                  />
                                </div>
                              </td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>
              )}

              {/* STEP 2: CONFIRMATION */}
              {step === 'confirmation' && (
                <div className="space-y-6">
                  <div className="bg-green-50 dark:bg-green-900/10 border border-green-100 dark:border-green-900/30 rounded-xl p-6 text-center">
                    <div className="w-12 h-12 bg-green-100 dark:bg-green-900/30 rounded-full flex items-center justify-center mx-auto mb-3">
                      <CheckCircle className="w-6 h-6 text-[#338660]" />
                    </div>
                    <h3 className="text-lg font-bold text-gray-900 dark:text-white">Confirmer le règlement</h3>
                    <p className="text-sm text-gray-500 mt-1">Veuillez vérifier les informations ci-dessous avant de valider.</p>
                  </div>

                  <div className="bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-xl overflow-hidden">
                    <div className="p-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-950">
                       <h4 className="font-semibold text-gray-900 dark:text-white text-sm">Récapitulatif</h4>
                    </div>
                    <div className="p-4 space-y-3">
                       <div className="flex justify-between text-sm">
                         <span className="text-gray-500">Client</span>
                         <span className="font-medium">{clientName} ({reglementData.client_id})</span>
                       </div>
                       <div className="flex justify-between text-sm">
                         <span className="text-gray-500">Date règlement</span>
                         <span className="font-medium">{new Date(reglementData.date_reglement).toLocaleDateString()}</span>
                       </div>
                       <div className="flex justify-between text-sm">
                         <span className="text-gray-500">Date échéance</span>
                         <span className="font-medium">{new Date(reglementData.date_echeance).toLocaleDateString()}</span>
                       </div>
                       <div className="flex justify-between text-sm">
                         <span className="text-gray-500">Mode de paiement</span>
                         <span className="font-medium">{selectedMode?.intitule || '-'}</span>
                       </div>
                       <div className="flex justify-between text-sm">
                         <span className="text-gray-500">Journal</span>
                         <span className="font-medium">{selectedTresorerie?.code} - {selectedTresorerie?.intitule}</span>
                       </div>
                       <div className="flex justify-between text-sm">
                         <span className="text-gray-500">Devise</span>
                         <span className="font-medium">{selectedDevise?.intitule} (cours: {reglementData.cours_devise})</span>
                       </div>
                       <div className="flex justify-between text-sm">
                         <span className="text-gray-500">Libellé</span>
                         <span className="font-medium">{reglementData.libelle}</span>
                       </div>
                       <div className="flex justify-between text-sm">
                         <span className="text-gray-500">Référence</span>
                         <span className="font-medium">{reglementData.reference || '-'}</span>
                       </div>
                       <div className="flex justify-between text-sm">
                         <span className="text-gray-500">TVA sur encaissement</span>
                         <span className="font-medium">{reglementData.tva_encaissement ? 'Oui' : 'Non'}</span>
                       </div>
                       <div className="h-px bg-gray-100 dark:bg-gray-800 my-2" />
                       <div className="flex justify-between text-base font-bold">
                         <span className="text-gray-900 dark:text-white">Montant Total</span>
                         <span className="text-[#338660]">{formatCurrency(reglementData.montant_total)} {selectedDevise?.sigle}</span>
                       </div>
                       <div className="flex justify-between text-sm text-gray-500">
                          <span>Montant non affecté (acompte/crédit)</span>
                          <span>{formatCurrency(remainingToAllocate > 0 ? remainingToAllocate : 0)}</span>
                       </div>
                    </div>
                  </div>

                  <div className="space-y-2">
                    <h4 className="text-sm font-semibold text-gray-900 dark:text-white px-1">
                      Factures concernées ({reglementData.numeros_factures.length})
                    </h4>
                    {selectedInvoices.filter(inv => (allocations[inv.numero] || 0) > 0).map(inv => (
                      <div key={inv.numero} className="flex justify-between items-center p-3 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-800 rounded-lg text-sm">
                         <div>
                            <span className="font-medium text-gray-900 dark:text-white">{inv.numero}</span>
                            <div className="text-xs text-gray-500">Solde avant: {formatCurrency(inv.total_ttc_calcule || 0)}</div>
                         </div>
                         <div className="text-right">
                            <span className="font-bold text-[#338660]">-{formatCurrency(allocations[inv.numero] || 0)}</span>
                            <div className="text-xs text-gray-500">
                               Reste: {formatCurrency((inv.total_ttc_calcule || 0) - (allocations[inv.numero] || 0))}
                            </div>
                         </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

            </div>

            {/* Footer */}
            <div className="p-4 border-t border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-950 z-10 flex justify-end gap-3">
              {step === 'input' ? (
                <>
                  <button onClick={onClose} className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors">
                    Annuler
                  </button>
                  <PrimaryButton_v2 onClick={handleValidateClick} disabled={reglementData.montant_total <= 0}>
                    Suivant
                  </PrimaryButton_v2>
                </>
              ) : (
                <>
                  <button onClick={() => setStep('input')} className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors">
                    Retour
                  </button>
                  <PrimaryButton_v2 disabled={statsReglement === "loading"} onClick={handlePaymentValidate} className="bg-[#338660] hover:bg-[#2A6F4F]">
                    
                    {statsReglement === "loading" ? (
                      <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                    ):(
                      <CheckCircle className="w-4 h-4 mr-2" />
                    )}
                    Valider le règlement
                  </PrimaryButton_v2>
                </>
              )}
            </div>

          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
};

export default ModalPaymentPanel;