import React, { useState, useEffect, useCallback } from 'react';
import {
  Plus, Handshake, CurrencyDollar, Percent, Buildings, User,
  ChartPieSlice, X, Eye, PencilSimple, Trash, Upload,
  ArrowRight, Money, FileText, Star, CheckCircle, Clock,
  Warning, TrendUp, Briefcase, Calendar, Phone, EnvelopeSimple,
  MapPin, IdentificationCard, Bank
} from '@phosphor-icons/react';
import axios from 'axios';
import toast from 'react-hot-toast';

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

const STATUS_COLOR = {
  active:   'bg-green-100 text-green-700',
  inactive: 'bg-gray-100 text-gray-600',
  exited:   'bg-red-100 text-red-700',
  pending:  'bg-yellow-100 text-yellow-700',
};
const TYPE_COLOR = {
  investor:        'bg-primary-100 text-primary-700',
  partner:         'bg-purple-100 text-purple-700',
  angel:           'bg-amber-100 text-amber-700',
  venture_capital: 'bg-indigo-100 text-indigo-700',
  strategic:       'bg-teal-100 text-teal-700',
};

const EMPTY_FORM = {
  entity_type:'individual', name:'', company_name:'', email:'', phone:'',
  address:'', country:'', nationality:'', date_of_birth:'', id_number:'', id_type:'passport',
  investment_type:'money', money_amount:'', asset_description:'', asset_value:'',
  intellectual_description:'', intellectual_value:'', equity_percentage:'', shares_count:'',
  share_price:'', expected_dividend_rate:'', dividend_frequency:'annually',
  company_id:'', status:'pending', partner_type:'investor', investment_date:'', notes:'',
};

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

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

export default function InvestorsPartners() {
  const [investors, setInvestors]   = useState([]);
  const [summary, setSummary]       = useState({});
  const [companies, setCompanies]   = useState([]);
  const [loading, setLoading]       = useState(true);
  const [tab, setTab]               = useState('all');
  const [search, setSearch]         = useState('');
  const [saving, setSaving]         = useState(false);

  const [showForm, setShowForm]     = useState(false);
  const [editing, setEditing]       = useState(null);
  const [form, setForm]             = useState(EMPTY_FORM);
  const [photoFile, setPhotoFile]   = useState(null);
  const [docFile, setDocFile]       = useState(null);
  const [photoPreview, setPhotoPreview] = useState(null);

  const [showDetail, setShowDetail] = useState(false);
  const [selected, setSelected]     = useState(null);
  const [payments, setPayments]     = useState([]);
  const [showPayForm, setShowPayForm] = useState(false);
  const [payForm, setPayForm]       = useState(EMPTY_PAY);
  const [payReceipt, setPayReceipt] = useState(null);
  const [paySaving, setPaySaving]   = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const [invRes, compRes] = await Promise.all([
        axios.get('/api/investors', { params: { search } }),
        axios.get('/api/companies'),
      ]);
      setInvestors(invRes.data.data || []);
      setSummary(invRes.data.summary || {});
      setCompanies(compRes.data.data || []);
    } catch { toast.error('Failed to load investors'); }
    finally { setLoading(false); }
  }, [search]);

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

  const openAdd = () => {
    setEditing(null); setForm(EMPTY_FORM);
    setPhotoFile(null); setDocFile(null); setPhotoPreview(null);
    setShowForm(true);
  };

  const openEdit = (inv) => {
    setEditing(inv);
    setForm({
      entity_type: inv.entity_type || 'individual',
      name: inv.name || '', company_name: inv.company_name || '',
      email: inv.email || '', phone: inv.phone || '',
      address: inv.address || '', country: inv.country || '',
      nationality: inv.nationality || '', date_of_birth: inv.date_of_birth || '',
      id_number: inv.id_number || '', id_type: inv.id_type || 'passport',
      investment_type: inv.investment_type || 'money',
      money_amount: inv.money_amount || '', asset_description: inv.asset_description || '',
      asset_value: inv.asset_value || '', intellectual_description: inv.intellectual_description || '',
      intellectual_value: inv.intellectual_value || '', equity_percentage: inv.equity_percentage || '',
      shares_count: inv.shares_count || '', share_price: inv.share_price || '',
      expected_dividend_rate: inv.expected_dividend_rate || '',
      dividend_frequency: inv.dividend_frequency || 'annually',
      company_id: inv.company_id || '', status: inv.status || 'pending',
      partner_type: inv.partner_type || 'investor',
      investment_date: inv.investment_date || '', notes: inv.notes || '',
    });
    setPhotoFile(null); setDocFile(null); setPhotoPreview(inv.photo_url || null);
    setShowForm(true);
  };

  const openDetail = async (inv) => {
    setSelected(inv); setShowDetail(true); setPayments([]);
    try {
      const res = await axios.get(`/api/investors/${inv.id}/payments`);
      setPayments(res.data.data || []);
    } catch {}
  };

  const handleSave = async (e) => {
    e.preventDefault(); setSaving(true);
    const fd = new FormData();
    Object.entries(form).forEach(([k,v]) => { if (v !== '' && v != null) fd.append(k, v); });
    if (photoFile) fd.append('photo', photoFile);
    if (docFile)   fd.append('id_document', docFile);
    try {
      if (editing) {
        await axios.post(`/api/investors/${editing.id}`, fd, { headers: { 'Content-Type':'multipart/form-data' } });
        toast.success('Investor updated');
      } else {
        await axios.post('/api/investors', fd, { headers: { 'Content-Type':'multipart/form-data' } });
        toast.success('Investor added');
      }
      setShowForm(false); load();
    } catch (err) { toast.error(err.response?.data?.message || 'Failed'); }
    finally { setSaving(false); }
  };

  const handleDelete = async (id) => {
    if (!confirm('Delete this investor? This cannot be undone.')) return;
    try { await axios.delete(`/api/investors/${id}`); toast.success('Deleted'); load(); }
    catch { toast.error('Failed to delete'); }
  };

  const handleAddPayment = async (e) => {
    e.preventDefault(); setPaySaving(true);
    const fd = new FormData();
    Object.entries(payForm).forEach(([k,v]) => { if (v !== '' && v != null) fd.append(k, v); });
    if (payReceipt) fd.append('receipt', payReceipt);
    try {
      await axios.post(`/api/investors/${selected.id}/payments`, fd, { headers: { 'Content-Type':'multipart/form-data' } });
      toast.success('Payment logged');
      setShowPayForm(false); setPayReceipt(null); setPayForm(EMPTY_PAY);
      const res = await axios.get(`/api/investors/${selected.id}/payments`);
      setPayments(res.data.data || []);
      load();
    } catch (err) { toast.error(err.response?.data?.message || 'Failed'); }
    finally { setPaySaving(false); }
  };

  const filtered = investors.filter(inv => {
    if (tab === 'active')   return inv.status === 'active';
    if (tab === 'pending')  return inv.status === 'pending';
    if (tab === 'exited')   return inv.status === 'exited';
    if (tab === 'company')  return inv.entity_type === 'company';
    if (tab === 'individual') return inv.entity_type === 'individual';
    return true;
  });

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

      {/* Header */}
      <div className="flex flex-wrap items-center justify-between gap-4 mb-6">
        <div>
          <h1 className="text-2xl font-black text-gray-900 flex items-center gap-2">
            <Handshake size={28} weight="duotone" className="text-indigo-600"/> Investors &amp; Partners
          </h1>
          <p className="text-sm text-gray-500 mt-0.5">Manage investors, partners, equity, and distributions</p>
        </div>
        <button onClick={openAdd}
          className="flex items-center gap-2 px-5 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white text-sm font-semibold rounded-xl shadow transition-all">
          <Plus size={16} weight="bold"/> Add Investor / Partner
        </button>
      </div>

      {/* Summary KPIs */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-4 mb-6">
        {[
          { label:'Total Investors', value: summary.total || 0,           icon: Handshake,      color:'#6366f1', unit:'count' },
          { label:'Active',          value: summary.active || 0,           icon: CheckCircle,    color:'#10b981', unit:'count' },
          { label:'Total Invested',  value: summary.total_invested || 0,   icon: CurrencyDollar, color:'#5D4037', unit:'currency' },
          { label:'Total Paid Out',  value: summary.total_paid_out || 0,   icon: TrendUp,        color:'#f59e0b', unit:'currency' },
          { label:'Total Equity',    value: summary.total_equity_given || 0,icon: Percent,       color:'#ec4899', unit:'pct' },
        ].map((k,i) => (
          <div key={i} className="bg-white rounded-2xl shadow-sm border border-gray-100 p-4 flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0" style={{ background: k.color + '18' }}>
              <k.icon size={20} weight="duotone" style={{ color: k.color }}/>
            </div>
            <div>
              <p className="text-lg font-black text-gray-900">
                {k.unit === 'currency' ? fmt(k.value) : k.unit === 'pct' ? pct(k.value) : k.value}
              </p>
              <p className="text-xs text-gray-500">{k.label}</p>
            </div>
          </div>
        ))}
      </div>

      {/* Search + Tabs */}
      <div className="flex flex-wrap gap-3 mb-5 items-center">
        <input value={search} onChange={e=>setSearch(e.target.value)} placeholder="Search by name, email, ID..."
          className="flex-1 min-w-[220px] px-4 py-2 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 outline-none bg-white"/>
        <div className="flex gap-1 bg-white rounded-xl p-1 shadow-sm border border-gray-100 flex-wrap">
          {['all','active','pending','exited','individual','company'].map(t => (
            <button key={t} onClick={() => setTab(t)}
              className={`px-3 py-1.5 rounded-lg text-xs font-semibold capitalize transition-all ${tab===t ? 'bg-indigo-600 text-white' : 'text-gray-500 hover:bg-gray-100'}`}>
              {t === 'all' ? 'All' : t}
            </button>
          ))}
        </div>
      </div>

      {/* Investor Cards Grid */}
      {loading ? (
        <div className="flex justify-center py-20"><div className="w-12 h-12 rounded-full border-4 border-t-transparent border-indigo-600 animate-spin"/></div>
      ) : filtered.length === 0 ? (
        <div className="text-center py-20 text-gray-400">
          <Handshake size={52} className="mx-auto mb-3 opacity-20"/>
          <p className="font-medium">No investors found</p>
          <p className="text-sm mt-1">Add your first investor or partner</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5">
          {filtered.map(inv => (
            <div key={inv.id} className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden hover:shadow-md transition-shadow">
              {/* Card Header */}
              <div className="p-5 pb-4">
                <div className="flex items-start gap-4">
                  {inv.photo_url ? (
                    <img src={inv.photo_url} alt={inv.display_name}
                      className="w-14 h-14 rounded-2xl object-cover border-2 border-indigo-100 flex-shrink-0"/>
                  ) : (
                    <div className="w-14 h-14 rounded-2xl flex items-center justify-center flex-shrink-0 text-2xl font-black"
                      style={{ background: inv.entity_type === 'company' ? '#e0e7ff' : '#f3e8ff', color: inv.entity_type === 'company' ? '#6366f1' : '#9333ea' }}>
                      {inv.entity_type === 'company' ? <Buildings size={26} weight="duotone"/> : <User size={26} weight="duotone"/>}
                    </div>
                  )}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 flex-wrap mb-1">
                      <span className={`text-xs font-semibold px-2 py-0.5 rounded-full ${TYPE_COLOR[inv.partner_type] || 'bg-gray-100 text-gray-600'}`}>
                        {(inv.partner_type || '').replace('_',' ')}
                      </span>
                      <span className={`text-xs font-semibold px-2 py-0.5 rounded-full ${STATUS_COLOR[inv.status] || 'bg-gray-100 text-gray-600'}`}>
                        {inv.status}
                      </span>
                    </div>
                    <h3 className="font-bold text-gray-900 truncate">{inv.display_name}</h3>
                    {inv.entity_type === 'company' && inv.name !== inv.company_name && (
                      <p className="text-xs text-gray-500 truncate">Rep: {inv.name}</p>
                    )}
                    <p className="text-xs text-gray-400">{inv.investor_number}</p>
                  </div>
                </div>

                {/* Investment type badge */}
                <div className="mt-3 flex items-center gap-2">
                  <span className="text-xs px-2 py-0.5 rounded-full bg-primary-50 text-primary-700 font-medium capitalize">
                    {(inv.investment_type || '').replace('_',' ')}
                  </span>
                  {inv.company && (
                    <span className="text-xs px-2 py-0.5 rounded-full bg-gray-50 text-gray-500">
                      {inv.company.name}
                    </span>
                  )}
                </div>

                {/* Financials */}
                <div className="mt-3 grid grid-cols-2 gap-3">
                  <div className="bg-indigo-50 rounded-xl p-2.5">
                    <p className="text-xs text-indigo-500 font-medium">Invested</p>
                    <p className="font-black text-indigo-900 text-sm truncate">{fmt(inv.total_investment_value)}</p>
                  </div>
                  <div className="bg-green-50 rounded-xl p-2.5">
                    <p className="text-xs text-green-600 font-medium">Paid Out</p>
                    <p className="font-black text-green-900 text-sm truncate">{fmt(inv.total_paid_out)}</p>
                  </div>
                  <div className="bg-purple-50 rounded-xl p-2.5">
                    <p className="text-xs text-purple-500 font-medium">Equity</p>
                    <p className="font-black text-purple-900 text-sm">{pct(inv.equity_percentage)}</p>
                  </div>
                  <div className="bg-amber-50 rounded-xl p-2.5">
                    <p className="text-xs text-amber-600 font-medium">Dividend Rate</p>
                    <p className="font-black text-amber-900 text-sm">{pct(inv.expected_dividend_rate)}</p>
                  </div>
                </div>
              </div>

              {/* Actions */}
              <div className="px-5 pb-4 flex gap-2">
                <button onClick={() => openDetail(inv)}
                  className="flex-1 flex items-center justify-center gap-1.5 px-3 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-xs font-semibold transition-all">
                  <Eye size={14}/> View
                </button>
                <button onClick={() => openEdit(inv)}
                  className="flex items-center justify-center gap-1 px-3 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-xl text-xs font-semibold transition-all">
                  <PencilSimple size={14}/> Edit
                </button>
                <button onClick={() => handleDelete(inv.id)}
                  className="flex items-center justify-center gap-1 px-3 py-2 bg-red-50 hover:bg-red-100 text-red-600 rounded-xl text-xs font-semibold transition-all">
                  <Trash size={14}/>
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* ── Add / Edit Modal ──────────────────────────────────────── */}
      {showForm && (
        <div className="fixed inset-0 z-50 flex items-start justify-center p-4 bg-black/50 overflow-y-auto" onClick={()=>setShowForm(false)}>
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-3xl my-6" onClick={e=>e.stopPropagation()}>
            <div className="flex items-center justify-between p-5 border-b sticky top-0 bg-white rounded-t-2xl z-10">
              <h2 className="text-lg font-bold text-gray-900">{editing ? 'Edit Investor / Partner' : 'Add New Investor / Partner'}</h2>
              <button onClick={()=>setShowForm(false)} className="p-1.5 hover:bg-gray-100 rounded-lg"><X size={20}/></button>
            </div>
            <form onSubmit={handleSave} className="p-5">
              {/* Entity Type */}
              <div className="mb-5">
                <p className="text-xs font-bold text-gray-500 uppercase tracking-wider mb-2">Investor Type</p>
                <div className="flex gap-3">
                  {['individual','company'].map(t => (
                    <button type="button" key={t} onClick={() => setForm(p=>({...p,entity_type:t}))}
                      className={`flex-1 flex items-center justify-center gap-2 py-3 rounded-xl border-2 font-semibold text-sm transition-all ${form.entity_type===t ? 'border-indigo-600 bg-indigo-50 text-indigo-700' : 'border-gray-200 text-gray-500 hover:border-gray-300'}`}>
                      {t === 'individual' ? <User size={18}/> : <Buildings size={18}/>}
                      {t === 'individual' ? 'Individual Person' : 'Company / Organisation'}
                    </button>
                  ))}
                </div>
              </div>

              {/* Personal Info */}
              <p className="text-xs font-bold text-gray-500 uppercase tracking-wider mb-3">
                {form.entity_type === 'individual' ? 'Personal Information' : 'Company Information'}
              </p>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-5">
                <Inp label={form.entity_type === 'individual' ? 'Full Name *' : 'Contact Person Name *'} required value={form.name} onChange={e=>setForm(p=>({...p,name:e.target.value}))}/>
                {form.entity_type === 'company' && (
                  <Inp label="Company / Organisation Name" value={form.company_name} onChange={e=>setForm(p=>({...p,company_name:e.target.value}))}/>
                )}
                <Inp label="Email" type="email" value={form.email} onChange={e=>setForm(p=>({...p,email:e.target.value}))}/>
                <Inp label="Phone" value={form.phone} onChange={e=>setForm(p=>({...p,phone:e.target.value}))}/>
                <Inp label="Country" value={form.country} onChange={e=>setForm(p=>({...p,country:e.target.value}))}/>
                {form.entity_type === 'individual' && (
                  <Inp label="Nationality" value={form.nationality} onChange={e=>setForm(p=>({...p,nationality:e.target.value}))}/>
                )}
                {form.entity_type === 'individual' && (
                  <Inp label="Date of Birth" type="date" value={form.date_of_birth} onChange={e=>setForm(p=>({...p,date_of_birth:e.target.value}))}/>
                )}
                <Sel label={form.entity_type === 'individual' ? 'ID Type' : 'Registration Type'} value={form.id_type} onChange={e=>setForm(p=>({...p,id_type:e.target.value}))}>
                  <option value="passport">Passport</option>
                  <option value="nin">NIN</option>
                  <option value="drivers_license">Driver's License</option>
                  <option value="rc_number">RC Number (Company)</option>
                  <option value="tin">TIN</option>
                  <option value="other">Other</option>
                </Sel>
                <Inp label="ID / RC / TIN Number" value={form.id_number} onChange={e=>setForm(p=>({...p,id_number:e.target.value}))}/>
                <div className="sm:col-span-2">
                  <Inp label="Address" value={form.address} onChange={e=>setForm(p=>({...p,address:e.target.value}))}/>
                </div>
              </div>

              {/* Photo + ID Upload */}
              <p className="text-xs font-bold text-gray-500 uppercase tracking-wider mb-3">Documents &amp; Photo</p>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-5">
                <Field label="Profile Photo">
                  <label className="flex flex-col items-center justify-center border-2 border-dashed border-gray-200 rounded-xl p-4 cursor-pointer hover:border-indigo-400 transition-colors">
                    {photoPreview ? (
                      <img src={photoPreview} className="w-20 h-20 rounded-xl object-cover mb-1"/>
                    ) : (
                      <Upload size={24} className="text-gray-400 mb-1"/>
                    )}
                    <span className="text-xs text-gray-500">{photoFile ? photoFile.name : 'Upload photo (JPG/PNG)'}</span>
                    <input type="file" accept="image/*" className="hidden" onChange={e=>{
                      const f = e.target.files[0];
                      if (f) { setPhotoFile(f); setPhotoPreview(URL.createObjectURL(f)); }
                    }}/>
                  </label>
                </Field>
                <Field label="ID Document (PDF/Image)">
                  <label className="flex flex-col items-center justify-center border-2 border-dashed border-gray-200 rounded-xl p-4 cursor-pointer hover:border-indigo-400 transition-colors">
                    <FileText size={24} className="text-gray-400 mb-1"/>
                    <span className="text-xs text-gray-500">{docFile ? docFile.name : 'Upload ID document'}</span>
                    <input type="file" accept=".pdf,image/*" className="hidden" onChange={e=>{ if(e.target.files[0]) setDocFile(e.target.files[0]); }}/>
                  </label>
                </Field>
              </div>

              {/* Investment Details */}
              <p className="text-xs font-bold text-gray-500 uppercase tracking-wider mb-3">Investment Details</p>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-5">
                <Sel label="Investment Type *" required value={form.investment_type} onChange={e=>setForm(p=>({...p,investment_type:e.target.value}))}>
                  <option value="money">Cash / Money</option>
                  <option value="assets">Assets</option>
                  <option value="intellectual_property">Intellectual Property / Knowledge</option>
                  <option value="mixed">Mixed (Multiple Types)</option>
                </Sel>
                <Sel label="Partner Role" value={form.partner_type} onChange={e=>setForm(p=>({...p,partner_type:e.target.value}))}>
                  <option value="investor">Investor</option>
                  <option value="partner">Partner</option>
                  <option value="angel">Angel Investor</option>
                  <option value="venture_capital">Venture Capital</option>
                  <option value="strategic">Strategic Partner</option>
                </Sel>

                {(form.investment_type === 'money' || form.investment_type === 'mixed') && (
                  <Inp label="Cash Investment Amount (\u20A6)" type="number" min="0" step="0.01" value={form.money_amount} onChange={e=>setForm(p=>({...p,money_amount:e.target.value}))}/>
                )}
                {(form.investment_type === 'assets' || form.investment_type === 'mixed') && (<>
                  <Inp label="Asset Market Value (\u20A6)" type="number" min="0" step="0.01" value={form.asset_value} onChange={e=>setForm(p=>({...p,asset_value:e.target.value}))}/>
                  <div className="sm:col-span-2">
                    <Field label="Asset Description">
                      <textarea rows={2} className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-primary-500 outline-none resize-none"
                        value={form.asset_description} onChange={e=>setForm(p=>({...p,asset_description:e.target.value}))} placeholder="Describe the assets contributed..."/>
                    </Field>
                  </div>
                </>)}
                {(form.investment_type === 'intellectual_property' || form.investment_type === 'mixed') && (<>
                  <Inp label="Intellectual Property Value (\u20A6)" type="number" min="0" step="0.01" value={form.intellectual_value} onChange={e=>setForm(p=>({...p,intellectual_value:e.target.value}))}/>
                  <div className="sm:col-span-2">
                    <Field label="Intellectual Property / Knowledge Description">
                      <textarea rows={2} className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-primary-500 outline-none resize-none"
                        value={form.intellectual_description} onChange={e=>setForm(p=>({...p,intellectual_description:e.target.value}))} placeholder="Describe the knowledge, patents, technology..."/>
                    </Field>
                  </div>
                </>)}

                <Inp label="Equity Percentage (%)" type="number" min="0" max="100" step="0.0001" value={form.equity_percentage} onChange={e=>setForm(p=>({...p,equity_percentage:e.target.value}))} placeholder="e.g. 15.5"/>
                <Inp label="Number of Shares" type="number" min="0" value={form.shares_count} onChange={e=>setForm(p=>({...p,shares_count:e.target.value}))}/>
                <Inp label="Share Price (\u20A6)" type="number" min="0" step="0.01" value={form.share_price} onChange={e=>setForm(p=>({...p,share_price:e.target.value}))}/>
                <Inp label="Expected Dividend Rate (%)" type="number" min="0" max="100" step="0.01" value={form.expected_dividend_rate} onChange={e=>setForm(p=>({...p,expected_dividend_rate:e.target.value}))} placeholder="e.g. 8"/>
                <Sel label="Dividend Frequency" value={form.dividend_frequency} onChange={e=>setForm(p=>({...p,dividend_frequency:e.target.value}))}>
                  <option value="monthly">Monthly</option>
                  <option value="quarterly">Quarterly</option>
                  <option value="annually">Annually</option>
                  <option value="on_exit">On Exit</option>
                </Sel>
                <Inp label="Investment Date" type="date" value={form.investment_date} onChange={e=>setForm(p=>({...p,investment_date:e.target.value}))}/>
                <Sel label="Investing In Company" value={form.company_id} onChange={e=>setForm(p=>({...p,company_id:e.target.value}))}>
                  <option value="">— Select company —</option>
                  {companies.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
                </Sel>
                <Sel label="Status" value={form.status} onChange={e=>setForm(p=>({...p,status:e.target.value}))}>
                  <option value="pending">Pending</option>
                  <option value="active">Active</option>
                  <option value="inactive">Inactive</option>
                  <option value="exited">Exited</option>
                </Sel>
                <div className="sm:col-span-2">
                  <Field label="Notes">
                    <textarea rows={3} className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-primary-500 outline-none resize-none"
                      value={form.notes} onChange={e=>setForm(p=>({...p,notes:e.target.value}))} placeholder="Additional notes..."/>
                  </Field>
                </div>
              </div>

              <div className="flex gap-3 pt-2">
                <button type="button" onClick={()=>setShowForm(false)} className="flex-1 px-4 py-2.5 bg-gray-100 text-gray-700 rounded-xl text-sm font-medium">Cancel</button>
                <button type="submit" disabled={saving} className="flex-1 px-4 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl text-sm font-semibold transition-all">
                  {saving ? 'Saving…' : editing ? 'Update Investor' : 'Add Investor'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* ── Detail / Profile Modal ─────────────────────────────────── */}
      {showDetail && selected && (
        <div className="fixed inset-0 z-50 flex items-start justify-center p-4 bg-black/50 overflow-y-auto" onClick={()=>setShowDetail(false)}>
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-2xl my-6" onClick={e=>e.stopPropagation()}>

            {/* Profile Header */}
            <div className="p-6 rounded-t-2xl" style={{ background:'linear-gradient(135deg,#6366f1,#4f46e5)' }}>
              <div className="flex items-start justify-between mb-4">
                <button onClick={()=>setShowDetail(false)} className="text-white/70 hover:text-white"><X size={20}/></button>
              </div>
              <div className="flex items-center gap-5">
                {selected.photo_url ? (
                  <img src={selected.photo_url} className="w-20 h-20 rounded-2xl object-cover border-3 border-white/40"/>
                ) : (
                  <div className="w-20 h-20 rounded-2xl flex items-center justify-center bg-white/20">
                    {selected.entity_type === 'company' ? <Buildings size={36} className="text-white"/> : <User size={36} className="text-white"/>}
                  </div>
                )}
                <div>
                  <h2 className="text-xl font-black text-white">{selected.display_name}</h2>
                  {selected.entity_type === 'company' && selected.name !== selected.company_name && (
                    <p className="text-indigo-200 text-sm">Contact: {selected.name}</p>
                  )}
                  <div className="flex items-center gap-2 mt-2 flex-wrap">
                    <span className="text-xs bg-white/20 text-white px-2 py-0.5 rounded-full capitalize">{(selected.partner_type||'').replace('_',' ')}</span>
                    <span className={`text-xs px-2 py-0.5 rounded-full font-semibold ${STATUS_COLOR[selected.status]}`}>{selected.status}</span>
                    <span className="text-xs text-indigo-200">{selected.investor_number}</span>
                  </div>
                </div>
              </div>
            </div>

            <div className="p-5 space-y-5">
              {/* Contact Info */}
              <div>
                <p className="text-xs font-bold text-gray-400 uppercase tracking-wider mb-3">Contact Information</p>
                <div className="grid grid-cols-2 gap-3">
                  {[
                    { icon: EnvelopeSimple, label:'Email', value: selected.email },
                    { icon: Phone,          label:'Phone', value: selected.phone },
                    { icon: MapPin,         label:'Country', value: selected.country },
                    { icon: IdentificationCard, label:`${selected.id_type?.toUpperCase() || 'ID'}`, value: selected.id_number },
                  ].filter(r=>r.value).map((r,i) => (
                    <div key={i} className="flex items-center gap-2">
                      <r.icon size={16} className="text-gray-400 flex-shrink-0"/>
                      <div>
                        <p className="text-xs text-gray-400">{r.label}</p>
                        <p className="text-sm font-medium text-gray-800">{r.value}</p>
                      </div>
                    </div>
                  ))}
                  {selected.id_document_url && (
                    <a href={selected.id_document_url} target="_blank" rel="noopener noreferrer"
                      className="flex items-center gap-2 text-indigo-600 hover:underline text-sm">
                      <FileText size={16}/> View ID Document
                    </a>
                  )}
                </div>
              </div>

              {/* Investment Summary */}
              <div>
                <p className="text-xs font-bold text-gray-400 uppercase tracking-wider mb-3">Investment Summary</p>
                <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                  {[
                    { label:'Total Invested', value: fmt(selected.total_investment_value), color:'#6366f1' },
                    { label:'Equity',          value: pct(selected.equity_percentage),     color:'#9333ea' },
                    { label:'Shares',          value: Number(selected.shares_count||0).toLocaleString(), color:'#5D4037' },
                    { label:'Share Price',     value: fmt(selected.share_price),           color:'#0891b2' },
                    { label:'Cash Invested',   value: fmt(selected.money_amount),          color:'#10b981' },
                    { label:'Asset Value',     value: fmt(selected.asset_value),           color:'#f59e0b' },
                    { label:'IP Value',        value: fmt(selected.intellectual_value),    color:'#ec4899' },
                    { label:'Dividend Rate',   value: `${pct(selected.expected_dividend_rate)} ${selected.dividend_frequency}`, color:'#84cc16' },
                  ].map((s,i) => (
                    <div key={i} className="rounded-xl p-3" style={{ background: s.color + '12' }}>
                      <p className="text-xs font-medium mb-0.5" style={{ color: s.color }}>{s.label}</p>
                      <p className="font-black text-gray-900 text-sm">{s.value}</p>
                    </div>
                  ))}
                </div>
                {selected.asset_description && (
                  <div className="mt-3 p-3 bg-amber-50 rounded-xl text-sm text-amber-800">
                    <strong>Assets:</strong> {selected.asset_description}
                  </div>
                )}
                {selected.intellectual_description && (
                  <div className="mt-2 p-3 bg-pink-50 rounded-xl text-sm text-pink-800">
                    <strong>Intellectual Property:</strong> {selected.intellectual_description}
                  </div>
                )}
                {selected.notes && (
                  <div className="mt-2 p-3 bg-gray-50 rounded-xl text-sm text-gray-700">
                    <strong>Notes:</strong> {selected.notes}
                  </div>
                )}
              </div>

              {/* Payment Log */}
              <div>
                <div className="flex items-center justify-between mb-3">
                  <p className="text-xs font-bold text-gray-400 uppercase tracking-wider">Payment / Distribution Log</p>
                  <button onClick={() => { setShowPayForm(true); setPayForm(EMPTY_PAY); setPayReceipt(null); }}
                    className="flex items-center gap-1 px-3 py-1.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg text-xs font-semibold">
                    <Plus size={12}/> Log Payment
                  </button>
                </div>

                {showPayForm && (
                  <form onSubmit={handleAddPayment} className="mb-4 bg-indigo-50 rounded-xl p-4 space-y-3">
                    <p className="text-sm font-bold text-indigo-800">Log New Payment</p>
                    <div className="grid grid-cols-2 gap-3">
                      <Sel label="Payment Type" value={payForm.payment_type} onChange={e=>setPayForm(p=>({...p,payment_type:e.target.value}))}>
                        <option value="dividend">Dividend</option>
                        <option value="share_sale">Share Sale</option>
                        <option value="profit_distribution">Profit Distribution</option>
                        <option value="buyback">Buyback</option>
                        <option value="bonus">Bonus</option>
                        <option value="other">Other</option>
                      </Sel>
                      <Inp label="Amount (\u20A6) *" required type="number" min="0.01" step="0.01" value={payForm.amount} onChange={e=>setPayForm(p=>({...p,amount:e.target.value}))}/>
                      <Inp label="Payment Date *" required type="date" value={payForm.payment_date} onChange={e=>setPayForm(p=>({...p,payment_date:e.target.value}))}/>
                      <Inp label="Reference No." value={payForm.reference_number} onChange={e=>setPayForm(p=>({...p,reference_number:e.target.value}))}/>
                      <Sel label="Payment Method" value={payForm.payment_method} onChange={e=>setPayForm(p=>({...p,payment_method:e.target.value}))}>
                        <option value="bank_transfer">Bank Transfer</option>
                        <option value="cheque">Cheque</option>
                        <option value="cash">Cash</option>
                        <option value="crypto">Crypto</option>
                        <option value="other">Other</option>
                      </Sel>
                      <Field label="Receipt (PDF/Image)">
                        <label className="flex items-center gap-2 border border-dashed border-indigo-300 rounded-xl px-3 py-2 cursor-pointer hover:border-indigo-500 transition-colors">
                          <Upload size={14} className="text-indigo-400"/>
                          <span className="text-xs text-indigo-500">{payReceipt ? payReceipt.name : 'Upload receipt'}</span>
                          <input type="file" accept=".pdf,image/*" className="hidden" onChange={e=>{ if(e.target.files[0]) setPayReceipt(e.target.files[0]); }}/>
                        </label>
                      </Field>
                    </div>
                    <Field label="Notes">
                      <textarea rows={2} className="w-full px-3 py-2 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-indigo-500 outline-none resize-none"
                        value={payForm.notes} onChange={e=>setPayForm(p=>({...p,notes:e.target.value}))}/>
                    </Field>
                    <div className="flex gap-2">
                      <button type="button" onClick={()=>setShowPayForm(false)} className="flex-1 px-3 py-2 bg-white text-gray-600 rounded-lg text-xs font-medium">Cancel</button>
                      <button type="submit" disabled={paySaving} className="flex-1 px-3 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg text-xs font-semibold">
                        {paySaving ? 'Saving…' : 'Log Payment'}
                      </button>
                    </div>
                  </form>
                )}

                {payments.length === 0 ? (
                  <p className="text-sm text-gray-400 text-center py-6">No payments logged yet</p>
                ) : (
                  <div className="space-y-2 max-h-64 overflow-y-auto">
                    {payments.map(p => (
                      <div key={p.id} className="flex items-center justify-between bg-gray-50 rounded-xl px-4 py-3">
                        <div>
                          <p className="text-sm font-semibold text-gray-900 capitalize">{p.payment_type?.replace('_',' ')}</p>
                          <p className="text-xs text-gray-500">{fmtD(p.payment_date)} · {p.payment_method} {p.reference_number ? `· Ref: ${p.reference_number}` : ''}</p>
                          {p.notes && <p className="text-xs text-gray-400 mt-0.5">{p.notes}</p>}
                        </div>
                        <div className="text-right">
                          <p className="font-black text-indigo-700">{fmt(p.amount)}</p>
                          {p.receipt_path && (
                            <a href={`/storage/${p.receipt_path}`} target="_blank" rel="noopener noreferrer" className="text-xs text-primary-500 hover:underline">Receipt</a>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                )}
                {payments.length > 0 && (
                  <div className="mt-3 flex items-center justify-between bg-indigo-50 rounded-xl px-4 py-2.5">
                    <span className="text-sm font-semibold text-indigo-700">Total Paid Out</span>
                    <span className="font-black text-indigo-900">{fmt(payments.reduce((s,p)=>s+Number(p.amount),0))}</span>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
