import React, { useState, useEffect } from 'react';
import { Helmet } from 'react-helmet';
import { useParams, useNavigate, useLocation } from 'react-router-dom';
import { 
  ArrowLeft, Lock, Download, MoreVertical, Trash2, 
  CheckCircle, Plus, RefreshCw, Eye
} from 'lucide-react';
import StatusBadge from '@/components/StatusBadge';
import PrimaryButton from '@/components/PrimaryButton';
import Tabs from '@/components/Tabs';
import Timeline from '@/components/Timeline';
import { Input, Select, Textarea, FormField } from '@/components/FormModal';
import ClientSearchInput from '@/components/inputs/ClientSearchInput';
import PDFPreviewPanel from '@/components/panels/PDFPreviewPanel';
import { toast } from '@/components/ui/use-toast';
import { mockPayments, mockInvoices, mockClients, currentUser } from '@/data/mockData';
import { cn } from '@/lib/utils';

const formatCurrency = (val) => new Intl.NumberFormat('fr-FR', { style: 'currency', currency: 'EUR' }).format(val);

const emptyPayment = {
  id: 'new',
  number: 'REG-PROVISOIRE',
  clientId: null,
  clientName: '',
  date: new Date().toISOString().split('T')[0],
  mode: 'Virement',
  reference: '',
  amount: 0,
  allocatedAmount: 0,
  remainingBalance: 0,
  status: 'Brouillon',
  notes: '',
  allocations: [],
  timeline: []
};

const PaymentDetailPage = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const location = useLocation();
  const isNew = id === 'new';
  
  const [activeTab, setActiveTab] = useState('identification');
  const [isEditing, setIsEditing] = useState(isNew);
  const [isPDFPreviewOpen, setIsPDFPreviewOpen] = useState(false);
  
  const [payment, setPayment] = useState(null);
  const [selectedClient, setSelectedClient] = useState(null);
  const [clientInvoices, setClientInvoices] = useState([]);

  useEffect(() => {
    if (isNew) {
       // Check for initial client from state (e.g., coming from Client Detail)
       const initialClient = location.state?.client || null;
       const initialInvoice = location.state?.invoice || null;

       let newPayment = { ...emptyPayment };
       if (initialClient) {
           newPayment.clientId = initialClient.id;
           newPayment.clientName = initialClient.company;
           setSelectedClient(initialClient);
       }
       
       if (initialInvoice) {
           // Pre-fill amount from invoice balance
           newPayment.amount = initialInvoice.balanceDue;
           newPayment.reference = `Regl. ${initialInvoice.number}`;
       }

       setPayment(newPayment);
       setIsEditing(true);
       setActiveTab('identification');
    } else {
      const found = mockPayments.find(p => p.id === parseInt(id));
      if (found) {
         setPayment({
             ...found,
             // Ensure fields exist
             notes: found.notes || '',
             timeline: found.timeline || []
         });
         const fullClient = mockClients.find(c => c.id === found.clientId);
         setSelectedClient(fullClient || { id: found.clientId, company: found.clientName });
      }
    }
  }, [id, isNew, location.state]);

  // Load Invoices when client changes
  useEffect(() => {
      if (payment?.clientId) {
          // Find unpaid invoices for this client
          const openInvoices = mockInvoices.filter(inv => 
              inv.clientId === payment.clientId && 
              inv.status !== 'Brouillon' && 
              inv.balanceDue > 0
          ).sort((a, b) => new Date(a.dueDate) - new Date(b.dueDate)); // Sort by Due Date Ascending

          // Augment invoices with allocation data from current payment
          const invoicesWithAllocation = openInvoices.map(inv => {
              const existingAlloc = payment.allocations.find(a => a.invoiceId === inv.id);
              return {
                  ...inv,
                  currentAllocation: existingAlloc ? existingAlloc.amount : 0
              };
          });
          
          setClientInvoices(invoicesWithAllocation);
      } else {
          setClientInvoices([]);
      }
  }, [payment?.clientId, payment?.allocations]); // Re-run if allocations change to keep sync, though simple state update below handles input

  // Calculations
  useEffect(() => {
      if (!payment) return;
      // Only recalc if editing
      if (isEditing) {
          const totalAllocated = payment.allocations.reduce((sum, a) => sum + a.amount, 0);
          setPayment(prev => ({
              ...prev,
              allocatedAmount: totalAllocated,
              remainingBalance: Math.max(0, prev.amount - totalAllocated)
          }));
      }
  }, [payment?.allocations, payment?.amount, isEditing]);

  if (!payment) return <div className="min-h-screen flex items-center justify-center"><div className="animate-spin w-8 h-8 border-4 border-[#941403] border-t-transparent rounded-full"></div></div>;

  const isDraft = payment.status === 'Brouillon';
  const isValidated = payment.status === 'Validé' || payment.status === 'Imputé' || payment.status === 'Crédit client';
  const fieldsDisabled = !isEditing || isValidated;

  // --- HANDLERS ---
  const handleClientSelect = (client) => {
    if (fieldsDisabled) return;
    setSelectedClient(client);
    setPayment(prev => ({
       ...prev,
       clientName: client ? (client.company || `${client.firstName} ${client.lastName}`) : '',
       clientId: client ? client.id : null,
       allocations: [] // Clear allocations on client change
    }));
  };

  const handleAmountChange = (val) => {
      const newAmount = parseFloat(val) || 0;
      setPayment(prev => ({ ...prev, amount: newAmount }));
  };

  const handleAutoAllocate = () => {
      let remaining = payment.amount;
      const newAllocations = [];
      
      const updatedInvoices = [...clientInvoices]; // These are sorted by due date

      for (const inv of updatedInvoices) {
          if (remaining <= 0) break;
          
          const amountToAllocate = Math.min(remaining, inv.balanceDue);
          if (amountToAllocate > 0) {
              newAllocations.push({
                  invoiceId: inv.id,
                  invoiceNumber: inv.number,
                  amount: amountToAllocate
              });
              remaining -= amountToAllocate;
          }
      }

      setPayment(prev => ({
          ...prev,
          allocations: newAllocations
      }));
      
      toast({ title: "Imputation automatique", description: "Les montants ont été répartis par échéance." });
  };

  const handleManualAllocation = (invoiceId, val) => {
      const amount = parseFloat(val) || 0;
      // Validate max amount
      const invoice = clientInvoices.find(i => i.id === invoiceId);
      if (!invoice) return;

      if (amount > invoice.balanceDue) {
          // Prevent over allocation on invoice
          return; 
      }

      // Check global limit? Maybe soft check or just visual
      
      setPayment(prev => {
          const filtered = prev.allocations.filter(a => a.invoiceId !== invoiceId);
          if (amount > 0) {
              filtered.push({
                  invoiceId: invoiceId,
                  invoiceNumber: invoice.number,
                  amount: amount
              });
          }
          return { ...prev, allocations: filtered };
      });
  };

  const handleSave = () => {
     if (!payment.clientId) {
        toast({ title: "Client manquant", description: "Veuillez sélectionner un client.", variant: "destructive" });
        return;
     }
     if (payment.amount <= 0) {
        toast({ title: "Montant invalide", description: "Le montant doit être supérieur à 0.", variant: "destructive" });
        return;
     }

     setIsEditing(false);
     if (isNew) {
        toast({ title: "Règlement créé", description: "Le brouillon a été enregistré.", variant: "success" });
        navigate('/reglements'); 
     } else {
        setPayment(prev => ({
            ...prev,
            timeline: [{ date: new Date().toISOString(), type: 'update', title: 'Règlement modifié', user: currentUser.name }, ...prev.timeline]
        }));
        toast({ title: "Sauvegardé", description: "Les modifications ont été enregistrées.", variant: "success" });
     }
  };

  const handleValidate = () => {
      let finalStatus = 'Validé';
      if (payment.remainingBalance === 0 && payment.amount > 0) finalStatus = 'Imputé';
      if (payment.remainingBalance > 0) finalStatus = 'Crédit client';

      setPayment(prev => ({
          ...prev,
          status: finalStatus,
          number: prev.number.replace('PROVISOIRE', `REG-2025-${Math.floor(Math.random()*1000)}`), 
          timeline: [{ date: new Date().toISOString(), type: 'validation', title: 'Règlement validé', description: `Statut: ${finalStatus}`, user: currentUser.name }, ...prev.timeline]
      }));
      setIsEditing(false);
      toast({ title: "Règlement validé", description: "Le paiement est verrouillé et les écritures sont passées.", variant: "success" });
  };

  const tabs = [
    { id: 'identification', label: 'Identification' },
    { id: 'allocations', label: 'Imputations', count: payment.allocations.length },
    { id: 'documents', label: 'Documents', count: payment.linkedDocuments?.length || 0 },
    { id: 'timeline', label: 'Historique' },
  ];

  return (
    <>
      <Helmet>
        <title>{payment.number} - Règlement - Bijou ERP</title>
      </Helmet>

      <div className="flex flex-col min-h-screen bg-gray-50/50 dark:bg-black/20 pb-20">
        
        {/* TOP HEADER */}
        <div className="bg-white dark:bg-gray-950 border-b border-gray-200 dark:border-gray-800 sticky top-0 z-30 shadow-sm">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex items-center justify-between h-16">
               <div className="flex items-center gap-4">
                  <button onClick={() => navigate('/reglements')} className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-full transition-colors text-gray-500">
                     <ArrowLeft className="w-5 h-5" />
                  </button>
                  <div>
                     <div className="flex items-center gap-3">
                        <h1 className="text-xl font-bold text-gray-900 dark:text-white">{payment.number}</h1>
                        <StatusBadge status={payment.status} />
                     </div>
                     <div className="flex items-center gap-2 text-sm text-gray-500">
                        <span className="font-medium text-gray-900 dark:text-gray-300">{payment.clientName || 'Client inconnu'}</span>
                        <span>•</span>
                        <span>{new Date(payment.date).toLocaleDateString()}</span>
                        <span className="text-[#941403] font-bold ml-2">{formatCurrency(payment.amount)}</span>
                     </div>
                  </div>
               </div>

               <div className="flex items-center gap-2">
                  <button 
                    onClick={() => setIsPDFPreviewOpen(true)}
                    className="flex items-center gap-2 px-3 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-200 rounded-xl hover:bg-gray-50 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-200 dark:hover:bg-gray-700 transition-colors"
                  >
                    <Eye className="w-4 h-4" />
                    <span className="hidden sm:inline">Aperçu</span>
                  </button>

                  {isDraft && (
                      <PrimaryButton onClick={handleValidate} className="bg-blue-600 hover:bg-blue-700">
                          <Lock className="w-4 h-4 mr-2" /> Valider
                      </PrimaryButton>
                  )}

                  {!isDraft && !isNew && (
                     <button className="p-2 border border-gray-200 dark:border-gray-800 rounded-xl hover:bg-gray-50 dark:hover:bg-gray-900 text-gray-600 dark:text-gray-400" title="Télécharger">
                        <Download className="w-5 h-5"/>
                     </button>
                  )}

                  {isDraft && !isEditing && (
                     <button 
                        onClick={() => setIsEditing(true)}
                        className="px-4 py-2 text-sm font-medium text-gray-600 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white border border-gray-200 dark:border-gray-700 rounded-xl hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
                     >
                        Modifier
                     </button>
                  )}

                  {isEditing && (
                     <>
                        <button 
                           onClick={() => isNew ? navigate('/reglements') : setIsEditing(false)}
                           className="px-4 py-2 text-sm font-medium text-gray-600 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white transition-colors"
                        >
                           Annuler
                        </button>
                        <PrimaryButton onClick={handleSave}>Enregistrer</PrimaryButton>
                     </>
                  )}
               </div>
            </div>
          </div>
        </div>

        {/* LOCKED BANNER */}
        {isValidated && (
            <div className="bg-blue-50 dark:bg-blue-900/20 border-b border-blue-100 dark:border-blue-800 px-4 py-3 text-center">
                <p className="text-sm text-blue-800 dark:text-blue-200 font-medium flex items-center justify-center gap-2">
                    <Lock className="w-4 h-4" />
                    Ce règlement est validé et n'est plus modifiable.
                </p>
            </div>
        )}

        {/* CONTENT */}
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 w-full mt-6">
           <Tabs tabs={tabs} active={activeTab} onChange={setActiveTab} />
           
           <div className="mt-6">
              {/* --- IDENTIFICATION TAB --- */}
              {activeTab === 'identification' && (
                 <div className="space-y-6">
                    <div className="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-6 relative overflow-hidden">
                       <h3 className="text-lg font-bold text-gray-900 dark:text-white mb-4">Détails du paiement</h3>
                       <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                          <FormField label="Client *" required fullWidth>
                              <ClientSearchInput 
                                 value={selectedClient} 
                                 onChange={handleClientSelect} 
                                 disabled={fieldsDisabled}
                                 placeholder="Rechercher un client..."
                              />
                          </FormField>
                          <div className="grid grid-cols-2 gap-4">
                             <FormField label="Date de règlement" required>
                                <Input type="date" value={payment.date} onChange={(e) => !fieldsDisabled && setPayment({...payment, date: e.target.value})} disabled={fieldsDisabled} />
                             </FormField>
                             <FormField label="Mode de paiement">
                                 <Select value={payment.mode} onChange={(e) => !fieldsDisabled && setPayment({...payment, mode: e.target.value})} disabled={fieldsDisabled}>
                                    <option value="Virement">Virement</option>
                                    <option value="CB">Carte Bancaire</option>
                                    <option value="Prélèvement">Prélèvement</option>
                                    <option value="Chèque">Chèque</option>
                                    <option value="Espèces">Espèces</option>
                                    <option value="Autre">Autre</option>
                                 </Select>
                             </FormField>
                          </div>
                          <FormField label="Référence bancaire / Libellé">
                             <Input value={payment.reference} onChange={(e) => !fieldsDisabled && setPayment({...payment, reference: e.target.value})} disabled={fieldsDisabled} placeholder="Ex: VIR 12345" />
                          </FormField>
                          <FormField label="Montant reçu (€) *" required>
                             <Input 
                                type="number" 
                                min="0" 
                                step="0.01" 
                                value={payment.amount} 
                                onChange={(e) => !fieldsDisabled && handleAmountChange(e.target.value)} 
                                disabled={fieldsDisabled} 
                                className="font-bold text-lg"
                             />
                          </FormField>
                          <FormField label="Notes internes" fullWidth>
                             <Textarea value={payment.notes} onChange={(e) => !fieldsDisabled && setPayment({...payment, notes: e.target.value})} disabled={fieldsDisabled} rows={2} />
                          </FormField>
                       </div>
                    </div>
                 </div>
              )}

              {/* --- ALLOCATIONS TAB --- */}
              {activeTab === 'allocations' && (
                 <div className="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-6 shadow-sm">
                     <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6">
                        <div>
                            <h3 className="text-lg font-bold text-gray-900 dark:text-white">Imputations</h3>
                            <p className="text-sm text-gray-500">Répartissez le montant reçu sur les factures en attente.</p>
                        </div>
                        {!fieldsDisabled && (
                           <button 
                                onClick={handleAutoAllocate}
                                className="flex items-center gap-2 px-4 py-2 bg-blue-50 text-blue-700 hover:bg-blue-100 rounded-lg text-sm font-medium transition-colors"
                           >
                              <RefreshCw className="w-4 h-4" /> Imputation automatique
                           </button>
                        )}
                     </div>

                     {/* Summary Bar */}
                     <div className="grid grid-cols-3 gap-4 mb-6">
                         <div className="p-4 bg-gray-50 dark:bg-gray-900 rounded-xl border border-gray-100 dark:border-gray-800">
                             <p className="text-xs text-gray-500 uppercase font-bold">Montant Reçu</p>
                             <p className="text-xl font-bold text-gray-900 dark:text-white">{formatCurrency(payment.amount)}</p>
                         </div>
                         <div className="p-4 bg-green-50 dark:bg-green-900/20 rounded-xl border border-green-100 dark:border-green-800">
                             <p className="text-xs text-green-700 uppercase font-bold">Montant Imputé</p>
                             <p className="text-xl font-bold text-green-700">{formatCurrency(payment.allocatedAmount)}</p>
                         </div>
                         <div className={cn(
                             "p-4 rounded-xl border",
                             payment.remainingBalance > 0 ? "bg-purple-50 dark:bg-purple-900/20 border-purple-100 dark:border-purple-800" : "bg-gray-50 dark:bg-gray-900 border-gray-100 dark:border-gray-800"
                         )}>
                             <p className={cn("text-xs uppercase font-bold", payment.remainingBalance > 0 ? "text-purple-700" : "text-gray-500")}>
                                 {payment.remainingBalance > 0 ? "Solde (Crédit)" : "Solde"}
                             </p>
                             <p className={cn("text-xl font-bold", payment.remainingBalance > 0 ? "text-purple-700" : "text-gray-500")}>
                                 {formatCurrency(payment.remainingBalance)}
                             </p>
                         </div>
                     </div>

                     {clientInvoices.length > 0 ? (
                         <div className="overflow-x-auto">
                            <table className="w-full text-sm">
                               <thead className="bg-gray-50 dark:bg-gray-900 text-xs uppercase text-gray-500 font-semibold border-b border-gray-200 dark:border-gray-800">
                                  <tr>
                                     <th className="px-4 py-3 text-left">Facture</th>
                                     <th className="px-4 py-3 text-left">Date</th>
                                     <th className="px-4 py-3 text-left text-red-600">Dû le</th>
                                     <th className="px-4 py-3 text-right">Montant TTC</th>
                                     <th className="px-4 py-3 text-right">Reste à payer</th>
                                     <th className="px-4 py-3 text-right w-40">Imputation</th>
                                  </tr>
                               </thead>
                               <tbody className="divide-y divide-gray-100 dark:divide-gray-800">
                                  {clientInvoices.map(inv => {
                                      const allocatedHere = payment.allocations.find(a => a.invoiceId === inv.id)?.amount || 0;
                                      return (
                                          <tr key={inv.id} className="hover:bg-gray-50 dark:hover:bg-gray-900/50">
                                              <td className="px-4 py-3 font-medium">{inv.number}</td>
                                              <td className="px-4 py-3 text-gray-500">{new Date(inv.date).toLocaleDateString()}</td>
                                              <td className="px-4 py-3 text-red-600 font-medium">{new Date(inv.dueDate).toLocaleDateString()}</td>
                                              <td className="px-4 py-3 text-right text-gray-600">{formatCurrency(inv.amountTTC)}</td>
                                              <td className="px-4 py-3 text-right font-bold">{formatCurrency(inv.balanceDue)}</td>
                                              <td className="px-4 py-3 text-right">
                                                  <Input 
                                                      type="number" 
                                                      min="0"
                                                      max={inv.balanceDue}
                                                      value={allocatedHere}
                                                      onChange={(e) => handleManualAllocation(inv.id, e.target.value)}
                                                      disabled={fieldsDisabled}
                                                      className={cn(
                                                          "text-right h-8 py-1",
                                                          allocatedHere > 0 && "border-green-500 bg-green-50 text-green-900 font-bold"
                                                      )}
                                                  />
                                              </td>
                                          </tr>
                                      );
                                  })}
                               </tbody>
                            </table>
                         </div>
                     ) : (
                         <div className="text-center py-12 text-gray-500">
                             <CheckCircle className="w-12 h-12 mx-auto mb-2 text-gray-300" />
                             <p>Aucune facture en attente de paiement pour ce client.</p>
                         </div>
                     )}
                 </div>
              )}

              {/* --- DOCUMENTS TAB --- */}
              {activeTab === 'documents' && (
                 <div className="space-y-6">
                    {/* Reuse simplified doc view */}
                    <div className="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-8 text-center text-gray-500">
                        <p>Module Documents identique aux autres pages...</p>
                    </div>
                 </div>
              )}

              {/* --- TIMELINE TAB --- */}
              {activeTab === 'timeline' && (
                 <div className="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl p-6">
                    <Timeline events={payment.timeline} />
                 </div>
              )}
           </div>
        </div>
      </div>
      
      <PDFPreviewPanel 
         isOpen={isPDFPreviewOpen}
         onClose={() => setIsPDFPreviewOpen(false)}
         title={`Recu - ${payment.number}`}
      />
    </>
  );
};

export default PaymentDetailPage;