import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import {
  Buildings, Users, CurrencyDollar, TrendUp, ArrowUp, ArrowDown, Wallet, ShieldCheck,
  ChartLineUp, Plus, X, FileText, Bank, Receipt, UserPlus, Briefcase, Pencil, Trash, Upload, Clock
} from '@phosphor-icons/react';
import { AreaChart, Area, PieChart, Pie, Cell, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts';
import axios from 'axios';
import useAuthStore from '../store/authStore';
import toast from 'react-hot-toast';

const COLORS = ['#5D4037', '#16a34a', '#f59e0b', '#ef4444', '#8b5cf6', '#06b6d4'];

const TABS = [
  { id: 'overview', label: 'Overview', icon: Buildings },
  { id: 'employees', label: 'Employees', icon: Users },
  { id: 'departments', label: 'Departments', icon: Briefcase },
  { id: 'assets', label: 'Assets', icon: Bank },
  { id: 'loans', label: 'Loans', icon: CurrencyDollar },
  { id: 'expenses', label: 'Expenses', icon: Receipt },
  { id: 'financials', label: 'Financials', icon: ChartLineUp },
];

export default function CompanyAdminDashboard() {
  const [stats, setStats] = useState(null);
  const [loading, setLoading] = useState(true);
  const [tab, setTab] = useState('overview');
  const [submitting, setSubmitting] = useState(false);
  const { user } = useAuthStore();

  // Tab data
  const [employees, setEmployees] = useState([]);
  const [departments, setDepartments] = useState([]);
  const [assets, setAssets] = useState([]);
  const [loans, setLoans] = useState([]);
  const [expenses, setExpenses] = useState([]);

  // Modals
  const [showEmpModal, setShowEmpModal] = useState(false);
  const [empForm, setEmpForm] = useState({ name: '', email: '', phone: '', department_id: '', salary: '', position: '', employment_type: 'full-time', status: 'active' });
  const [editingEmp, setEditingEmp] = useState(null);

  const [showDeptModal, setShowDeptModal] = useState(false);
  const [deptForm, setDeptForm] = useState({ name: '', description: '', manager_id: '' });
  const [editingDept, setEditingDept] = useState(null);

  const [showAssetModal, setShowAssetModal] = useState(false);
  const [assetForm, setAssetForm] = useState({ name: '', category: 'equipment', purchase_value: '', current_value: '', purchase_date: '', vendor_name: '', location: '', notes: '' });
  const [editingAsset, setEditingAsset] = useState(null);
  const [receiptFile, setReceiptFile] = useState(null);

  const [showLoanRequest, setShowLoanRequest] = useState(false);
  const [loanForm, setLoanForm] = useState({ amount: '', interest_rate: '8', term_months: '12', purpose: '', repayment_schedule: 'monthly', interest_type: 'simple', payment_method: 'bank', bank_account_id: '' });
  const [bankAccounts, setBankAccounts] = useState([]);

  const [showRepayModal, setShowRepayModal] = useState(false);
  const [selectedLoan, setSelectedLoan] = useState(null);
  const [repayAmount, setRepayAmount] = useState('');
  const [superAdminBankAccounts, setSuperAdminBankAccounts] = useState([]);
  const [repayForm, setRepayForm] = useState({
    amount: '', payment_date: new Date().toISOString().split('T')[0],
    payment_method: 'bank_transfer', reference_number: '', notes: '', super_admin_bank_account_id: '', bank_account_id: ''
  });

  const [showLogModal, setShowLogModal] = useState(false);
  const [logForm, setLogForm] = useState({ employee_id: '', log_type: 'salary_increase', amount_change: '', effective_date: '', end_date: '', description: '', notes: '' });

  const [showExpenseModal, setShowExpenseModal] = useState(false);
  const [expenseForm, setExpenseForm] = useState({ title: '', amount: '', category: '', expense_date: '', description: '', vendor_name: '' });

  const [showFinancialModal, setShowFinancialModal] = useState(false);
  const [financialForm, setFinancialForm] = useState({ revenue: '', cash_balance: '', total_assets: '', total_liabilities: '', expenses_manual: '', runway_days: '', credit_score: '' });

  useEffect(() => { fetchDashboardData(); }, []);
  useEffect(() => { if (tab !== 'overview') fetchTabData(); }, [tab]);

  const fetchDashboardData = async () => {
    try {
      setLoading(true);
      const dashRes = await axios.get('/api/dashboard/company');
      setStats({ ...dashRes.data });
    } catch {
      toast.error('Failed to load company dashboard');
      setStats({});
    } finally {
      setLoading(false);
    }
  };

  const fetchTabData = async () => {
    try {
      // Always fetch bank accounts for loan requests
      const bankRes = await axios.get('/api/bank-accounts');
      setBankAccounts(bankRes.data.data || []);
      
      // Always fetch super admin bank accounts for repayments
      const superAdminBankRes = await axios.get('/api/super-admin-bank-accounts/list');
      setSuperAdminBankAccounts(superAdminBankRes.data.data || []);
      
      if (tab === 'employees') {
        const res = await axios.get('/api/employees');
        setEmployees(res.data.data || []);
      }
      if (tab === 'departments') {
        const res = await axios.get('/api/departments');
        setDepartments(res.data.data || []);
      }
      if (tab === 'assets') {
        const res = await axios.get('/api/company-assets');
        setAssets(res.data.data || []);
      }
      if (tab === 'loans') {
        const res = await axios.get('/api/loans');
        setLoans(res.data.data || []);
      }
      if (tab === 'expenses') {
        const res = await axios.get('/api/expenses');
        setExpenses(res.data.data || []);
      }
    } catch {
      toast.error('Failed to load tab data');
    }
  };

  const submitEmployee = async (e) => {
    e.preventDefault(); setSubmitting(true);
    try {
      if (editingEmp) await axios.put(`/api/employees/${editingEmp.id}`, empForm);
      else await axios.post('/api/employees', empForm);
      toast.success(editingEmp ? 'Employee updated' : 'Employee added');
      setShowEmpModal(false); setEditingEmp(null); setEmpForm({ name: '', email: '', phone: '', department_id: '', salary: '', position: '', employment_type: 'full-time', status: 'active' });
      fetchTabData();
    } catch (e) { toast.error(e.response?.data?.message || 'Failed'); }
    finally { setSubmitting(false); }
  };

  const submitDepartment = async (e) => {
    e.preventDefault(); setSubmitting(true);
    try {
      if (editingDept) await axios.put(`/api/departments/${editingDept.id}`, deptForm);
      else await axios.post('/api/departments', deptForm);
      toast.success(editingDept ? 'Department updated' : 'Department added');
      setShowDeptModal(false); setEditingDept(null); setDeptForm({ name: '', description: '', manager_id: '' });
      fetchTabData();
    } catch (e) { toast.error(e.response?.data?.message || 'Failed'); }
    finally { setSubmitting(false); }
  };

  const submitAsset = async (e) => {
    e.preventDefault(); setSubmitting(true);
    const fd = new FormData();
    Object.keys(assetForm).forEach(k => fd.append(k, assetForm[k]));
    if (receiptFile) fd.append('receipt', receiptFile);
    try {
      if (editingAsset) await axios.post(`/api/company-assets/${editingAsset.id}?_method=PUT`, fd, { headers: { 'Content-Type': 'multipart/form-data' } });
      else await axios.post('/api/company-assets', fd, { headers: { 'Content-Type': 'multipart/form-data' } });
      toast.success(editingAsset ? 'Asset updated' : 'Asset added');
      setShowAssetModal(false); setEditingAsset(null); setAssetForm({ name: '', category: 'equipment', purchase_value: '', current_value: '', purchase_date: '', vendor_name: '', location: '', notes: '' }); setReceiptFile(null);
      fetchTabData();
    } catch (e) { toast.error(e.response?.data?.message || 'Failed'); }
    finally { setSubmitting(false); }
  };

  const submitLoan = async (e) => {
    e.preventDefault(); setSubmitting(true);
    try {
      await axios.post('/api/loans', loanForm);
      toast.success('Loan request submitted');
      setShowLoanRequest(false); setLoanForm({ amount: '', interest_rate: '8', term_months: '12', purpose: '', repayment_schedule: 'monthly', interest_type: 'simple', payment_method: 'bank', bank_account_id: '' });
      fetchTabData();
    } catch (e) { toast.error(e.response?.data?.message || 'Failed'); }
    finally { setSubmitting(false); }
  };

  const submitRepayment = async (e) => {
    e.preventDefault(); setSubmitting(true);
    
    // Ensure bank account is selected
    if (!repayForm.bank_account_id) {
      toast.error('Please select a bank account');
      setSubmitting(false);
      return;
    }
    
    const fd = new FormData();
    fd.append('amount', repayAmount);
    fd.append('payment_date', repayForm.payment_date);
    fd.append('payment_method', repayForm.payment_method);
    fd.append('reference_number', repayForm.reference_number);
    fd.append('notes', repayForm.notes);
    fd.append('bank_account_id', repayForm.bank_account_id);
    
    if (repayForm.payment_method === 'bank_transfer' && repayForm.super_admin_bank_account_id) {
      fd.append('super_admin_bank_account_id', repayForm.super_admin_bank_account_id);
    }
    if (receiptFile) fd.append('receipt', receiptFile);
    
    // Final debug - show FormData contents
    console.log('=== FINAL DEBUG ===');
    console.log('repayForm.bank_account_id:', repayForm.bank_account_id);
    console.log('FormData bank_account_id:', fd.get('bank_account_id'));
    console.log('FormData contents:');
    for (let [key, value] of fd.entries()) {
      console.log(`${key}: ${value}`);
    }
    console.log('=== END DEBUG ===');
    
    try {
      await axios.post(`/api/loans/${selectedLoan.id}/repay`, fd, { headers: { 'Content-Type': 'multipart/form-data' } });
      toast.success('Repayment submitted for confirmation');
      setShowRepayModal(false); setSelectedLoan(null); setRepayAmount(''); setReceiptFile(null);
      setRepayForm({
        amount: '', 
        payment_date: new Date().toISOString().split('T')[0], 
        payment_method: 'bank_transfer', 
        reference_number: '', 
        notes: '', 
        super_admin_bank_account_id: '',
        bank_account_id: ''
      });
      fetchTabData();
    } catch (e) { toast.error(e.response?.data?.message || 'Failed'); }
    finally { setSubmitting(false); }
  };

  const submitLog = async (e) => {
    e.preventDefault(); setSubmitting(true);
    try {
      await axios.post('/api/employee-logs', logForm);
      toast.success('Log added');
      setShowLogModal(false); setLogForm({ employee_id: '', log_type: 'salary_increase', amount_change: '', effective_date: '', end_date: '', description: '', notes: '' });
      fetchTabData();
    } catch (e) { toast.error(e.response?.data?.message || 'Failed'); }
    finally { setSubmitting(false); }
  };

  const submitExpense = async (e) => {
    e.preventDefault(); setSubmitting(true);
    try {
      await axios.post('/api/expenses', expenseForm);
      toast.success('Expense added');
      setShowExpenseModal(false); setExpenseForm({ title: '', amount: '', category: '', expense_date: '', description: '', vendor_name: '' });
      fetchTabData();
    } catch (e) { toast.error(e.response?.data?.message || 'Failed'); }
    finally { setSubmitting(false); }
  };

  const submitFinancials = async (e) => {
    e.preventDefault(); setSubmitting(true);
    try {
      const payload = {};
      Object.entries(financialForm).forEach(([k, v]) => { if (v !== '') payload[k] = v; });
      await axios.put('/api/company/financials', payload);
      toast.success('Financials updated successfully');
      setShowFinancialModal(false);
      fetchDashboardData();
    } catch (err) { toast.error(err.response?.data?.message || 'Failed to update financials'); }
    finally { setSubmitting(false); }
  };

  const openFinancialModal = () => {
    const s2 = stats?.stats || {};
    setFinancialForm({
      revenue: s2.totalRevenue || '',
      cash_balance: s2.cashBalance || '',
      total_assets: s2.totalAssets || '',
      total_liabilities: s2.totalLiabilities || '',
      expenses_manual: s2.totalExpenses || '',
      runway_days: s2.runwayDays || '',
      credit_score: s2.creditScore || '',
    });
    setShowFinancialModal(true);
  };

  const deleteEmployee = async (id) => {
    if (!window.confirm('Delete this employee?')) return;
    try { await axios.delete(`/api/employees/${id}`); toast.success('Deleted'); fetchTabData(); } catch { toast.error('Failed to delete'); }
  };

  const openRepay = (loan) => { 
  setSelectedLoan(loan); 
  setRepayAmount(''); 
  setReceiptFile(null); 
  setRepayForm({
    amount: '', 
    payment_date: new Date().toISOString().split('T')[0], 
    payment_method: 'bank_transfer', 
    reference_number: '', 
    notes: '', 
    super_admin_bank_account_id: '',
    bank_account_id: bankAccounts.length > 0 ? bankAccounts[0].id.toString() : ''
  });
  
  // Debug: Log what we're setting
  console.log('openRepay - bankAccounts:', bankAccounts);
  console.log('openRepay - selected bank_account_id:', bankAccounts.length > 0 ? bankAccounts[0].id.toString() : 'NO_ACCOUNTS'); 
  setShowRepayModal(true); 
};

  const openEmpModal = (emp = null) => {
    if (emp) { setEmpForm({ ...emp, department_id: emp.department_id || '' }); setEditingEmp(emp); }
    else { setEmpForm({ name: '', email: '', phone: '', department_id: '', salary: '', position: '', employment_type: 'full-time', status: 'active' }); setEditingEmp(null); }
    setShowEmpModal(true);
  };

  const openDeptModal = (dept = null) => {
    if (dept) { setDeptForm({ ...dept, manager_id: dept.manager_id || '' }); setEditingDept(dept); }
    else { setDeptForm({ name: '', description: '', manager_id: '' }); setEditingDept(null); }
    setShowDeptModal(true);
  };

  const openAssetModal = (asset = null) => {
    if (asset) { setAssetForm({ ...asset, purchase_date: asset.purchase_date || '' }); setEditingAsset(asset); }
    else { setAssetForm({ name: '', category: 'equipment', purchase_value: '', current_value: '', purchase_date: '', vendor_name: '', location: '', notes: '' }); setEditingAsset(null); }
    setShowAssetModal(true);
  };

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

  if (!stats?.stats) {
    return (
      <div className="p-8 text-center">
        <h2 className="text-xl font-semibold text-gray-800 mb-2">No Company Data</h2>
        <p className="text-gray-500">You are not assigned to a company.</p>
      </div>
    );
  }

  const s = stats.stats;
  const kpiCards = [
    { label: 'Revenue', value: `₦${(s.totalRevenue || 0).toLocaleString()}`, change: s.revenueChange, icon: CurrencyDollar, color: 'bg-primary-50 text-primary-600' },
    { label: 'Net Profit', value: `₦${(s.netProfit || 0).toLocaleString()}`, change: s.profitChange, icon: TrendUp, color: 'bg-green-50 text-green-600' },
    { label: 'Expenses', value: `₦${(s.totalExpenses || 0).toLocaleString()}`, change: s.expensesChange, icon: Receipt, color: 'bg-red-50 text-red-600' },
    { label: 'Cash Balance', value: `₦${(s.cashBalance || 0).toLocaleString()}`, change: s.cashChange, icon: Wallet, color: 'bg-amber-50 text-amber-600' },
    { label: 'Active Employees', value: s.activeEmployees || 0, change: s.employeesChange, icon: Users, color: 'bg-purple-50 text-purple-600' },
    { label: 'Departments', value: s.totalDepartments ?? s.departments ?? 0, change: null, icon: Buildings, color: 'bg-cyan-50 text-cyan-600' },
    { label: 'System Users', value: s.totalUsers ?? 0, change: null, icon: UserPlus, color: 'bg-indigo-50 text-indigo-600' },
    { label: 'Runway (Days)', value: s.runwayDays ?? '—', change: null, icon: Clock, color: 'bg-teal-50 text-teal-600' },
  ];

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 p-6">
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900 flex items-center gap-3">
          <ShieldCheck size={28} weight="duotone" className="text-primary-600" />
          {s.companyName || 'Company Dashboard'}
        </h1>
        <p className="text-gray-600 mt-1 text-sm">Financial overview and quick management links</p>
      </div>

      <div className="flex flex-wrap items-center gap-2 mb-6">
        <button onClick={openFinancialModal}
          className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-semibold text-white shadow-sm" style={{background:'#5D4037'}}>
          <Pencil size={15}/> Update Financials
        </button>
        <button onClick={() => setShowLoanRequest(true)}
          className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-semibold text-white shadow-sm bg-green-600 hover:bg-green-700">
          <CurrencyDollar size={15}/> Request Loan
        </button>
      </div>

      <div className="flex flex-wrap gap-2 mb-4">
        {[
          { label: 'Employees', path: '/employees', icon: Users, color: 'text-purple-600 bg-purple-50' },
          { label: 'Departments', path: '/departments', icon: Briefcase, color: 'text-cyan-600 bg-cyan-50' },
          { label: 'Assets', path: '/assets', icon: Bank, color: 'text-primary-600 bg-primary-50' },
          { label: 'Loans', path: '/loans', icon: CurrencyDollar, color: 'text-amber-600 bg-amber-50' },
          { label: 'Expenses', path: '/expenses', icon: Receipt, color: 'text-red-600 bg-red-50' },
          { label: 'Profit Allocation', path: '/profit-sweeps', icon: TrendUp, color: 'text-green-600 bg-green-50' },
        ].map((item) => (
          <Link key={item.path} to={item.path} className={`flex items-center gap-2 px-4 py-2 rounded-lg shadow-sm border border-gray-200 hover:shadow-md transition-all text-sm font-medium ${item.color}`}>
            <item.icon size={18} weight="duotone" />{item.label}
          </Link>
        ))}
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-4 mb-8">
        {kpiCards.map((card, idx) => (
          <div key={idx} className="bg-white rounded-xl shadow-sm border border-gray-100 p-5 hover:shadow-md transition-all">
            <div className="flex items-center justify-between mb-3">
              <span className="text-xs font-semibold text-gray-500 uppercase tracking-wider">{card.label}</span>
              <div className={`p-2 rounded-lg ${card.color}`}><card.icon size={20} weight="duotone" /></div>
            </div>
            <div className="text-2xl font-bold text-gray-900 mb-1">{card.value}</div>
            {card.change !== null && (
              <div className={`flex items-center gap-1 text-xs font-medium ${card.change >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                {card.change >= 0 ? <ArrowUp size={14} /> : <ArrowDown size={14} />}
                {Math.abs(card.change).toFixed(1)}%
              </div>
            )}
          </div>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6 lg:col-span-2">
          <div className="flex items-center gap-2 mb-4">
            <ChartLineUp size={24} className="text-primary-600" weight="duotone" />
            <h3 className="text-lg font-bold text-gray-900">Revenue vs Expenses Trend</h3>
          </div>
          <ResponsiveContainer width="100%" height={300}>
            <AreaChart data={stats.revenueData || []}>
              <defs>
                <linearGradient id="colorRev" x1="0" y1="0" x2="0" y2="1"><stop offset="5%" stopColor="#5D4037" stopOpacity={0.1}/><stop offset="95%" stopColor="#5D4037" stopOpacity={0}/></linearGradient>
                <linearGradient id="colorExp" x1="0" y1="0" x2="0" y2="1"><stop offset="5%" stopColor="#ef4444" stopOpacity={0.1}/><stop offset="95%" stopColor="#ef4444" stopOpacity={0}/></linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" stroke="#f3f4f6" />
              <XAxis dataKey="month" stroke="#9ca3af" fontSize={12} />
              <YAxis stroke="#9ca3af" fontSize={12} tickFormatter={(v) => `₦${(v/1000).toFixed(0)}k`} />
              <Tooltip formatter={(v) => `₦${v.toLocaleString()}`} />
              <Legend />
              <Area type="monotone" dataKey="revenue" stroke="#5D4037" fillOpacity={1} fill="url(#colorRev)" strokeWidth={2} />
              <Area type="monotone" dataKey="expenses" stroke="#ef4444" fillOpacity={1} fill="url(#colorExp)" strokeWidth={2} />
              <Area type="monotone" dataKey="profit" stroke="#16a34a" fill="none" strokeWidth={2} strokeDasharray="5 5" />
            </AreaChart>
          </ResponsiveContainer>
        </div>

        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
          <div className="flex items-center gap-2 mb-4">
            <ChartLineUp size={24} className="text-amber-600" weight="duotone" />
            <h3 className="text-lg font-bold text-gray-900">Expense Breakdown</h3>
          </div>
          <ResponsiveContainer width="100%" height={250}>
            <PieChart>
              <Pie data={stats.expenseData || []} cx="50%" cy="50%" innerRadius={60} outerRadius={90} paddingAngle={5} dataKey="value" nameKey="name">
                {(stats.expenseData || []).map((entry, index) => <Cell key={`cell-${index}`} fill={entry.color || COLORS[index % COLORS.length]} />)}
              </Pie>
              <Tooltip formatter={(v, n) => [`₦${v.toLocaleString()}`, n]} />
              <Legend verticalAlign="bottom" height={36} />
            </PieChart>
          </ResponsiveContainer>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
          <h3 className="text-lg font-bold text-gray-900 mb-4">Asset Distribution</h3>
          <div className="space-y-4">
            {(stats.assetData || []).map((asset, idx) => (
              <div key={idx}>
                <div className="flex justify-between text-sm mb-1">
                  <span className="font-medium text-gray-700">{asset.category}</span>
                  <span className="text-gray-900 font-semibold">₦{asset.current.toLocaleString()}</span>
                </div>
                <div className="w-full bg-gray-100 rounded-full h-2">
                  <div className="bg-primary-600 h-2 rounded-full" style={{ width: `${Math.min((asset.current / asset.target) * 100, 100)}%` }} />
                </div>
                <div className="text-xs text-gray-500 mt-1">Target: ₦{asset.target.toLocaleString()}</div>
              </div>
            ))}
          </div>
        </div>

        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-bold text-gray-900">Recent Audit Activity</h3>
            <Link to="/audit-logs" className="text-sm text-primary-600 hover:underline">View all</Link>
          </div>
          <div className="space-y-3">
            <div className="grid grid-cols-3 gap-4 mb-4">
              <div className="bg-primary-50 rounded-lg p-3 text-center">
                <div className="text-2xl font-bold text-primary-600">{stats.audit?.today || 0}</div>
                <div className="text-xs text-primary-700">Today</div>
              </div>
              <div className="bg-purple-50 rounded-lg p-3 text-center">
                <div className="text-2xl font-bold text-purple-600">{stats.audit?.week || 0}</div>
                <div className="text-xs text-purple-700">This Week</div>
              </div>
              <div className="bg-green-50 rounded-lg p-3 text-center">
                <div className="text-2xl font-bold text-green-600">{stats.audit?.month || 0}</div>
                <div className="text-xs text-green-700">This Month</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* ── Update Financials Modal ─────────────────────────── */}
      {showFinancialModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50" onClick={() => setShowFinancialModal(false)}>
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between p-5 border-b border-gray-100">
              <h3 className="font-bold text-lg text-gray-900 flex items-center gap-2"><ChartLineUp size={20} className="text-primary-600"/> Update Company Financials</h3>
              <button onClick={() => setShowFinancialModal(false)} className="p-1 hover:bg-gray-100 rounded-lg"><X size={20}/></button>
            </div>
            <form onSubmit={submitFinancials} className="p-5">
              <p className="text-xs text-gray-500 mb-4">Enter values to update the KPI cards on the dashboard. Leave blank to keep current values.</p>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                {[
                  {key:'revenue', label:'Annual Revenue (₦)', type:'number'},
                  {key:'cash_balance', label:'Cash Balance (₦)', type:'number'},
                  {key:'total_assets', label:'Total Assets (₦)', type:'number'},
                  {key:'total_liabilities', label:'Total Liabilities (₦)', type:'number'},
                  {key:'expenses_manual', label:'Monthly Expenses (₦)', type:'number'},
                  {key:'runway_days', label:'Runway (Days)', type:'number'},
                  {key:'credit_score', label:'Credit Score (300–850)', type:'number'},
                ].map(({key, label, type}) => (
                  <div key={key}>
                    <label className="block text-xs font-semibold text-gray-600 mb-1">{label}</label>
                    <input type={type} min="0" value={financialForm[key]} onChange={e => setFinancialForm(p => ({...p, [key]: 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"
                      placeholder="Enter value…"/>
                  </div>
                ))}
              </div>
              <div className="flex justify-end gap-3 pt-2">
                <button type="button" onClick={() => setShowFinancialModal(false)} className="px-4 py-2 bg-gray-100 text-gray-700 rounded-xl text-sm font-medium">Cancel</button>
                <button type="submit" disabled={submitting} className="px-5 py-2 text-white rounded-xl text-sm font-semibold" style={{background:'#5D4037'}}>{submitting ? 'Saving…' : 'Save Financials'}</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* ── Loan Request Modal ─────────────────────────── */}
      {showLoanRequest && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50" onClick={() => setShowLoanRequest(false)}>
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between p-5 border-b border-gray-100">
              <h3 className="font-bold text-lg text-gray-900 flex items-center gap-2"><CurrencyDollar size={20} className="text-primary-600"/> Request Loan</h3>
              <button onClick={() => setShowLoanRequest(false)} className="p-1 hover:bg-gray-100 rounded-lg"><X size={20}/></button>
            </div>
            <form onSubmit={submitLoan} className="p-5">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Loan Amount (₦) *</label>
                  <input type="number" min="0" step="0.01" value={loanForm.amount} onChange={e => setLoanForm(p => ({...p, amount: 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"
                    placeholder="Enter loan amount" required />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Interest Rate (%) *</label>
                  <input type="number" min="0" max="100" step="0.1" value={loanForm.interest_rate} onChange={e => setLoanForm(p => ({...p, interest_rate: 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"
                    placeholder="Enter interest rate" required />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Term (Months) *</label>
                  <input type="number" min="1" value={loanForm.term_months} onChange={e => setLoanForm(p => ({...p, term_months: 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"
                    placeholder="Enter loan term in months" required />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Repayment Schedule *</label>
                  <select value={loanForm.repayment_schedule} onChange={e => setLoanForm(p => ({...p, repayment_schedule: 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="monthly">Monthly</option>
                    <option value="quarterly">Quarterly</option>
                    <option value="annually">Annually</option>
                  </select>
                </div>
                <div className="md:col-span-2">
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Purpose *</label>
                  <input type="text" value={loanForm.purpose} onChange={e => setLoanForm(p => ({...p, purpose: 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"
                    placeholder="Enter loan purpose" required />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Payment Method *</label>
                  <select value={loanForm.payment_method} onChange={e => setLoanForm(p => ({...p, payment_method: e.target.value, bank_account_id: ''}))}
                    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="bank">Bank Transfer</option>
                    <option value="cash">Cash</option>
                  </select>
                </div>
                {loanForm.payment_method === 'bank' && (
                  <div>
                    <label className="block text-xs font-semibold text-gray-600 mb-1">Bank Account *</label>
                    <select value={loanForm.bank_account_id} onChange={e => setLoanForm(p => ({...p, bank_account_id: 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 bank account —</option>
                      {bankAccounts.map(ba => (
                        <option key={ba.id} value={ba.id}>{ba.bank_name} - {ba.account_number} ({ba.account_name})</option>
                      ))}
                    </select>
                  </div>
                )}
              </div>
              <div className="flex justify-end gap-3 pt-2">
                <button type="button" onClick={() => setShowLoanRequest(false)} className="px-4 py-2 bg-gray-100 text-gray-700 rounded-xl text-sm font-medium">Cancel</button>
                <button type="submit" disabled={submitting || (loanForm.payment_method === 'bank' && !loanForm.bank_account_id)} className="px-5 py-2 text-white rounded-xl text-sm font-semibold" style={{background:'#5D4037'}}>{submitting ? 'Submitting…' : 'Submit Request'}</button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* ── Loan Repayment Modal ─────────────────────────── */}
      {showRepayModal && selectedLoan && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50" onClick={() => setShowRepayModal(false)}>
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between p-5 border-b border-gray-100">
              <h3 className="font-bold text-lg text-gray-900 flex items-center gap-2"><CurrencyDollar size={20} className="text-green-600"/> Repay Loan</h3>
              <button onClick={() => setShowRepayModal(false)} className="p-1 hover:bg-gray-100 rounded-lg"><X size={20}/></button>
            </div>
            <form onSubmit={submitRepayment} className="p-5">
              <div className="mb-4">
                <p className="text-sm text-gray-600 mb-2">Loan: <span className="font-bold">#{selectedLoan.loan_number}</span></p>
                <p className="text-sm text-gray-600">Outstanding: <span className="font-bold text-green-600">₦{Number(selectedLoan.outstanding_balance).toLocaleString()}</span></p>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Repayment Amount (₦) *</label>
                  <input type="number" min="0" step="0.01" value={repayAmount} onChange={e => setRepayAmount(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"
                    placeholder="Enter repayment amount" required />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Payment Date *</label>
                  <input type="date" value={repayForm.payment_date} onChange={e => setRepayForm(p => ({...p, payment_date: 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" required />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Payment Method *</label>
                  <select value={repayForm.payment_method} onChange={e => setRepayForm(p => ({...p, payment_method: 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="bank_transfer">Bank Transfer</option>
                    <option value="cash">Cash</option>
                  </select>
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Your Bank Account *</label>
                  <select value={repayForm.bank_account_id} onChange={e => setRepayForm(p => ({...p, bank_account_id: 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 your bank account —</option>
                      {bankAccounts.map(ba => (
                        <option key={ba.id} value={ba.id}>{ba.bank_name} - {ba.account_number} ({ba.account_name})</option>
                      ))}
                    </select>
                </div>
                {repayForm.payment_method === 'bank_transfer' && (
                  <div>
                    <label className="block text-xs font-semibold text-gray-600 mb-1">Super Admin Bank Account *</label>
                    <select value={repayForm.super_admin_bank_account_id} onChange={e => setRepayForm(p => ({...p, super_admin_bank_account_id: 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 Super Admin bank account —</option>
                      {superAdminBankAccounts.map(ba => (
                        <option key={ba.id} value={ba.id}>{ba.bank_name} - {ba.account_number} ({ba.account_name})</option>
                      ))}
                    </select>
                  </div>
                )}
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Reference Number</label>
                  <input type="text" value={repayForm.reference_number} onChange={e => setRepayForm(p => ({...p, reference_number: 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"
                    placeholder="Enter reference number" />
                </div>
                <div className="md:col-span-2">
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Notes</label>
                  <textarea value={repayForm.notes} onChange={e => setRepayForm(p => ({...p, notes: 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"
                    placeholder="Enter notes" rows="3" />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-600 mb-1">Receipt</label>
                  <input type="file" onChange={e => setReceiptFile(e.target.files[0])}
                    className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-primary-500 outline-none"
                    accept="image/*,.pdf" />
                </div>
              </div>
              <div className="flex justify-end gap-3 pt-2">
                <button type="button" onClick={() => setShowRepayModal(false)} className="px-4 py-2 bg-gray-100 text-gray-700 rounded-xl text-sm font-medium">Cancel</button>
                <button type="submit" disabled={submitting} className="px-5 py-2 text-white rounded-xl text-sm font-semibold bg-green-600 hover:bg-green-700">{submitting ? 'Submitting…' : 'Submit Repayment'}</button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
