import React, { useState, useEffect } from 'react';
import { FileText, Plus, MagnifyingGlass, ArrowUp, ArrowDown,
  CheckCircle, Clock, Warning, X, Eye, Trash, CurrencyDollar } from '@phosphor-icons/react';
import axios from 'axios';
import toast from 'react-hot-toast';
import useAuthStore from '../store/authStore';

const BRAND = '#5D4037';

const STATUS_STYLES = {
  paid:      'bg-green-100 text-green-700 border-green-200',
  sent:      'bg-primary-100 text-primary-700 border-primary-200',
  viewed:    'bg-purple-100 text-purple-700 border-purple-200',
  partial:   'bg-cyan-100 text-cyan-700 border-cyan-200',
  overdue:   'bg-red-100 text-red-700 border-red-200',
  draft:     'bg-gray-100 text-gray-600 border-gray-200',
  cancelled: 'bg-gray-100 text-gray-400 border-gray-200',
};

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

const EMPTY_FORM = {
  type: 'receivable', client_name: '', client_email: '', client_address: '',
  invoice_date: new Date().toISOString().slice(0,10),
  due_date: '', bank_account_id: '', payment_method: 'bank', cash_amount: '', notes: '', terms: '', tax_rate: 0, discount: 0,
  is_profit_allocation_payment: false, allocation_month: '', is_loan_request: false, is_loan_repayment: false, loan_id: '',
  loan_amount: '', loan_interest_rate: '', loan_term_months: '', loan_purpose: '', loan_repayment_schedule: 'monthly',
  company_id: '',
};
const EMPTY_ITEM = { description: '', quantity: 1, unit_price: '' };

export default function Invoices() {
  const { isSuperAdmin } = useAuthStore();
  const [invoices, setInvoices] = useState([]);
  const [loading, setLoading]   = useState(true);
  const [search, setSearch]     = useState('');
  const [filter, setFilter]     = useState('all');
  const [selected, setSelected] = useState(null);
  const [showCreate, setShowCreate] = useState(false);
  const [saving, setSaving]     = useState(false);
  const [form, setForm]         = useState(EMPTY_FORM);
  const [items, setItems]       = useState([{ ...EMPTY_ITEM }]);
  const [bankAccounts, setBankAccounts] = useState([]);
  const [superAdminBankAccounts, setSuperAdminBankAccounts] = useState([]);
  const [companies, setCompanies] = useState([]);
  const [companyFilter, setCompanyFilter] = useState('');
  const [createdByFilter, setCreatedByFilter] = useState('');
  const [availableMonths, setAvailableMonths] = useState([]);
  const [loans, setLoans] = useState([]);
  const [profitSweepRules, setProfitSweepRules] = useState([]);

  const fetchInvoices = () => {
    setLoading(true);
  const { user } = useAuthStore.getState();
  // Use the store helper to determine Super Admin status (user.roles is populated)
  const isSuperAdmin = useAuthStore.getState().isSuperAdmin();
    let bankAccountRequests = [
      // Company bank accounts for the logged-in user (may be empty for super admin)
      axios.get('/api/bank-accounts/list').catch(() => ({ data: { data: [] } })),
      // Super admin holding accounts - public list so companies can choose which holding account to credit
      axios.get('/api/super-admin-bank-accounts/public-list').catch(() => ({ data: { data: [] } })),
    ];
    // Build invoices URL with optional company filter
    let invoicesUrl = companyFilter ? `/api/invoices?company_id=${companyFilter}` : '/api/invoices';
    if (createdByFilter === 'me') {
      invoicesUrl += (invoicesUrl.includes('?') ? '&' : '?') + 'created_by=me';
    }

    Promise.all([
      axios.get(invoicesUrl),
      ...bankAccountRequests,
      axios.get('/api/profit-sweeps/available-months').catch(() => ({ data: { data: [] } })),
      axios.get('/api/loans').catch(() => ({ data: { data: [] } })),
      axios.get('/api/profit-sweep-rules').catch(() => ({ data: { data: [] } })),
    ])
      .then((responses) => {
        const invRes = responses[0];
        const monthsRes = responses[responses.length - 3];
        const loansRes = responses[responses.length - 2];
        const rulesRes = responses[responses.length - 1];
        const bankResponses = responses.slice(1, responses.length - 3);
        // bankResponses[0] -> company bank accounts
        // bankResponses[1] -> super admin holding accounts
        
        setInvoices(invRes.data.data || []);
        setAvailableMonths(monthsRes.data.data || []);
        setLoans(loansRes.data.data || []);
        setProfitSweepRules(rulesRes.data.data || []);
        // If super admin, fetch companies for filtering/creation
        if (isSuperAdmin) {
          axios.get('/api/companies?per_page=1000')
            .then(r => setCompanies((r.data && r.data.data) ? r.data.data : []))
            .catch(() => setCompanies([]));
        }
        
        // Handle bank accounts based on user role
        console.log('Processing bank account responses:', bankResponses);
        
        const companyBankRes = bankResponses[0] || { data: { data: [] } };
        const superAdminBankRes = bankResponses[1] || { data: { data: [] } };

        // Company users: show their company bank accounts for payer selection
        const companyAccounts = companyBankRes.data.data || [];
        const companyAccountsWithDisplay = companyAccounts.map(acc => ({ ...acc, account_type: 'company', display_name: `${acc.account_name} - ${acc.bank_name} (${acc.account_number})` }));
        setBankAccounts(companyAccountsWithDisplay);

        // Always set available super-admin holding accounts so companies can choose target account when repaying
        const superAdminAccounts = superAdminBankRes.data.data || [];
        const superAdminWithDisplay = superAdminAccounts.map(acc => ({ ...acc, account_type: 'super_admin', display_name: `${acc.account_name} - ${acc.bank_name} (${acc.account_number})` }));
        setSuperAdminBankAccounts(superAdminWithDisplay);
      })
      .catch(() => toast.error('Failed to load invoices'))
      .finally(() => setLoading(false));
  };

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

  // Re-fetch invoices when filters change
  useEffect(() => {
    // Debounce slightly if needed in future; for now, immediate fetch
    fetchInvoices();
  }, [companyFilter, createdByFilter]);

  // Item calculations
  const subtotal  = items.reduce((s,i) => s + ((+i.quantity||0) * (+i.unit_price||0)), 0);
  const taxAmt    = subtotal * ((+form.tax_rate||0) / 100);
  const total     = subtotal + taxAmt - (+form.discount||0);

  const addItem    = () => setItems(p => [...p, { ...EMPTY_ITEM }]);
  const removeItem = i => setItems(p => p.filter((_,idx) => idx !== i));
  const setItem    = (i, k, v) => setItems(p => p.map((it,idx) => idx===i ? {...it, [k]:v} : it));

  const handleCreate = async e => {
    e.preventDefault();
    if (items.some(i => !i.description || !i.unit_price)) {
      return toast.error('All line items need a description and price');
    }
    // Round unit prices to handle floating point precision
    const roundedItems = items.map(i => ({
      ...i,
      unit_price: parseFloat((parseFloat(i.unit_price) || 0).toFixed(2))
    }));
    setSaving(true);
    try {
  if (form.is_loan_repayment) {
        // Validation: Ensure company bank account is selected
        if (!form.bank_account_id) {
          setSaving(false);
          return toast.error('Please select your company bank account to debit for this repayment');
        }
        // Validation: Ensure holding account is selected
        if (!form.super_admin_bank_account_id) {
          setSaving(false);
          return toast.error('Please select the holding company account that will receive this repayment');
        }
        // Submit loan repayment
        const fd = new FormData();
        fd.append('amount', form.loan_amount);
        fd.append('payment_date', form.invoice_date);
        fd.append('payment_method', form.payment_method);
        fd.append('reference_number', form.invoice_date);
        fd.append('notes', 'Loan repayment via invoice');
        fd.append('bank_account_id', form.bank_account_id);
        fd.append('super_admin_bank_account_id', form.super_admin_bank_account_id);
        await axios.post(`/api/loans/${form.loan_id}/repay`, fd, { headers: { 'Content-Type':'multipart/form-data' } });
        toast.success('Loan repayment submitted - pending confirmation');
      } else {
        // Create invoice (including loan requests - backend will handle loan creation)
        // Client-side validation: if creating a loan request with bank payment, require bank account
        if (form.is_loan_request && form.payment_method === 'bank' && !form.bank_account_id) {
          return toast.error('Please select the bank account that will receive the loan disbursement');
        }
        const payload = { ...form, items: roundedItems };
        // If Super Admin and they selected a holding account, mark invoice as paid immediately
        if (isSuperAdmin() && form.super_admin_bank_account_id) {
          payload.status = 'paid';
        }
        const res = await axios.post('/api/invoices', payload);
        const created = res.data?.data || null;
        toast.success(form.is_loan_request ? 'Loan request invoice created' : 'Invoice created');
        // Insert created invoice into the current list so the user sees it immediately
        if (created) {
          setInvoices(prev => [created, ...prev.filter(i => i.id !== created.id)]);
        }
      }
      setShowCreate(false);
      setForm(EMPTY_FORM);
      setItems([{ ...EMPTY_ITEM }]);
      fetchInvoices();
    } catch (err) {
      toast.error(err.response?.data?.message || 'Failed to create invoice');
    } finally { setSaving(false); }
  };

  const markPaid = async inv => {
    try {
      await axios.post(`/api/invoices/${inv.id}/mark-paid`);
      toast.success('Invoice marked as paid');
      setSelected(null);
      fetchInvoices();
    } catch { toast.error('Failed to update'); }
  };

  const updateStatus = async (inv, status) => {
    try {
      await axios.patch(`/api/invoices/${inv.id}/status`, { status });
      toast.success('Status updated');
      setSelected(null);
      fetchInvoices();
    } catch { toast.error('Failed to update'); }
  };

  const filtered = invoices.filter(inv => {
    const s = (inv.invoice_number + ' ' + (inv.client_name||'')).toLowerCase();
    const matchSearch = s.includes(search.toLowerCase());
    const matchFilter = filter === 'all' || inv.status === filter || inv.type === filter;
    return matchSearch && matchFilter;
  });

  const totalReceivable = invoices.filter(i=>i.type==='receivable').reduce((s,i)=>s+(+i.total_amount||0),0);
  const totalPayable    = invoices.filter(i=>i.type==='payable').reduce((s,i)=>s+(+i.total_amount||0),0);
  const totalPaid       = invoices.filter(i=>i.status==='paid').reduce((s,i)=>s+(+i.total_amount||0),0);
  const totalOverdue    = invoices.filter(i=>i.status==='overdue').reduce((s,i)=>s+(+i.total_amount||0),0);

  return (
    <div className="space-y-6 fade-in">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-extrabold text-gray-900 flex items-center gap-3">
            <FileText size={30} weight="duotone" style={{ color: BRAND }} />
            Invoices
          </h1>
          <p className="text-sm text-gray-500 mt-0.5">
            {isSuperAdmin() ? 'Manage holding company receivables and payables' : 'Manage receivables, payables and billing'}
          </p>
        </div>
        <button onClick={()=>setShowCreate(true)}
          className="flex items-center gap-2 px-5 py-2.5 rounded-xl text-white font-semibold shadow-lg transition-all hover:scale-105 text-sm"
          style={{ background:'linear-gradient(135deg,#5D4037,#6D4C41)' }}>
          <Plus size={18} weight="bold" /> New Invoice
        </button>
      </div>

      {/* KPIs */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {[
          { label:'Total Receivable', value: totalReceivable, icon: ArrowUp,    color: BRAND,      bg:'#EFEBE9' },
          { label:'Total Payable',    value: totalPayable,    icon: ArrowDown,   color:'#dc2626',   bg:'#fee2e2' },
          { label:'Total Paid',       value: totalPaid,       icon: CheckCircle, color:'#16a34a',   bg:'#dcfce7' },
          { label:'Overdue',          value: totalOverdue,    icon: Warning,     color:'#d97706',   bg:'#fef3c7' },
        ].map((k,i) => (
          <div key={i} className="kpi-card">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1">{k.label}</p>
                <p className="text-xl font-extrabold text-gray-900">{fmt(k.value)}</p>
              </div>
              <div className="w-10 h-10 rounded-xl flex items-center justify-center" style={{ background: k.bg }}>
                <k.icon size={22} weight="duotone" style={{ color: k.color }} />
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Filters */}
      <div className="glass rounded-2xl p-4 flex flex-wrap gap-3 items-center">
        <div className="relative flex-1 min-w-[200px]">
          <MagnifyingGlass size={18} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
          <input value={search} onChange={e=>setSearch(e.target.value)} placeholder="Search invoices…"
            className="w-full pl-9 pr-4 py-2 bg-white border-2 border-gray-200 rounded-xl text-sm focus:border-primary-500 focus:outline-none" />
        </div>
        {isSuperAdmin() && (
          <>
            <div className="min-w-[220px]">
              <select value={companyFilter} onChange={e => { setCompanyFilter(e.target.value); fetchInvoices(); }}
                className="w-full py-2 px-3 border-2 border-gray-200 rounded-xl text-sm focus:border-primary-500 focus:outline-none">
                <option value="">All companies</option>
                {companies.map(c => (
                  <option key={c.id} value={c.id}>{c.name}</option>
                ))}
              </select>
            </div>
            <div className="min-w-[160px] flex items-center gap-2">
              <button onClick={() => { setCreatedByFilter('me'); fetchInvoices(); }}
                className={`px-3 py-2 rounded-xl text-sm font-semibold ${createdByFilter==='me' ? 'text-white bg-primary-600' : 'text-gray-700 bg-white'}`}>
                My invoices
              </button>
              <button onClick={() => { setCreatedByFilter(''); fetchInvoices(); }}
                className={`px-3 py-2 rounded-xl text-sm font-semibold ${createdByFilter==='' ? 'text-white bg-primary-600' : 'text-gray-700 bg-white'}`}>
                All
              </button>
            </div>
          </>
        )}
        {['all','receivable','payable','draft','sent','paid','overdue'].map(f => (
          <button key={f} onClick={()=>setFilter(f)}
            className={`px-4 py-2 rounded-xl text-sm font-semibold transition-all capitalize ${filter===f ? 'text-white shadow' : 'text-gray-600 bg-white hover:bg-gray-50'}`}
            style={filter===f ? { background:'linear-gradient(135deg,#5D4037,#6D4C41)' } : {}}>
            {f}
          </button>
        ))}
      </div>

      {/* Table */}
      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
        {loading ? (
          <div className="py-16 text-center text-gray-400 text-sm">Loading invoices…</div>
        ) : (
          <table className="w-full data-table">
            <thead>
              <tr>
                <th>Invoice #</th>
                <th>Client</th>
                <th>Type</th>
                <th>Amount</th>
                <th>Due Date</th>
                <th>Status</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(inv => (
                <tr key={inv.id}>
                  <td><span className="font-bold text-gray-900">{inv.invoice_number}</span></td>
                  <td>
                    <div className="flex items-center gap-2">
                      <div className="w-7 h-7 rounded-lg flex items-center justify-center text-white font-bold text-xs flex-shrink-0"
                        style={{ background:'linear-gradient(135deg,#5D4037,#6D4C41)' }}>
                        {(inv.client_name||'?')[0].toUpperCase()}
                      </div>
                      <span className="truncate max-w-[140px]">{inv.client_name}</span>
                    </div>
                  </td>
                  <td>
                    <span className={`px-2 py-0.5 rounded-lg text-xs font-bold capitalize ${inv.type==='receivable' ? 'bg-primary-100 text-primary-700' : 'bg-orange-100 text-orange-700'}`}>
                      {inv.type}
                    </span>
                  </td>
                  <td><span className="font-bold">{fmt(inv.total_amount)}</span></td>
                  <td className="text-gray-600 text-sm">{fmtDate(inv.due_date)}</td>
                  <td>
                    <span className={`px-2.5 py-0.5 rounded-lg text-xs font-bold border capitalize ${STATUS_STYLES[inv.status] || STATUS_STYLES.draft}`}>
                      {inv.status}
                    </span>
                  </td>
                  <td>
                        <button onClick={()=>setSelected(inv)}
                          className="p-1.5 rounded-lg hover:bg-primary-50 text-gray-400 hover:text-primary-600 transition-colors">
                          <Eye size={16} weight="duotone" />
                        </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
        {!loading && filtered.length === 0 && (
          <div className="py-16 text-center text-gray-400">
            <FileText size={40} weight="duotone" className="mx-auto mb-2 opacity-40" />
            <p className="text-sm">No invoices found</p>
          </div>
        )}
      </div>

      {/* ── Detail / View Modal ─────────────────────────────────────── */}
      {selected && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4" style={{ background:'rgba(0,0,0,0.55)' }}>
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between p-6 border-b rounded-t-2xl" style={{ background:'linear-gradient(135deg,#5D4037,#3E2723)' }}>
              <div>
                <h2 className="text-xl font-bold text-white">{selected.invoice_number}</h2>
                <p className="text-sm text-primary-200 mt-0.5">{selected.client_name}</p>
              </div>
              <button onClick={()=>setSelected(null)} className="text-white/60 hover:text-white p-1.5 rounded-lg hover:bg-white/10">
                <X size={20} />
              </button>
            </div>
            <div className="p-6 space-y-3">
              {[
                ['Type',         <span className={`px-2 py-0.5 rounded text-xs font-bold capitalize ${selected.type==='receivable' ? 'bg-primary-100 text-primary-700' : 'bg-orange-100 text-orange-700'}`}>{selected.type}</span>],
                ['Amount',       <span className="font-extrabold text-xl text-gray-900">{fmt(selected.total_amount)}</span>],
                ['Balance Due',  <span className="font-bold text-red-600">{fmt(selected.balance)}</span>],
                ['Invoice Date', fmtDate(selected.invoice_date)],
                ['Due Date',     fmtDate(selected.due_date)],
                ['Status',       <span className={`px-3 py-1 rounded-lg text-xs font-bold border capitalize ${STATUS_STYLES[selected.status] || STATUS_STYLES.draft}`}>{selected.status}</span>],
                ...(selected.notes ? [['Notes', selected.notes]] : []),
              ].map(([label, val], i) => (
                <div key={i} className="flex items-center justify-between py-2 border-b border-gray-50">
                  <span className="text-sm text-gray-500">{label}</span>
                  <span className="text-sm text-right max-w-xs">{val}</span>
                </div>
              ))}

              {/* Line Items */}
              {(selected.items||[]).length > 0 && (
                <div className="mt-4">
                  <p className="text-xs font-semibold text-gray-400 uppercase mb-2">Line Items</p>
                  <div className="space-y-1">
                    {selected.items.map((item,i) => (
                      <div key={i} className="flex justify-between text-sm py-1 border-b border-gray-50">
                        <span className="text-gray-700">{item.description} × {item.quantity}</span>
                        <span className="font-semibold">{fmt(item.total_price)}</span>
                      </div>
                    ))}
                  </div>
                  <div className="flex justify-between text-sm font-bold mt-2 pt-2 border-t">
                    <span>Total</span>
                    <span>{fmt(selected.total_amount)}</span>
                  </div>
                </div>
              )}

              {/* Action Buttons */}
              <div className="flex flex-wrap gap-2 pt-3">
                {/* Don't show Mark as Paid for loan requests or repayments - only Super Admin can confirm */}
                {/* Only allow marking as paid if the current user created this invoice (Super Admin) or if company user */}
                {(!['paid','cancelled'].includes(selected.status) && !selected.is_loan_request && !selected.is_loan_repayment) && (
                  ((isSuperAdmin() && selected.created_by === useAuthStore.getState().user?.id) || !isSuperAdmin()) ? (
                    <button onClick={()=>markPaid(selected)}
                      className="flex-1 py-2.5 rounded-xl text-white font-bold text-sm"
                      style={{ background:'linear-gradient(135deg,#16a34a,#15803d)' }}>
                      Mark as Paid
                    </button>
                  ) : (
                    <button disabled className="flex-1 py-2.5 rounded-xl text-white/40 font-bold text-sm bg-gray-100 cursor-not-allowed">Mark as Paid</button>
                  )
                )}
                {/* Don't show Mark as Sent for loan requests or repayments */}
                {selected.status === 'draft' && !selected.is_loan_request && !selected.is_loan_repayment && (
                  ((isSuperAdmin() && selected.created_by === useAuthStore.getState().user?.id) || !isSuperAdmin()) ? (
                    <button onClick={()=>updateStatus(selected,'sent')}
                      className="flex-1 py-2.5 rounded-xl font-bold text-sm border"
                      style={{ borderColor: BRAND, color: BRAND }}>
                      Mark as Sent
                    </button>
                  ) : (
                    <button disabled className="flex-1 py-2.5 rounded-xl font-bold text-sm border border-gray-200 text-gray-400 cursor-not-allowed">Mark as Sent</button>
                  )
                )}
                {!['cancelled','paid'].includes(selected.status) && (
                  ((isSuperAdmin() && selected.created_by === useAuthStore.getState().user?.id) || !isSuperAdmin()) ? (
                    <button onClick={()=>updateStatus(selected,'cancelled')}
                      className="px-4 py-2.5 rounded-xl font-bold text-sm bg-red-50 text-red-600 hover:bg-red-100">
                      Cancel
                    </button>
                  ) : (
                    <button disabled className="px-4 py-2.5 rounded-xl font-bold text-sm bg-gray-50 text-gray-400 cursor-not-allowed">Cancel</button>
                  )
                )}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* ── Create Invoice Modal ────────────────────────────────────── */}
      {showCreate && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4" style={{ background:'rgba(0,0,0,0.55)' }}>
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-2xl max-h-[92vh] overflow-y-auto">
            <div className="flex items-center justify-between px-6 py-4 border-b" style={{ background:'linear-gradient(135deg,#5D4037,#3E2723)' }}>
              <h2 className="text-lg font-bold text-white flex items-center gap-2">
                <FileText size={20} weight="duotone" /> New Invoice
              </h2>
              <button onClick={()=>setShowCreate(false)} className="text-white/60 hover:text-white p-1.5 rounded-lg hover:bg-white/10">
                <X size={20} />
              </button>
            </div>

            <form onSubmit={handleCreate} className="p-6 space-y-5">
              {/* Basic fields */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                {isSuperAdmin() && (
                  <div className="sm:col-span-2">
                    <label className="block text-xs font-semibold text-gray-600 mb-1">Company (target) *</label>
                    <select className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm bg-white focus:ring-2 focus:ring-primary-500 outline-none"
                      value={form.company_id || ''}
                      onChange={e=>setForm({...form,company_id:e.target.value})}>
                      <option value="">Select company (will default to holding company)</option>
                      {companies.map(c=> (
                        <option key={c.id} value={c.id}>{c.name}</option>
                      ))}
                    </select>
                  </div>
                )}
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Type *</label>
                  <select className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm bg-white focus:ring-2 focus:ring-primary-500 outline-none"
                    value={form.type} onChange={e=>setForm({...form,type:e.target.value})}>
                    <option value="receivable">Receivable (Money coming in)</option>
                    <option value="payable">Payable (Money going out)</option>
                  </select>
                </div>
                {!form.is_profit_allocation_payment && !form.is_loan_request && !form.is_loan_repayment && (
                  <div>
                    <label className="block text-xs font-semibold text-gray-600 mb-1">Client Name *</label>
                    <input required className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 outline-none"
                      placeholder="Client or company name"
                      value={form.client_name} onChange={e=>setForm({...form,client_name:e.target.value})} />
                  </div>
                )}
                {!form.is_profit_allocation_payment && !form.is_loan_request && !form.is_loan_repayment && (
                  <div>
                    <label className="block text-xs font-semibold text-gray-600 mb-1">Client Email</label>
                    <input type="email" className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 outline-none"
                      placeholder="client@example.com"
                      value={form.client_email} onChange={e=>setForm({...form,client_email:e.target.value})} />
                  </div>
                )}
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Invoice Date *</label>
                  <input required type="date" className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 outline-none"
                    value={form.invoice_date} onChange={e=>setForm({...form,invoice_date:e.target.value})} />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Due Date *</label>
                  <input required type="date" className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 outline-none"
                    value={form.due_date} onChange={e=>setForm({...form,due_date:e.target.value})} />
                </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-lg text-sm focus:ring-2 focus:ring-primary-500 outline-none bg-white"
                    value={form.payment_method} onChange={e=>setForm({...form,payment_method:e.target.value})}>
                    <option value="bank">Bank Transfer</option>
                    <option value="cash">Cash</option>
                    <option value="mixed">Mixed (Bank + Cash)</option>
                  </select>
                </div>
                {(form.payment_method === 'bank' || form.payment_method === 'mixed') && (
                  <div>
                    <label className="block text-xs font-semibold text-gray-600 mb-1">Bank Account</label>
                    {isSuperAdmin() ? (
                      // Super Admin selects which holding account should receive the funds
                      <select className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 outline-none bg-white"
                        value={form.super_admin_bank_account_id || ''}
                        onChange={e=>setForm({...form, super_admin_bank_account_id: e.target.value, bank_account_id: ''})}>
                        <option value="">Select holding account</option>
                        {superAdminBankAccounts.map(ba => (
                          <option key={ba.id} value={ba.id}>{ba.display_name}</option>
                        ))}
                      </select>
                    ) : (
                      // Company user selects their company bank account
                      <select className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 outline-none bg-white"
                        value={form.bank_account_id} onChange={e=>setForm({...form,bank_account_id:e.target.value, super_admin_bank_account_id: ''})}>
                        <option value="">Select bank account</option>
                        {bankAccounts.map(ba=>(
                          <option key={ba.id} value={ba.id}>
                            {ba.display_name || `${ba.account_name} - ${ba.bank_name} (${ba.account_number})`}
                          </option>
                        ))}
                      </select>
                    )}
                  </div>
                )}
                {(form.payment_method === 'cash' || form.payment_method === 'mixed') && (
                  <div>
                    <label className="block text-xs font-semibold text-gray-600 mb-1">Cash Amount</label>
                    <input type="number" min="0" step="0.01" className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 outline-none"
                      placeholder="0.00"
                      value={form.cash_amount} onChange={e=>setForm({...form,cash_amount:e.target.value})} />
                  </div>
                )}
                {!form.is_profit_allocation_payment && !form.is_loan_request && !form.is_loan_repayment && (
                  <div>
                    <label className="block text-xs font-semibold text-gray-600 mb-1">Client Address</label>
                    <input className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 outline-none"
                      placeholder="Street, City, State"
                      value={form.client_address} onChange={e=>setForm({...form,client_address:e.target.value})} />
                  </div>
                )}
              </div>

              {/* Line Items */}
              <div>
                <div className="flex items-center justify-between mb-2">
                  <label className="text-xs font-semibold text-gray-600 uppercase">Line Items *</label>
                  <button type="button" onClick={addItem}
                    className="text-xs font-semibold px-3 py-1 rounded-lg"
                    style={{ background:'#EFEBE9', color: BRAND }}>
                    + Add Item
                  </button>
                </div>
                <div className="border border-gray-200 rounded-xl overflow-hidden">
                  <table className="w-full text-sm">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="text-left px-3 py-2 text-xs text-gray-500 font-semibold">Description</th>
                        <th className="text-center px-3 py-2 text-xs text-gray-500 font-semibold w-20">Qty</th>
                        <th className="text-right px-3 py-2 text-xs text-gray-500 font-semibold w-28">Unit Price</th>
                        <th className="text-right px-3 py-2 text-xs text-gray-500 font-semibold w-28">Total</th>
                        <th className="w-8"></th>
                      </tr>
                    </thead>
                    <tbody>
                      {items.map((item,i) => (
                        <tr key={i} className="border-t border-gray-100">
                          <td className="px-3 py-2">
                            <input required className="w-full border-0 outline-none text-sm" placeholder="Description"
                              value={item.description} onChange={e=>setItem(i,'description',e.target.value)} />
                          </td>
                          <td className="px-3 py-2">
                            <input type="number" min="1" required className="w-full border-0 outline-none text-sm text-center"
                              value={item.quantity} onChange={e=>setItem(i,'quantity',e.target.value)} />
                          </td>
                          <td className="px-3 py-2">
                            <input type="number" min="0" step="0.01" required className="w-full border-0 outline-none text-sm text-right"
                              placeholder="0.00" value={item.unit_price} onChange={e=>setItem(i,'unit_price',e.target.value)} />
                          </td>
                          <td className="px-3 py-2 text-right font-semibold text-gray-800">
                            {fmt((+item.quantity||0) * (+item.unit_price||0))}
                          </td>
                          <td className="px-2 py-2">
                            {items.length > 1 && (
                              <button type="button" onClick={()=>removeItem(i)} className="text-red-400 hover:text-red-600">
                                <X size={14} />
                              </button>
                            )}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>

              {/* Totals row */}
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Tax Rate (%)</label>
                  <input type="number" min="0" max="100" step="0.1"
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 outline-none"
                    value={form.tax_rate} onChange={e=>setForm({...form,tax_rate:e.target.value})} />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Discount (₦)</label>
                  <input type="number" min="0" step="0.01"
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 outline-none"
                    value={form.discount} onChange={e=>setForm({...form,discount:e.target.value})} />
                </div>
                <div className="bg-gray-50 rounded-xl p-3 flex flex-col justify-center">
                  <div className="flex justify-between text-xs text-gray-500 mb-1">
                    <span>Subtotal</span><span>{fmt(subtotal)}</span>
                  </div>
                  {+form.tax_rate > 0 && <div className="flex justify-between text-xs text-gray-500 mb-1">
                    <span>Tax ({form.tax_rate}%)</span><span>{fmt(taxAmt)}</span>
                  </div>}
                  {+form.discount > 0 && <div className="flex justify-between text-xs text-gray-500 mb-1">
                    <span>Discount</span><span>-{fmt(form.discount)}</span>
                  </div>}
                  <div className="flex justify-between font-bold text-gray-900 border-t pt-1 mt-1">
                    <span>Total</span><span style={{ color: BRAND }}>{fmt(total)}</span>
                  </div>
                </div>
              </div>

              {/* Notes & Terms */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Notes</label>
                  <textarea rows={3} className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 outline-none resize-none"
                    placeholder="Additional notes…" value={form.notes} onChange={e=>setForm({...form,notes:e.target.value})} />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Payment Terms</label>
                  <textarea rows={3} className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 outline-none resize-none"
                    placeholder="e.g. Payment due within 30 days…" value={form.terms} onChange={e=>setForm({...form,terms:e.target.value})} />
                </div>
              </div>

              {/* Special Invoice Types - Only for Company Users */}
              {!isSuperAdmin() && (
                <div className="bg-primary-50 rounded-xl p-4 border border-primary-100">
                  <p className="text-xs font-semibold text-primary-800 mb-3 uppercase">Special Invoice Type (Optional)</p>
                  <div className="space-y-3">
                    <label className="flex items-center gap-2 text-sm font-semibold text-gray-700">
                      <input type="checkbox" id="profit_allocation"
                        checked={form.is_profit_allocation_payment}
                        onChange={e=>{
                          setForm({...form,is_profit_allocation_payment:e.target.checked,is_loan_request:false});
                          if (e.target.checked) {
                            // Auto-set type to payable for profit allocation (money going out)
                            setForm(prev=>({...prev,type:'payable'}));
                            // Auto-select first available month and populate amount
                            const firstMonth = availableMonths[0];
                            if (firstMonth) {
                              setForm(prev=>({...prev,allocation_month:firstMonth.year_month}));
                              const activeRule = profitSweepRules.find(r => r.is_active);
                              const percentage = activeRule ? (activeRule.sweep_percentage || 0) : 0;
                              const allocationAmount = percentage > 0 
                                ? firstMonth.available_profit * (percentage / 100)
                                : firstMonth.available_profit;
                              setItems([{ description: 'Profit Allocation Payment', quantity: 1, unit_price: allocationAmount }]);
                            }
                          } else {
                            setForm(prev=>({...prev,allocation_month:'',type:'receivable'}));
                            setItems([{ ...EMPTY_ITEM }]);
                          }
                        }}
                      />
                      Profit Allocation Payment
                    </label>
                    {form.is_profit_allocation_payment && (
                      <div className="ml-7 space-y-3">
                        <div>
                          <label className="block text-xs font-semibold text-gray-600 mb-1">Allocation Month</label>
                          <select
                            className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 outline-none bg-white"
                            value={form.allocation_month}
                            onChange={e=>{
                              setForm({...form,allocation_month:e.target.value});
                              const monthData = availableMonths.find(m => m.year_month === e.target.value);
                              if (monthData) {
                                // Apply profit sweep rule percentage
                                const activeRule = profitSweepRules.find(r => r.is_active);
                                const percentage = activeRule ? (activeRule.sweep_percentage || 0) : 0;
                                // If no active rule or percentage is 0, use full available profit
                                const allocationAmount = percentage > 0 
                                  ? monthData.available_profit * (percentage / 100)
                                  : monthData.available_profit;
                                setItems([{ description: 'Profit Allocation Payment', quantity: 1, unit_price: allocationAmount }]);
                              } else {
                                setItems([{ ...EMPTY_ITEM }]);
                              }
                            }}
                          >
                            <option value="">Select month</option>
                            {availableMonths.map(m => (
                              <option key={m.year_month} value={m.year_month}>
                                {m.month_name} - {m.has_sweep ? `Swept: ₦${Number(m.sweep_amount).toLocaleString()}` : `Available: ₦${Number(m.available_profit).toLocaleString()}`}
                              </option>
                            ))}
                          </select>
                        </div>
                        {form.allocation_month && (
                          <div className="bg-green-50 rounded-lg p-2 border border-green-200">
                            <p className="text-xs text-green-700">
                              Amount to pay: <span className="font-bold">₦{Number(items[0]?.unit_price || 0).toLocaleString()}</span>
                            </p>
                            {profitSweepRules.find(r => r.is_active) && (
                              <p className="text-xs text-green-600 mt-1">
                                Rule: {profitSweepRules.find(r => r.is_active)?.sweep_percentage}% of net profit
                              </p>
                            )}
                          </div>
                        )}
                      </div>
                    )}
                    <label className="flex items-center gap-2 text-sm font-semibold text-gray-700">
                      <input type="checkbox" id="loan_request"
                        checked={form.is_loan_request}
                        onChange={e=>{
                          setForm({...form,is_loan_request:e.target.checked,is_profit_allocation_payment:false,is_loan_repayment:false});
                          if (e.target.checked) {
                            setForm(prev=>({...prev,type:'receivable',client_name:'',client_email:'',client_address:''}));
                            setItems([{ description: 'Loan Request', quantity: 1, unit_price: form.loan_amount || 0 }]);
                          } else {
                            setForm(prev=>({...prev,loan_amount:'',loan_interest_rate:'',loan_term_months:'',loan_purpose:'',type:'receivable'}));
                            setItems([{ ...EMPTY_ITEM }]);
                          }
                        }}
                      />
                      Loan Request (Money IN)
                    </label>
                    {form.is_loan_request && (
                      <div className="ml-7 space-y-3">
                        <div className="grid grid-cols-2 gap-3">
                          <div>
                            <label className="block text-xs font-semibold text-gray-600 mb-1">Loan Amount</label>
                            <input type="number" className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 outline-none"
                              placeholder="₦0.00" value={form.loan_amount} onChange={e=>{
                                const newAmount = parseFloat(e.target.value) || 0;
                                const rate = parseFloat(form.loan_interest_rate) || 0;
                                const months = parseInt(form.loan_term_months) || 12;
                                
                                // Calculate total interest using simple interest (align with backend)
                                const monthlyRate = rate / 100 / 12;
                                const totalInterest = +(newAmount * monthlyRate * months).toFixed(2);
                                const totalAmount = +(newAmount + totalInterest).toFixed(2);
                                setForm({...form,loan_amount:e.target.value});
                                // For invoice line item, show principal only (invoice represents principal)
                                setItems([{ 
                                  description: `Loan Request - Principal: ₦${newAmount.toLocaleString()} (Interest ₦${totalInterest.toLocaleString()} applied to loan)`, 
                                  quantity: 1, 
                                  unit_price: newAmount 
                                }]);
                              }} />
                          </div>
                          <div>
                            <label className="block text-xs font-semibold text-gray-600 mb-1">Interest Rate (%)</label>
                            <input type="number" step="0.1" className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 outline-none"
                              placeholder="e.g. 10" value={form.loan_interest_rate} onChange={e=>{
                                const rate = parseFloat(e.target.value) || 0;
                                const amount = parseFloat(form.loan_amount) || 0;
                                const months = parseInt(form.loan_term_months) || 12;
                                
                                // Simple interest calculation
                                const monthlyRate2 = rate / 100 / 12;
                                const totalInterest2 = +(amount * monthlyRate2 * months).toFixed(2);
                                const totalAmount2 = +(amount + totalInterest2).toFixed(2);
                                setForm({...form,loan_interest_rate:e.target.value});
                                setItems([{ 
                                  description: `Loan Request - Principal: ₦${amount.toLocaleString()} (Interest ₦${totalInterest2.toLocaleString()} applied to loan)`, 
                                  quantity: 1, 
                                  unit_price: amount 
                                }]);
                              }} />
                          </div>
                          <div>
                            <label className="block text-xs font-semibold text-gray-600 mb-1">Term (Months)</label>
                            <input type="number" className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 outline-none"
                              placeholder="e.g. 12" value={form.loan_term_months} onChange={e=>{
                                const months = parseInt(e.target.value) || 12;
                                const amount = parseFloat(form.loan_amount) || 0;
                                const rate = parseFloat(form.loan_interest_rate) || 0;
                                
                                // Simple interest calculation
                                const monthlyRate3 = rate / 100 / 12;
                                const totalInterest3 = +(amount * monthlyRate3 * months).toFixed(2);
                                const totalAmount3 = +(amount + totalInterest3).toFixed(2);
                                setForm({...form,loan_term_months:e.target.value});
                                setItems([{ 
                                  description: `Loan Request - Principal: ₦${amount.toLocaleString()} (Interest ₦${totalInterest3.toLocaleString()} applied to loan)`, 
                                  quantity: 1, 
                                  unit_price: amount 
                                }]);
                              }} />
                          </div>
                          <div>
                            <label className="block text-xs font-semibold text-gray-600 mb-1">Repayment Schedule</label>
                            <select className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 outline-none bg-white"
                              value={form.loan_repayment_schedule} onChange={e=>setForm({...form,loan_repayment_schedule:e.target.value})}>
                              <option value="monthly">Monthly</option>
                              <option value="quarterly">Quarterly</option>
                              <option value="annually">Annually</option>
                            </select>
                          </div>
                        </div>
                        <div>
                          <label className="block text-xs font-semibold text-gray-600 mb-1">Purpose</label>
                          <textarea rows={2} className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 outline-none resize-none"
                            placeholder="Describe the purpose of this loan…" value={form.loan_purpose} onChange={e=>setForm({...form,loan_purpose:e.target.value})} />
                        </div>
                        {form.loan_amount && form.loan_interest_rate && form.loan_term_months && (() => {
                          const principal = Number(form.loan_amount);
                          const interest = principal * (form.loan_interest_rate / 100 / 12) * form.loan_term_months;
                          const total = principal + interest;
                          return (
                            <div className="bg-purple-50 rounded-lg p-3 border border-purple-200">
                              <p className="text-xs text-purple-700 font-semibold mb-1">Loan Summary</p>
                              <p className="text-xs text-purple-600">Principal: ₦{principal.toLocaleString()}</p>
                              <p className="text-xs text-purple-600">Interest: ₦{interest.toFixed(2).toLocaleString()}</p>
                              <p className="text-xs text-purple-600 font-bold">Total Repayable: ₦{total.toFixed(2).toLocaleString()}</p>
                            </div>
                          );
                        })()}
                      </div>
                    )}
                    <label className="flex items-center gap-2 text-sm font-semibold text-gray-700">
                      <input type="checkbox" id="loan_repayment"
                        checked={form.is_loan_repayment}
                        onChange={e=>{
                          setForm({...form,is_loan_repayment:e.target.checked,is_profit_allocation_payment:false,is_loan_request:false});
                          if (e.target.checked) {
                            setForm(prev=>({...prev,type:'payable',client_name:'',client_email:'',client_address:''}));
                            setItems([{ description: 'Loan Repayment', quantity: 1, unit_price: form.loan_amount || 0 }]);
                          } else {
                            setForm(prev=>({...prev,loan_amount:'',loan_id:'',type:'receivable'}));
                            setItems([{ ...EMPTY_ITEM }]);
                          }
                        }}
                      />
                      Loan Repayment (Money OUT)
                    </label>
                    {form.is_loan_repayment && (
                      <div className="ml-7 space-y-3">
                        <div>
                          <label className="block text-xs font-semibold text-gray-600 mb-1">Select Loan</label>
                          <select className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 outline-none bg-white"
                            value={form.loan_id || ''}
                            onChange={e=>{
                              setForm({...form,loan_id:e.target.value});
                              const loan = loans.find(l => String(l.id) === String(e.target.value));
                              if (loan) {
                                setForm(prev=>({...prev,loan_amount:loan.outstanding_balance || loan.amount}));
                                setItems([{ description: 'Loan Repayment', quantity: 1, unit_price: loan.outstanding_balance || loan.amount }]);
                              }
                            }}>
                            <option value="">Select loan to repay</option>
                            {loans.filter(l => l.status === 'approved').map(l => (
                              <option key={l.id} value={l.id}>
                                {l.loan_number} - ₦{Number(l.outstanding_balance || l.amount).toLocaleString()} outstanding
                              </option>
                            ))}
                          </select>
                        </div>
                        <div>
                          <label className="block text-xs font-semibold text-gray-600 mb-1">Repayment Amount</label>
                          <input type="number" className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 outline-none"
                            placeholder="₦0.00" value={form.loan_amount} onChange={e=>{
                              setForm({...form,loan_amount:e.target.value});
                              setItems([{ description: 'Loan Repayment', quantity: 1, unit_price: e.target.value }]);
                            }} />
                        </div>
                        {form.loan_id && (
                          <div className="bg-green-50 rounded-lg p-3 border border-green-200">
                            <p className="text-xs text-green-700 font-semibold mb-1">Repayment Details</p>
                            <p className="text-xs text-green-600">Amount: ₦{Number(form.loan_amount).toLocaleString()}</p>
                          </div>
                        )}
                        {/* Choose which holding account the repayment should credit */}
                        {form.is_loan_repayment && superAdminBankAccounts.length > 0 && (
                          <div>
                            <label className="block text-xs font-semibold text-gray-600 mb-1">Credit Holding Account * <span className="text-red-500">(Required)</span></label>
                            <select className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 outline-none bg-white"
                              value={form.super_admin_bank_account_id || ''}
                              onChange={e => setForm({...form, super_admin_bank_account_id: e.target.value})}
                              required={form.is_loan_repayment}>
                              <option value="">Select holding account to receive repayment</option>
                              {superAdminBankAccounts.map(ba => (
                                <option key={ba.id} value={ba.id}>{ba.display_name}</option>
                              ))}
                            </select>
                            <p className="text-xs text-gray-500 mt-1">Select which holding company account will receive this repayment</p>
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                </div>
              )}

              <div className="flex justify-end gap-3 pt-2 border-t">
                <button type="button" onClick={()=>setShowCreate(false)}
                  className="px-5 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-xl font-semibold text-sm">
                  Cancel
                </button>
                <button type="submit" disabled={saving}
                  className="px-6 py-2.5 text-white rounded-xl font-bold text-sm disabled:opacity-60"
                  style={{ background:'linear-gradient(135deg,#5D4037,#6D4C41)' }}>
                  {saving ? 'Creating…' : 'Create Invoice'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
