import React, { useState, useEffect, useCallback } from 'react';
import {
  Plus, CurrencyDollar, CheckCircle, XCircle, Clock,
  FileText, Calendar, Percent, Wallet, TrendUp, Upload, X,
  Warning, ArrowRight, Buildings, Eye, UserCircle, Money
} from '@phosphor-icons/react';
import toast from 'react-hot-toast';
import axios from 'axios';
import useAuthStore from '../store/authStore';

const fmt = v => `\u20A6${Number(v || 0).toLocaleString()}`;
const fmtD = d => d ? new Date(d).toLocaleDateString('en-GB', { day:'2-digit', month:'short', year:'numeric' }) : '\u2014';

const FI = ({label,...p}) => (
  <div>
    <label className="block text-xs font-semibold text-gray-600 mb-1">{label}</label>
    <input className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-primary-500 outline-none" {...p}/>
  </div>
);
const SE = ({label,children,...p}) => (
  <div>
    <label className="block text-xs font-semibold text-gray-600 mb-1">{label}</label>
    <select className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-primary-500 outline-none bg-white" {...p}>{children}</select>
  </div>
);

const STATUS_STYLE = {
  pending:              'bg-yellow-100 text-yellow-700 border-yellow-200',
  approved:             'bg-green-100 text-green-700 border-green-200',
  rejected:             'bg-red-100 text-red-700 border-red-200',
  paid:                 'bg-primary-100 text-primary-700 border-primary-200',
  overdue:              'bg-red-200 text-red-800 border-red-300',
  pending_confirmation: 'bg-orange-100 text-orange-700 border-orange-200',
};

export default function LoanManagement() {
  const { user } = useAuthStore();
  const [loans, setLoans]           = useState([]);
  const [loading, setLoading]       = useState(true);
  const [tab, setTab]               = useState('all');
  const [saving, setSaving]         = useState(false);

  const [selectedLoan, setSelectedLoan] = useState(null);
  const [showDetail, setShowDetail]     = useState(false);
  const [repayments, setRepayments]     = useState([]);
  const [detailLoading, setDetailLoading] = useState(false);
  const [showRepayModal, setShowRepayModal] = useState(false);
  const [confirmModal, setConfirmModal] = useState(null);
  const [confirmReceiptFile, setConfirmReceiptFile] = useState(null);
  const [confirmBankAccountId, setConfirmBankAccountId] = useState('');
  const [confirmSuperAdminBankAccountId, setConfirmSuperAdminBankAccountId] = useState('');
  const [receiptFile, setReceiptFile]   = useState(null);
  const [approveModal, setApproveModal] = useState(null);
  const [approveForm, setApproveForm] = useState({ payment_method: 'bank', bank_account_id: '', super_admin_bank_account_id: '' });
  const [superAdminBankAccounts, setSuperAdminBankAccounts] = useState([]);

  const [repayForm, setRepayForm] = useState({
    amount: '', payment_date: new Date().toISOString().split('T')[0],
    payment_method: 'bank_transfer', reference_number: '', notes: '',
  });

  // Staff loans state
  const [staffLoans, setStaffLoans]               = useState([]);
  const [staffLoading, setStaffLoading]           = useState(false);
  const [showStaffModal, setShowStaffModal]       = useState(false);
  const [showStaffApproveModal, setShowStaffApproveModal] = useState(false);
  const [staffForm, setStaffForm]                 = useState({
    employee_id: '', amount: '', interest_rate: '0', term_months: '',
    purpose: '', deduction_type: 'fixed', deduction_value: '', notes: '',
    payment_method: 'cash', bank_account_id: '',
  });
  const [employees, setEmployees]                 = useState([]);
  const [bankAccounts, setBankAccounts]         = useState([]);
  const [selectedStaffLoan, setSelectedStaffLoan] = useState(null);
  const [staffApproveForm, setStaffApproveForm] = useState({ payment_method: 'cash', bank_account_id: '' });
  const [showStaffDetail, setShowStaffDetail]     = useState(false);
  const [staffDeductions, setStaffDeductions]     = useState([]);
  const [staffDetailLoading, setStaffDetailLoading] = useState(false);

  const isSuperAdmin = user?.roles?.some(r => r.name === 'Super Admin');
  // We no longer rely on company.is_holding_company in the UI; approval is role-gated.
  const canApprove   = isSuperAdmin; // Super Admin can approve loans
  const canManageStaff = isSuperAdmin
    || user?.roles?.some(r => ['Company Admin','Finance Manager','HR Manager'].includes(r.name));

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const [loansRes, bankRes] = await Promise.all([
        axios.get('/api/loans'),
        axios.get('/api/bank-accounts').catch(() => ({ data: { data: [] } })),
      ]);
      const raw = loansRes.data.data || [];
      const now = new Date();
      setLoans(raw.map(l => ({
        ...l,
        is_overdue: l.status === 'approved' && l.due_date && new Date(l.due_date) < now,
      })));
      setBankAccounts(bankRes.data.data || []);
    } catch { toast.error('Failed to load loans'); }
    finally { setLoading(false); }
  }, []);

  useEffect(() => { load(); }, [load]);

  const loadStaffLoans = useCallback(async () => {
    setStaffLoading(true);
    try {
      const [slRes, empRes, bankRes] = await Promise.all([
        axios.get('/api/staff-loans'),
        axios.get('/api/employees').catch(() => ({ data: { data: [] } })),
        axios.get('/api/bank-accounts').catch(() => ({ data: { data: [] } })),
      ]);
      setStaffLoans(slRes.data.data || []);
      setEmployees(empRes.data.data || []);
      setBankAccounts(bankRes.data.data || []);
    } catch { toast.error('Failed to load staff loans'); }
    finally { setStaffLoading(false); }
  }, []);

  useEffect(() => {
    if (tab === 'staff_loans') loadStaffLoans();
  }, [tab, loadStaffLoans]);

  const openStaffDetail = async (loan) => {
    setSelectedStaffLoan(loan); setShowStaffDetail(true); setStaffDetailLoading(true);
    try {
      const res = await axios.get(`/api/staff-loans/${loan.id}/deductions`);
      setStaffDeductions(res.data.data || []);
    } catch { setStaffDeductions([]); }
    finally { setStaffDetailLoading(false); }
  };

  const submitStaffLoan = async (e) => {
    e.preventDefault(); setSaving(true);
    try {
      await axios.post('/api/staff-loans', staffForm);
      toast.success('Staff loan created — pending approval');
      setShowStaffModal(false);
      setStaffForm({ employee_id:'', amount:'', interest_rate:'0', term_months:'', purpose:'', deduction_type:'fixed', deduction_value:'', notes:'', payment_method:'cash', bank_account_id:'' });
      loadStaffLoans();
    } catch (err) { toast.error(err.response?.data?.message || 'Failed to create loan'); }
    finally { setSaving(false); }
  };

  const approveStaffLoan = async (loan) => {
    // open modal to choose payment method / bank account
    setSelectedStaffLoan(loan);
    setStaffApproveForm({ payment_method: loan.payment_method || 'cash', bank_account_id: loan.bank_account_id || '' });
    try {
      const res = await axios.get('/api/bank-accounts', { params: { company_id: loan.company_id } }).catch(() => ({ data: { data: [] } }));
      setBankAccounts(res.data.data || []);
    } catch (e) { setBankAccounts([]); }
    setShowStaffApproveModal(true);
  };

  const submitApproveStaffLoan = async () => {
    if (!selectedStaffLoan) return;
    if (staffApproveForm.payment_method === 'bank' && !staffApproveForm.bank_account_id) return toast.error('Select a bank account');
    if (!confirm('Confirm staff loan approval?')) return;
    try {
      await axios.post(`/api/staff-loans/${selectedStaffLoan.id}/approve`, staffApproveForm);
      toast.success('Staff loan approved — deduction schedule created');
      setShowStaffApproveModal(false); setSelectedStaffLoan(null);
      loadStaffLoans();
    } catch (e) {
      toast.error(e.response?.data?.message || 'Failed');
    }
  };

  const rejectStaffLoan = async (id) => {
    const reason = prompt('Reason for rejection:');
    if (!reason) return;
    try { await axios.post(`/api/staff-loans/${id}/reject`, { reason }); toast.success('Loan rejected'); loadStaffLoans(); }
    catch (e) { toast.error(e.response?.data?.message || 'Failed'); }
  };

  const markDeducted = async (deductionId) => {
    try {
      await axios.post(`/api/staff-loan-deductions/${deductionId}/mark-deducted`);
      toast.success('Deduction recorded');
      if (selectedStaffLoan) openStaffDetail(selectedStaffLoan);
    } catch (e) { toast.error(e.response?.data?.message || 'Failed'); }
  };

  const openDetail = async (loan) => {
    setSelectedLoan(loan); setShowDetail(true); setDetailLoading(true);
    try {
      const res = await axios.get(`/api/loans/${loan.id}/repayments`);
      setRepayments(res.data.data || []);
    } catch { setRepayments([]); }
    finally { setDetailLoading(false); }
  };

  const openRepay = async (loan) => {
    setSelectedLoan(loan);
    setRepayForm({ amount: '', payment_date: new Date().toISOString().split('T')[0], payment_method: 'bank_transfer', reference_number: '', notes: '' });
    setReceiptFile(null);
    setShowRepayModal(true);
    try {
      const [bankRes, superAdminBankRes] = await Promise.all([
        axios.get('/api/bank-accounts', { params: { company_id: loan.borrower_company_id } }).catch(() => ({ data: { data: [] } })),
        axios.get('/api/super-admin-bank-accounts/public-list').catch(() => ({ data: { data: [] } }))
      ]);
      setBankAccounts(bankRes.data.data || []);
      const sa = superAdminBankRes.data.data || [];
      setSuperAdminBankAccounts(sa);
      // default to primary holding account if borrower hasn't chosen one
      if (sa.length > 0) {
        const primary = sa.find(a => a.is_primary) || sa[0];
        setRepayForm(p => ({ ...p, super_admin_bank_account_id: primary.id }));
      }
    } catch (e) {
      setBankAccounts([]);
      setSuperAdminBankAccounts([]);
    }
  };

  const handleApprove = async (loanId) => {
    const loan = loans.find(l => l.id === loanId);
    if (!loan) return;
    setApproveModal(loan);
    setApproveForm({ payment_method: 'bank', bank_account_id: loan.bank_account_id || '', super_admin_bank_account_id: loan.super_admin_bank_account_id || '' });
    
    // Fetch bank accounts for the borrower company and Super Admin
    try {
      const [bankRes, superAdminBankRes] = await Promise.all([
        axios.get('/api/bank-accounts', { params: { company_id: loan.borrower_company_id } }),
        axios.get('/api/super-admin-bank-accounts/list').catch(() => ({ data: { data: [] } }))
      ]);
      setBankAccounts(bankRes.data.data || []);
      setSuperAdminBankAccounts(superAdminBankRes.data.data || []);
    } catch {
      setBankAccounts([]);
      setSuperAdminBankAccounts([]);
    }
  };

  const submitApprove = async () => {
    if (!approveModal) return;
    if (approveForm.payment_method === 'bank') {
      if (!approveForm.bank_account_id) return toast.error('Please select borrower bank account');
      if (!approveForm.super_admin_bank_account_id) return toast.error('Please select Super Admin bank account');
    }
    setSaving(true);
    try {
      await axios.post(`/api/loans/${approveModal.id}/approve`, approveForm);
      toast.success('Loan approved');
      setApproveModal(null);
      load();
    } catch (e) {
      toast.error(e.response?.data?.message || 'Failed');
    } finally {
      setSaving(false);
    }
  };

  const handleReject = async (loanId) => {
    const reason = prompt('Rejection reason:');
    if (!reason) return;
    try { await axios.post(`/api/loans/${loanId}/reject`, { reason }); toast.success('Loan rejected'); load(); }
    catch (e) { toast.error(e.response?.data?.message || 'Failed'); }
  };

  const submitRepayment = async (e) => {
    e.preventDefault(); setSaving(true);
    const fd = new FormData();
    Object.entries(repayForm).forEach(([k,v]) => { if (v) fd.append(k, v); });
    if (receiptFile) fd.append('receipt', receiptFile);
    try {
      await axios.post(`/api/loans/${selectedLoan.id}/repay`, fd, { headers: { 'Content-Type':'multipart/form-data' } });
      toast.success('Repayment submitted — pending lender confirmation');
      setShowRepayModal(false); setReceiptFile(null); load();
      if (showDetail) openDetail(selectedLoan);
    } catch (err) { toast.error(err.response?.data?.message || 'Failed'); }
    finally { setSaving(false); }
  };

  const confirmRepayment = async () => {
    if (!confirmModal) return; setSaving(true);
    const fd = new FormData();
    if (confirmReceiptFile) fd.append('receipt', confirmReceiptFile);
    // Super admin can select holding account during confirmation if not already set
    if (isSuperAdmin && confirmSuperAdminBankAccountId) fd.append('super_admin_bank_account_id', confirmSuperAdminBankAccountId);
    try {
      await axios.post(`/api/loan-repayments/${confirmModal.id}/confirm`, fd, { headers:{ 'Content-Type':'multipart/form-data' } });
      toast.success('Repayment confirmed — balance updated');
      setConfirmModal(null); setConfirmReceiptFile(null); setConfirmBankAccountId(''); setConfirmSuperAdminBankAccountId(''); load();
      if (showDetail && selectedLoan) openDetail(selectedLoan);
    } catch (err) { toast.error(err.response?.data?.message || 'Failed'); }
    finally { setSaving(false); }
  };

  const rejectRepayment = async (r) => {
    const reason = prompt('Reason for rejecting this repayment?');
    if (!reason) return;
    try {
      await axios.post(`/api/loan-repayments/${r.id}/reject`, { reason });
      toast.success('Repayment rejected');
      if (showDetail && selectedLoan) openDetail(selectedLoan);
    } catch (err) { toast.error(err.response?.data?.message || 'Failed'); }
  };

  const filtered = loans.filter(l => {
    if (tab === 'all') return true;
    if (tab === 'overdue') return l.is_overdue;
    return l.status === tab;
  });

  const TABS = [
    { id:'all',      label:'All Loans' },
    { id:'pending',  label:'Pending' },
    { id:'approved', label:'Active' },
    { id:'overdue',  label:'Overdue', danger:true },
    { id:'paid',     label:'Paid' },
    ...(canApprove ? [{ id:'pending_repayments', label:'Repayment Queue' }] : []),
    { id:'staff_loans', label:'Staff Loans' },
  ];

  return (
    <div className="min-h-screen p-4 md:p-6" style={{ background:'linear-gradient(135deg,#EFEBE9 0%,#f8faff 100%)' }}>

      {/* Header */}
      <div className="flex flex-wrap items-center justify-between gap-3 mb-6">
        <div>
          <h1 className="text-2xl font-black text-gray-900 flex items-center gap-2">
            <Wallet size={28} weight="duotone" className="text-primary-600"/> Loan Management
          </h1>
          <p className="text-sm text-gray-500 mt-0.5">
            {canApprove ? 'Review loan requests and confirm repayments' : 'View loan status - Request loans via Invoice page'}
          </p>
        </div>
        <div className="flex items-center gap-2">
          {canManageStaff && tab === 'staff_loans' && (
            <button onClick={() => { setShowStaffModal(true); if (employees.length === 0) loadStaffLoans(); }}
              className="flex items-center gap-2 px-5 py-2.5 text-white text-sm font-semibold rounded-xl shadow" style={{ background:'#C6A862' }}>
              <Plus size={16}/> New Staff Loan
            </button>
          )}
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 mb-5 bg-white rounded-2xl p-1 shadow-sm border border-gray-100 overflow-x-auto">
        {TABS.map(t => (
          <button key={t.id} onClick={() => setTab(t.id)}
            className={`px-4 py-2 rounded-xl text-sm font-semibold whitespace-nowrap transition-all ${tab===t.id?'text-white shadow':'text-gray-500 hover:text-gray-700'}`}
            style={tab===t.id ? { background: t.danger ? '#dc2626' : '#5D4037' } : {}}>
            {t.label}
            {t.id==='overdue' && loans.filter(l=>l.is_overdue).length>0 && (
              <span className="ml-1 text-xs bg-red-600 text-white px-1.5 py-0.5 rounded-full">{loans.filter(l=>l.is_overdue).length}</span>
            )}
          </button>
        ))}
      </div>

      {/* Repayment Queue */}
      {tab==='pending_repayments' && (
        <PendingRepaymentQueue loans={loans} user={user} isSuperAdmin={isSuperAdmin}
          onConfirm={r => {
            setConfirmModal(r);
            setConfirmReceiptFile(null);
            setConfirmBankAccountId('');
            setConfirmSuperAdminBankAccountId('');
            // Fetch bank accounts
            Promise.all([
              axios.get('/api/bank-accounts').catch(() => ({ data: { data: [] } })),
              axios.get('/api/super-admin-bank-accounts/list').catch(() => ({ data: { data: [] } }))
            ]).then(([bankRes, superAdminBankRes]) => {
              setBankAccounts(bankRes.data.data || []);
              setSuperAdminBankAccounts(superAdminBankRes.data.data || []);
            });
          }}
          onReject={rejectRepayment}/>
      )}

      {/* Staff Loan Approve Modal */}
      {showStaffApproveModal && selectedStaffLoan && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50" onClick={() => setShowStaffApproveModal(false)}>
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between p-4 border-b">
              <h3 className="text-lg font-bold">Approve Staff Loan — #{selectedStaffLoan.loan_number}</h3>
              <button onClick={() => setShowStaffApproveModal(false)} className="text-gray-500">Close</button>
            </div>
            <div className="p-4 space-y-4">
              <div>
                <label className="block text-xs font-semibold text-gray-600 mb-1">Payment Method</label>
                <select className="w-full px-3 py-2 border rounded-xl" value={staffApproveForm.payment_method}
                  onChange={e => setStaffApproveForm(s => ({ ...s, payment_method: e.target.value }))}>
                  <option value="cash">Cash (company cash balance)</option>
                  <option value="bank">Bank (select company bank account)</option>
                </select>
              </div>

              {staffApproveForm.payment_method === 'bank' && (
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Company Bank Account</label>
                  <select className="w-full px-3 py-2 border rounded-xl" value={staffApproveForm.bank_account_id}
                    onChange={e => setStaffApproveForm(s => ({ ...s, bank_account_id: e.target.value }))}>
                    <option value="">Select account</option>
                    {bankAccounts.map(b => (
                      <option key={b.id} value={b.id}>{b.bank_name} — {b.account_number} ({fmt(b.current_balance)})</option>
                    ))}
                  </select>
                </div>
              )}

              <div className="flex justify-end gap-2">
                <button onClick={() => setShowStaffApproveModal(false)} className="px-3 py-1.5 text-sm rounded-xl border">Cancel</button>
                <button onClick={submitApproveStaffLoan} className="px-3 py-1.5 text-sm rounded-xl bg-green-600 text-white">Approve</button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Loan Cards */}
      {tab!=='pending_repayments' && (
        loading ? (
          <div className="flex justify-center py-16"><div className="w-12 h-12 rounded-full border-4 border-t-transparent border-primary-600 animate-spin"/></div>
        ) : filtered.length===0 ? (
          <div className="text-center py-16 text-gray-400">
            <CurrencyDollar size={48} className="mx-auto mb-3 opacity-30"/>
            <p className="font-medium">No loans found</p>
          </div>
        ) : (
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
            {filtered.map(loan => (
              <LoanCard key={loan.id} loan={loan} canApprove={canApprove} user={user}
                onApprove={handleApprove} onReject={handleReject}
                onDetail={() => openDetail(loan)}
                onRepay={() => openRepay(loan)}/>
            ))}
          </div>
        )
      )}

      {/* Staff Loans View */}
      {tab === 'staff_loans' && (
        staffLoading ? (
          <div className="flex justify-center py-16"><div className="w-12 h-12 rounded-full border-4 border-t-transparent border-purple-600 animate-spin"/></div>
        ) : staffLoans.length === 0 ? (
          <div className="text-center py-16 text-gray-400">
            <UserCircle size={48} className="mx-auto mb-3 opacity-30"/>
            <p className="font-medium">No staff loans yet</p>
            {canManageStaff && <p className="text-sm mt-1">Click "New Staff Loan" to issue one</p>}
          </div>
        ) : (
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
            {staffLoans.map(sl => (
              <div key={sl.id} className="bg-white rounded-2xl shadow-sm border border-gray-100 p-5 hover:shadow-md transition-all">
                <div className="flex items-start justify-between mb-4">
                  <div className="flex items-center gap-3">
                    <div className="w-11 h-11 rounded-xl flex items-center justify-center text-white font-bold text-lg"
                      style={{ background:'linear-gradient(135deg,#C6A862,#a78bfa)' }}>
                      {(sl.employee?.first_name||'?').charAt(0)}
                    </div>
                    <div>
                      <p className="font-bold text-gray-900">{sl.employee?.first_name} {sl.employee?.last_name}</p>
                      <p className="text-xs text-gray-500">#{sl.loan_number} · {sl.employee?.position||''}</p>
                    </div>
                  </div>
                  <span className={`px-2.5 py-1 rounded-full text-xs font-bold border capitalize ${STATUS_STYLE[sl.status]||'bg-gray-100 text-gray-600 border-gray-200'}`}>
                    {sl.status}
                  </span>
                </div>
                <div className="grid grid-cols-2 gap-3 mb-4">
                  <div className="bg-purple-50 rounded-xl p-3"><p className="text-xs text-gray-500 mb-0.5">Principal</p><p className="font-black text-gray-900 text-sm">{fmt(sl.principal_amount)}</p></div>
                  <div className="bg-amber-50 rounded-xl p-3"><p className="text-xs text-gray-500 mb-0.5">Outstanding</p><p className="font-black text-gray-900 text-sm">{fmt(sl.outstanding_balance)}</p></div>
                  <div className="bg-primary-50 rounded-xl p-3"><p className="text-xs text-gray-500 mb-0.5">Term</p><p className="font-bold text-gray-900 text-sm">{sl.term_months} months</p></div>
                  <div className="bg-green-50 rounded-xl p-3">
                    <p className="text-xs text-gray-500 mb-0.5">Monthly Deduction</p>
                    <p className="font-bold text-gray-900 text-sm">
                      {sl.deduction_type === 'percentage' ? `${sl.deduction_value}% of salary` : fmt(sl.deduction_value)}
                    </p>
                  </div>
                </div>
                {sl.purpose && <p className="text-xs text-gray-500 bg-gray-50 rounded-xl px-3 py-2 mb-4 line-clamp-2">{sl.purpose}</p>}
                <div className="flex flex-wrap gap-2">
                  <button onClick={() => openStaffDetail(sl)}
                    className="flex items-center gap-1 px-3 py-1.5 text-xs font-semibold text-purple-600 bg-purple-50 hover:bg-purple-100 rounded-xl">
                    <Eye size={13}/> Schedule
                  </button>
                  {canManageStaff && sl.status === 'pending' && (
                    <>
                      <button onClick={() => approveStaffLoan(sl)}
                        className="flex items-center gap-1 px-3 py-1.5 text-xs font-semibold text-white bg-green-600 hover:bg-green-700 rounded-xl">
                        <CheckCircle size={13}/> Approve
                      </button>
                      <button onClick={() => rejectStaffLoan(sl.id)}
                        className="flex items-center gap-1 px-3 py-1.5 text-xs font-semibold text-white bg-red-600 hover:bg-red-700 rounded-xl">
                        <XCircle size={13}/> Reject
                      </button>
                    </>
                  )}
                </div>
              </div>
            ))}
          </div>
        )
      )}

      {/* Staff Loan Detail Modal */}
      {showStaffDetail && selectedStaffLoan && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50" onClick={() => setShowStaffDetail(false)}>
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-3xl max-h-[90vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between p-5 rounded-t-2xl" style={{ background:'linear-gradient(135deg,#C6A862,#a78bfa)' }}>
              <div>
                <h2 className="text-lg font-bold text-white">Deduction Schedule — #{selectedStaffLoan.loan_number}</h2>
                <p className="text-purple-200 text-xs">{selectedStaffLoan.employee?.first_name} {selectedStaffLoan.employee?.last_name} · {selectedStaffLoan.employee?.position}</p>
              </div>
              <button onClick={() => setShowStaffDetail(false)} className="text-white/70 hover:text-white"><X size={20}/></button>
            </div>
            <div className="p-5">
              <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-5">
                {[
                  { label:'Principal',    value:fmt(selectedStaffLoan.principal_amount) },
                  { label:'Outstanding',  value:fmt(selectedStaffLoan.outstanding_balance) },
                  { label:'Rate',         value:`${selectedStaffLoan.interest_rate}%` },
                  { label:'Deduction',    value: selectedStaffLoan.deduction_type==='percentage'
                      ? `${selectedStaffLoan.deduction_value}% / month`
                      : `${fmt(selectedStaffLoan.deduction_value)} / month` },
                ].map((item,i) => (
                  <div key={i} className="bg-gray-50 rounded-xl p-3 text-center">
                    <p className="text-xs text-gray-500 mb-0.5">{item.label}</p>
                    <p className="font-bold text-gray-900 text-sm">{item.value}</p>
                  </div>
                ))}
              </div>
              {staffDetailLoading ? (
                <div className="flex justify-center py-8"><div className="w-8 h-8 rounded-full border-4 border-t-transparent border-purple-600 animate-spin"/></div>
              ) : (
                <div className="border border-gray-100 rounded-xl overflow-x-auto">
                  <table className="w-full text-sm">
                    <thead className="bg-gray-50"><tr>
                      {['Month','Due Date','Amount','Principal','Interest','Status','Action'].map(h => (
                        <th key={h} className="px-3 py-2.5 text-left text-xs font-semibold text-gray-500">{h}</th>
                      ))}
                    </tr></thead>
                    <tbody className="divide-y divide-gray-50">
                      {staffDeductions.length === 0 && (
                        <tr><td colSpan={7} className="py-8 text-center text-gray-400">No deduction schedule generated yet</td></tr>
                      )}
                      {staffDeductions.map((d, i) => (
                        <tr key={d.id||i} className="hover:bg-gray-50">
                          <td className="px-3 py-2.5 font-medium text-gray-900">{d.month_number}</td>
                          <td className="px-3 py-2.5 text-gray-500 text-xs">{fmtD(d.due_date)}</td>
                          <td className="px-3 py-2.5 font-bold text-gray-900">{fmt(d.deduction_amount)}</td>
                          <td className="px-3 py-2.5 text-gray-500 text-xs">{fmt(d.principal_portion)}</td>
                          <td className="px-3 py-2.5 text-gray-500 text-xs">{fmt(d.interest_portion)}</td>
                          <td className="px-3 py-2.5">
                            <span className={`px-2 py-0.5 rounded-full text-xs font-bold border capitalize ${
                              d.status==='deducted' ? 'bg-green-100 text-green-700 border-green-200' :
                              d.status==='missed'   ? 'bg-red-100 text-red-700 border-red-200' :
                              'bg-gray-100 text-gray-600 border-gray-200'
                            }`}>{d.status}</span>
                          </td>
                          <td className="px-3 py-2.5">
                            {canManageStaff && d.status === 'scheduled' && selectedStaffLoan.status === 'approved' && (
                              <button onClick={() => markDeducted(d.id)}
                                className="px-2 py-1 text-xs bg-purple-600 text-white rounded-lg font-semibold hover:bg-purple-700">
                                Mark Deducted
                              </button>
                            )}
                            {d.status === 'deducted' && (
                              <span className="text-xs text-gray-400">{fmtD(d.deducted_on)}</span>
                            )}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* New Staff Loan Modal */}
      {showStaffModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50" onClick={() => setShowStaffModal(false)}>
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-xl max-h-[90vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between p-5 rounded-t-2xl" style={{ background:'linear-gradient(135deg,#C6A862,#a78bfa)' }}>
              <h2 className="text-lg font-bold text-white">Issue Staff Loan</h2>
              <button onClick={() => setShowStaffModal(false)} className="text-white/70 hover:text-white"><X size={20}/></button>
            </div>
            <form onSubmit={submitStaffLoan} className="p-5 grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="md:col-span-2">
                <SE label="Employee *" value={staffForm.employee_id} onChange={e => setStaffForm(p => ({...p, employee_id: e.target.value}))} required>
                  <option value="">— Select employee —</option>
                  {employees.map(emp => (
                    <option key={emp.id} value={emp.id}>{emp.first_name} {emp.last_name} · {emp.position}</option>
                  ))}
                </SE>
              </div>
              <FI label="Loan Amount (NGN) *" type="number" min="1" required placeholder="100000"
                value={staffForm.amount} onChange={e => setStaffForm(p => ({...p, amount: e.target.value}))}/>
              <FI label="Interest Rate (%) *" type="number" step="any" min="0" max="100" placeholder="0"
                value={staffForm.interest_rate} onChange={e => setStaffForm(p => ({...p, interest_rate: e.target.value}))}/>
              <FI label="Term (Months) *" type="number" min="1" max="120" required placeholder="12"
                value={staffForm.term_months} onChange={e => setStaffForm(p => ({...p, term_months: e.target.value}))}/>
              <SE label="Deduction Method *" value={staffForm.deduction_type} onChange={e => setStaffForm(p => ({...p, deduction_type: e.target.value}))}>
                <option value="fixed">Fixed Monthly Amount</option>
                <option value="percentage">Percentage of Salary</option>
              </SE>
              <div className="md:col-span-2">
                <FI label={staffForm.deduction_type === 'percentage' ? 'Deduction % of Salary *' : 'Fixed Monthly Deduction (NGN) *'}
                  type="number" step="any" min="0.01" required
                  placeholder={staffForm.deduction_type === 'percentage' ? 'e.g. 10 (10% of salary)' : 'e.g. 5000'}
                  value={staffForm.deduction_value} onChange={e => setStaffForm(p => ({...p, deduction_value: e.target.value}))}/>
                <p className="text-xs text-gray-400 mt-1">
                  {staffForm.deduction_type === 'percentage'
                    ? 'This percentage will be deducted from the employee gross salary each month.'
                    : 'This fixed amount will be deducted from the employee salary each month.'}
                </p>
              </div>
              <div className="md:col-span-2">
                <label className="block text-xs font-semibold text-gray-600 mb-1">Purpose *</label>
                <textarea rows={2} required className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:ring-2 outline-none resize-none"
                  style={{ '--tw-ring-color':'#C6A862' }}
                  placeholder="Reason for loan..." value={staffForm.purpose} onChange={e => setStaffForm(p => ({...p, purpose: e.target.value}))}/>
              </div>
              <div className="md:col-span-2">
                <label className="block text-xs font-semibold text-gray-600 mb-1">Notes</label>
                <textarea rows={2} className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm outline-none resize-none"
                  value={staffForm.notes} onChange={e => setStaffForm(p => ({...p, notes: e.target.value}))}/>
              </div>
              <div className="md:col-span-2">
                <SE label="Payment Method *" value={staffForm.payment_method} onChange={e => setStaffForm(p => ({...p, payment_method: e.target.value, bank_account_id: ''}))}>
                  <option value="cash">Cash</option>
                  <option value="bank">Bank Transfer</option>
                </SE>
              </div>
              {staffForm.payment_method === 'bank' && (
                <div className="md:col-span-2">
                  <SE label="Bank Account *" value={staffForm.bank_account_id} onChange={e => setStaffForm(p => ({...p, bank_account_id: e.target.value}))} required>
                    <option value="">— Select bank account —</option>
                    {bankAccounts.map(ba => (
                      <option key={ba.id} value={ba.id}>{ba.bank_name} - {ba.account_number} ({ba.account_name})</option>
                    ))}
                  </SE>
                </div>
              )}
              {staffForm.amount && staffForm.term_months && staffForm.interest_rate && (
                <div className="md:col-span-2 bg-purple-50 border border-purple-100 rounded-xl p-3 text-sm text-purple-800">
                  <p className="font-semibold mb-0.5">Smart Calculation</p>
                  <div className="space-y-1">
                    <p>Loan Amount: {fmt(staffForm.amount)}</p>
                    <p>Interest Rate: {staffForm.interest_rate}% per annum</p>
                    <p>Term: {staffForm.term_months} months</p>
                    
                    {/* Calculate total interest and repayment */}
                    {(() => {
                      const principal = Number(staffForm.amount) || 0;
                      const rate = Number(staffForm.interest_rate) || 0;
                      const months = Number(staffForm.term_months) || 1;
                      const totalInterest = principal * (rate / 100 / 12) * months;
                      const totalRepayable = principal + totalInterest;
                      const monthlyPayment = totalRepayable / months;
                      const monthlyPrincipal = principal / months;
                      const monthlyInterest = totalInterest / months;
                      
                      return (
                        <>
                          <p className="border-t border-purple-200 pt-1 mt-1">
                            <span className="font-semibold">Total Interest:</span> {fmt(totalInterest)}
                          </p>
                          <p>
                            <span className="font-semibold">Total Repayment:</span> {fmt(totalRepayable)}
                          </p>
                          <p className="bg-purple-100 rounded p-2 mt-1">
                            <span className="font-semibold">Monthly Payment:</span> {fmt(monthlyPayment)}
                            <span className="text-xs block text-purple-700 mt-0.5">
                              (Principal: {fmt(monthlyPrincipal)} + Interest: {fmt(monthlyInterest)})
                            </span>
                          </p>
                          <p className="text-xs text-purple-600 mt-1">
                            Deduction Method: {staffForm.deduction_type === 'percentage'
                              ? `${staffForm.deduction_value}% of gross salary`
                              : fmt(staffForm.deduction_value || 0)}
                          </p>
                        </>
                      );
                    })()}
                  </div>
                </div>
              )}
              <div className="md:col-span-2 flex justify-end gap-2 pt-2">
                <button type="button" onClick={() => setShowStaffModal(false)} className="px-4 py-2 bg-gray-100 text-gray-700 rounded-xl text-sm">Cancel</button>
                <button type="submit" disabled={saving} className="px-5 py-2 text-white rounded-xl text-sm font-semibold"
                  style={{ background:'linear-gradient(135deg,#C6A862,#a78bfa)' }}>
                  {saving ? 'Creating…' : 'Issue Loan'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}


      {/* Approve Loan Modal */}
      {approveModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50" onClick={()=>setApproveModal(null)}>
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg" onClick={e=>e.stopPropagation()}>
            <div className="flex items-center justify-between p-5 rounded-t-2xl" style={{ background:'#5D4037' }}>
              <div>
                <h2 className="text-lg font-bold text-white">Approve Loan Request</h2>
                <p className="text-primary-200 text-xs">{approveModal.loan_number} — {fmt(approveModal.principal_amount)}</p>
              </div>
              <button onClick={()=>setApproveModal(null)} className="text-white/70 hover:text-white"><X size={20}/></button>
            </div>
            <form onSubmit={e=>{e.preventDefault(); submitApprove();}} className="p-5 space-y-4">
              <div className="bg-primary-50 rounded-xl p-3 border border-primary-100">
                <p className="text-xs text-primary-700 font-semibold mb-0.5">Loan Amount</p>
                <p className="text-2xl font-black text-primary-700">{fmt(approveModal.principal_amount)}</p>
                <p className="text-xs text-primary-600 mt-1">Purpose: {approveModal.purpose}</p>
              </div>
              <div>
                <label className="block text-xs font-semibold text-gray-600 mb-1">Payment Method *</label>
                <select
                  className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-primary-500 outline-none bg-white"
                  value={approveForm.payment_method}
                  onChange={e=>setApproveForm({...approveForm,payment_method:e.target.value,bank_account_id:''})}
                >
                  <option value="bank">Bank Transfer</option>
                  <option value="cash">Cash</option>
                </select>
              </div>
              {approveForm.payment_method === 'bank' && (
                <>
                  <div>
                    <label className="block text-xs font-semibold text-gray-600 mb-1">Super Admin Bank Account (to debit from) *</label>
                    <select
                      className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-primary-500 outline-none bg-white"
                      value={approveForm.super_admin_bank_account_id}
                      onChange={e=>setApproveForm({...approveForm,super_admin_bank_account_id:e.target.value})}
                    >
                      <option value="">— Select Super Admin bank account —</option>
                      {superAdminBankAccounts.map(ba => (
                        <option key={ba.id} value={ba.id}>{ba.bank_name} - {ba.account_number} ({ba.account_name}) - Balance: ₦{Number(ba.current_balance).toLocaleString()}</option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label className="block text-xs font-semibold text-gray-600 mb-1">Borrower Bank Account (to deposit to) *</label>
                    <select
                      className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-primary-500 outline-none bg-white"
                      value={approveForm.bank_account_id}
                      onChange={e=>setApproveForm({...approveForm,bank_account_id:e.target.value})}
                    >
                      <option value="">— Select bank account —</option>
                      {bankAccounts.filter(ba => ba.company_id === approveModal.borrower_company_id).map(ba => (
                        <option key={ba.id} value={ba.id}>{ba.bank_name} - {ba.account_number} ({ba.account_name})</option>
                      ))}
                    </select>
                  </div>
                </>
              )}
              <div className="flex gap-2 pt-2">
                <button type="button" onClick={()=>setApproveModal(null)} className="flex-1 px-4 py-2 bg-gray-100 text-gray-700 rounded-xl text-sm font-medium">Cancel</button>
                <button type="submit" disabled={saving} className="flex-1 px-4 py-2 text-white rounded-xl text-sm font-semibold" style={{ background:'#5D4037' }}>
                  {saving ? 'Approving…' : 'Approve Loan'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Loan Detail Modal */}
      {showDetail && selectedLoan && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50" onClick={()=>setShowDetail(false)}>
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-3xl max-h-[90vh] overflow-y-auto" onClick={e=>e.stopPropagation()}>
            <div className="flex items-center justify-between p-5 rounded-t-2xl bg-primary-600">
              <div>
                <h2 className="text-lg font-bold text-white">Loan #{selectedLoan.loan_number}</h2>
                <p className="text-primary-200 text-xs">{selectedLoan.borrower?.name} → {selectedLoan.lender?.name}</p>
              </div>
              <button onClick={()=>setShowDetail(false)} className="text-white/70 hover:text-white"><X size={20}/></button>
            </div>
            <div className="p-5">
              <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-5">
                {[
                  {label:'Principal',    value:fmt(selectedLoan.principal_amount)},
                  {label:'Outstanding',  value:fmt(selectedLoan.outstanding_balance)},
                  {label:'Interest',     value:`${selectedLoan.interest_rate}%`},
                  {label:'Status',       value:selectedLoan.status},
                ].map((item,i)=>(
                  <div key={i} className="bg-gray-50 rounded-xl p-3 text-center">
                    <p className="text-xs text-gray-500 mb-0.5">{item.label}</p>
                    <p className="font-bold text-gray-900 capitalize text-sm">{item.value}</p>
                  </div>
                ))}
              </div>
              <h3 className="font-bold text-gray-800 mb-3 flex items-center gap-2">
                <FileText size={16} className="text-primary-600"/> Repayment History
              </h3>
              {detailLoading ? (
                <div className="flex justify-center py-8"><div className="w-8 h-8 rounded-full border-4 border-t-transparent border-primary-600 animate-spin"/></div>
              ) : (
                <div className="border border-gray-100 rounded-xl overflow-x-auto">
                  <table className="w-full text-sm">
                    <thead className="bg-gray-50"><tr>
                      {['#','Total','Principal','Interest','Date','Method','Status','Action'].map(h=>(
                        <th key={h} className="px-3 py-2.5 text-left text-xs font-semibold text-gray-500">{h}</th>
                      ))}
                    </tr></thead>
                    <tbody className="divide-y divide-gray-50">
                      {repayments.length===0&&<tr><td colSpan={8} className="py-8 text-center text-gray-400">No repayment records</td></tr>}
                      {repayments.map((r,i)=>(
                        <tr key={r.id||i} className="hover:bg-gray-50">
                          <td className="px-3 py-2.5 font-medium text-gray-900">{i+1}</td>
                          <td className="px-3 py-2.5 font-bold text-gray-900">{fmt(r.amount||r.total_amount)}</td>
                          <td className="px-3 py-2.5 text-green-700 font-semibold text-xs">{fmt(r.principal_portion||0)}</td>
                          <td className="px-3 py-2.5 text-orange-700 font-semibold text-xs">{fmt(r.interest_portion||0)}</td>
                          <td className="px-3 py-2.5 text-gray-500 text-xs">{fmtD(r.due_date||r.payment_date)}</td>
                          <td className="px-3 py-2.5 text-gray-500 capitalize text-xs">{(r.payment_method||'—').replace('_',' ')}</td>
                          <td className="px-3 py-2.5">
                            <span className={`px-2 py-0.5 rounded-full text-xs font-bold border capitalize ${STATUS_STYLE[r.status]||'bg-gray-100 text-gray-600 border-gray-200'}`}>
                              {(r.status||'').replace('_',' ')}
                            </span>
                          </td>
                          <td className="px-3 py-2.5">
                            {canApprove && r.status==='pending_confirmation' && (
                              <div className="flex gap-1">
                                <button onClick={()=>{setConfirmModal(r);setConfirmReceiptFile(null);}}
                                  className="px-2 py-1 text-xs bg-green-600 text-white rounded-lg font-semibold">Confirm</button>
                                <button onClick={()=>rejectRepayment(r)}
                                  className="px-2 py-1 text-xs bg-red-100 text-red-700 rounded-lg font-semibold">Reject</button>
                              </div>
                            )}
                            {r.receipt_path && (
                              <a href={`/storage/${r.receipt_path}`} target="_blank" rel="noreferrer"
                                className="text-xs text-primary-600 underline flex items-center gap-1">
                                <FileText size={11}/> Receipt
                              </a>
                            )}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Confirm Repayment Modal */}
      {confirmModal && (
        <div className="fixed inset-0 z-[60] flex items-center justify-center p-4 bg-black/60" onClick={()=>setConfirmModal(null)}>
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md" onClick={e=>e.stopPropagation()}>
            <div className="flex items-center justify-between p-5 border-b">
              <h3 className="font-bold text-gray-900">Confirm Repayment Receipt</h3>
              <button onClick={()=>setConfirmModal(null)} className="p-1 hover:bg-gray-100 rounded-lg"><X size={18}/></button>
            </div>
            <div className="p-5 space-y-4">
              <div className="bg-green-50 rounded-xl p-3">
                <p className="text-xs text-gray-500 mb-0.5">Amount being confirmed</p>
                <p className="text-2xl font-black text-green-700">{fmt(confirmModal.total_amount || confirmModal.amount)}</p>
                <p className="text-xs text-gray-400">Ref: {confirmModal.reference_number||'N/A'} · {(confirmModal.payment_method||'').replace('_',' ')}</p>
              </div>
              {confirmModal.selected_holding_account ? (
                <div className="bg-gray-50 rounded-xl p-3">
                  <p className="text-xs text-gray-500 mb-1">Holding Account (selected by borrower)</p>
                  <p className="font-bold text-gray-900">{confirmModal.selected_holding_account.bank_name} - {confirmModal.selected_holding_account.account_number}</p>
                  <p className="text-xs text-gray-600">{confirmModal.selected_holding_account.account_name}</p>
                  <p className="text-xs text-gray-500 mt-1">This holding account was chosen by the borrower and cannot be changed during confirmation.</p>
                </div>
              ) : isSuperAdmin ? (
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Select Holding Account to Credit * <span className="text-red-500">(Required if not pre-selected)</span></label>
                  <select
                    value={confirmSuperAdminBankAccountId}
                    onChange={e=>setConfirmSuperAdminBankAccountId(e.target.value)}
                    className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-primary-500 outline-none bg-white"
                    required
                  >
                    <option value="">— Select which holding account receives this repayment —</option>
                    {superAdminBankAccounts.map(ba => (
                      <option key={ba.id} value={ba.id}>{ba.bank_name} - {ba.account_number} ({ba.account_name})</option>
                    ))}
                  </select>
                  <p className="text-xs text-gray-500 mt-1">The repayment amount will be credited to this holding account</p>
                </div>
              ) : null}
              <div>
                <label className="block text-xs font-semibold text-gray-600 mb-1">Upload Acknowledgment Receipt (optional)</label>
                <div className="border-2 border-dashed border-gray-200 rounded-xl p-4 text-center hover:border-green-400 transition-colors">
                  <input type="file" accept=".pdf,.jpg,.jpeg,.png" id="confirm-file" className="hidden" onChange={e=>setConfirmReceiptFile(e.target.files[0])}/>
                  <label htmlFor="confirm-file" className="cursor-pointer">
                    <Upload size={20} className="mx-auto text-gray-400 mb-1"/>
                    <p className="text-sm text-gray-600">{confirmReceiptFile ? confirmReceiptFile.name : 'Upload your receipt'}</p>
                  </label>
                </div>
              </div>
              <div className="flex gap-2 pt-1">
                <button onClick={()=>setConfirmModal(null)} className="flex-1 px-4 py-2 bg-gray-100 text-gray-700 rounded-xl text-sm font-medium">Cancel</button>
                <button onClick={confirmRepayment} disabled={saving} className="flex-1 px-4 py-2 text-white rounded-xl text-sm font-semibold bg-green-600 hover:bg-green-700">
                  {saving ? 'Confirming…' : 'Confirm & Update Balance'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function LoanCard({ loan, canApprove, user, onApprove, onReject, onDetail, onRepay }) {
  const isBorrower = loan.borrower_company_id === user?.company_id;
  const overdue    = loan.is_overdue;

  return (
    <div className={`bg-white rounded-2xl shadow-sm border p-5 hover:shadow-md transition-all ${overdue?'border-red-300':'border-gray-100'}`}>
      {overdue && (
        <div className="flex items-center gap-2 mb-3 px-3 py-2 bg-red-50 rounded-xl text-red-700 text-xs font-bold">
          <Warning size={14}/> OVERDUE — repayment past due date
        </div>
      )}
      <div className="flex items-start justify-between mb-4">
        <div className="flex items-center gap-3">
          <div className="w-11 h-11 rounded-xl bg-gradient-to-br from-primary-500 to-purple-600 flex items-center justify-center text-white font-bold text-lg">
            {(loan.borrower?.name||'?').charAt(0)}
          </div>
          <div>
            <p className="font-bold text-gray-900">{loan.borrower?.name||'Unknown'}</p>
            <p className="text-xs text-gray-500">#{loan.loan_number} · {fmtD(loan.created_at)}</p>
          </div>
        </div>
        <span className={`px-2.5 py-1 rounded-full text-xs font-bold border capitalize ${STATUS_STYLE[overdue?'overdue':loan.status]||'bg-gray-100 text-gray-600 border-gray-200'}`}>
          {overdue ? 'Overdue' : loan.status}
        </span>
      </div>
      <div className="grid grid-cols-2 gap-3 mb-4">
        <div className="bg-primary-50 rounded-xl p-3"><p className="text-xs text-gray-500 mb-0.5">Principal</p><p className="font-black text-gray-900 text-sm">{fmt(loan.principal_amount)}</p></div>
        <div className="bg-amber-50 rounded-xl p-3"><p className="text-xs text-gray-500 mb-0.5">Outstanding</p><p className="font-black text-gray-900 text-sm">{fmt(loan.outstanding_balance)}</p></div>
        <div className="bg-purple-50 rounded-xl p-3"><p className="text-xs text-gray-500 mb-0.5">Rate / Term</p><p className="font-black text-gray-900 text-sm">{loan.interest_rate}% · {loan.term_months}mo</p></div>
        <div className="bg-green-50 rounded-xl p-3"><p className="text-xs text-gray-500 mb-0.5">Lender</p><p className="font-bold text-gray-900 text-sm truncate">{loan.lender?.name || (loan.is_super_admin_lender ? 'Super Admin' : '—')}</p></div>
      </div>
      {loan.bank_account && (
        <div className="bg-cyan-50 rounded-xl p-3 mb-4">
          <p className="text-xs text-gray-500 mb-1">Selected Bank Account</p>
          <p className="font-bold text-gray-900 text-sm">{loan.bank_account.bank_name} - {loan.bank_account.account_number}</p>
          <p className="text-xs text-gray-600">{loan.bank_account.account_name}</p>
        </div>
      )}
      {loan.purpose && <p className="text-xs text-gray-500 bg-gray-50 rounded-xl px-3 py-2 mb-4 line-clamp-2">{loan.purpose}</p>}
      <div className="flex flex-wrap gap-2">
        <button onClick={onDetail} className="flex items-center gap-1 px-3 py-1.5 text-xs font-semibold text-primary-600 bg-primary-50 hover:bg-primary-100 rounded-xl">
          <Eye size={13}/> View
        </button>
        {canApprove && loan.status==='pending' && (
          <>
            <button onClick={()=>onApprove(loan.id)} className="flex items-center gap-1 px-3 py-1.5 text-xs font-semibold text-white bg-green-600 hover:bg-green-700 rounded-xl">
              <CheckCircle size={13}/> Approve
            </button>
            <button onClick={()=>onReject(loan.id)} className="flex items-center gap-1 px-3 py-1.5 text-xs font-semibold text-white bg-red-600 hover:bg-red-700 rounded-xl">
              <XCircle size={13}/> Reject
            </button>
          </>
        )}
      </div>
    </div>
  );
}

function PendingRepaymentQueue({ loans, user, isSuperAdmin, onConfirm, onReject }) {
  const [items, setItems]   = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetch = async () => {
      setLoading(true);
      const all = [];
      const relevant = loans.filter(l => isSuperAdmin || l.lender_company_id === user?.company_id);
      for (const loan of relevant) {
        try {
          const res = await axios.get(`/api/loans/${loan.id}/repayments`);
          (res.data.data||[]).filter(r=>r.status==='pending_confirmation').forEach(r=>all.push({...r,loan}));
        } catch {}
      }
      setItems(all); setLoading(false);
    };
    fetch();
  }, [loans]);

  if (loading) return <div className="flex justify-center py-16"><div className="w-10 h-10 rounded-full border-4 border-t-transparent border-primary-600 animate-spin"/></div>;

  if (items.length===0) return (
    <div className="text-center py-16 text-gray-400">
      <CheckCircle size={48} className="mx-auto mb-3 opacity-30"/>
      <p className="font-medium">No repayments awaiting confirmation</p>
    </div>
  );

  return (
    <div className="space-y-4">
      {items.map((r,i)=>(
        <div key={r.id||i} className="bg-white rounded-2xl shadow-sm border border-orange-200 p-5">
          <div className="flex flex-wrap items-start justify-between gap-3 mb-3">
            <div>
              <p className="font-bold text-gray-900">{r.loan?.borrower?.name}</p>
              <p className="text-xs text-gray-500">Loan #{r.loan?.loan_number} · Submitted {fmtD(r.created_at)}</p>
            </div>
            <span className="px-2.5 py-1 rounded-full text-xs font-bold bg-orange-100 text-orange-700 border border-orange-200">Awaiting Confirmation</span>
          </div>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-4">
            <div className="bg-gray-50 rounded-xl p-3"><p className="text-xs text-gray-400">Amount</p><p className="font-black text-gray-900">{fmt(r.amount)}</p></div>
            <div className="bg-gray-50 rounded-xl p-3"><p className="text-xs text-gray-400">Method</p><p className="font-bold text-sm capitalize">{(r.payment_method||'—').replace('_',' ')}</p></div>
            <div className="bg-gray-50 rounded-xl p-3"><p className="text-xs text-gray-400">Reference</p><p className="font-bold text-sm">{r.reference_number||'—'}</p></div>
            <div className="bg-gray-50 rounded-xl p-3"><p className="text-xs text-gray-400">Date</p><p className="font-bold text-sm">{fmtD(r.due_date)}</p></div>
          </div>
          {r.notes && <p className="text-xs text-gray-500 bg-gray-50 rounded-xl px-3 py-2 mb-3">{r.notes}</p>}
          {r.receipt_path && (
            <a href={`/storage/${r.receipt_path}`} target="_blank" rel="noreferrer"
              className="text-xs text-primary-600 underline flex items-center gap-1 mb-3"><FileText size={12}/> View borrower receipt</a>
          )}
          <div className="flex gap-2">
            <button onClick={()=>onConfirm(r)} className="flex items-center gap-1 px-4 py-2 text-sm font-semibold text-white bg-green-600 hover:bg-green-700 rounded-xl">
              <CheckCircle size={15}/> Confirm Receipt
            </button>
            <button onClick={()=>onReject(r)} className="flex items-center gap-1 px-4 py-2 text-sm font-semibold text-red-700 bg-red-50 hover:bg-red-100 rounded-xl">
              <XCircle size={15}/> Reject
            </button>
          </div>
        </div>
      ))}
    </div>
  );
}
