import { useState, useEffect, useCallback } from 'react';
import { fetchLeads, fetchLists, deleteLead, assignLeadList, bulkAssignLeads, fetchLeadCountries } from '../../utils/api';
import LeadModal from './LeadModal';
import Modal from '../UI/Modal';
import Button from '../UI/Button';
import Pagination from './Pagination';
import LeadRow from './LeadRow';
import Badge from '../UI/Badge';

const DEFAULT_PER_PAGE = 20;
const INITIAL_FILTERS  = { search: '', status: '', list_id: '', orderby: 'last_activity', order: 'DESC' };

// Simple status badge
function StatusBadge({ status }) {
  const map = { abandoned: 'red', recovered: 'emerald', submitted: 'indigo', active: 'slate' };
  return <Badge color={map[status] || 'slate'}>{status || '—'}</Badge>;
}

// Basic inline list assign (free)
function ListAssignInline({ lead, lists, onAssign }) {
  const [open, setOpen] = useState(false);
  return (
    <div className="relative">
      <button onClick={() => setOpen(o => !o)}
        className="text-xs border border-slate-300 rounded-lg px-2 py-1 text-slate-600 hover:bg-slate-50 max-w-[100px] truncate">
        {lead.list_name || <span className="text-slate-400 italic">— List —</span>}
      </button>
      {open && (
        <>
          <div className="fixed inset-0 z-10" onClick={() => setOpen(false)} />
          <div className="absolute z-20 left-0 top-full mt-1 w-44 bg-white border border-slate-200 rounded-xl py-1 shadow-lg overflow-hidden">
            <button onClick={() => { onAssign(lead.id, null); setOpen(false); }}
              className="w-full text-left px-3 py-2 text-xs text-slate-500 italic hover:bg-slate-50">Remove from list</button>
            {lists.map(l => (
              <button key={l.id} onClick={() => { onAssign(lead.id, l.id); setOpen(false); }}
                className="w-full text-left flex items-center gap-2 px-3 py-2 text-xs hover:bg-indigo-50 text-slate-700">
                <span className="w-2 h-2 rounded-full shrink-0" style={{ background: l.color || '#6366f1' }} />
                <span className="flex-1 truncate">{l.name}</span>
              </button>
            ))}
          </div>
        </>
      )}
    </div>
  );
}

export default function LeadsTable({ isPro }) {
  const [leads,        setLeads]        = useState([]);
  const [lists,        setLists]        = useState([]);
  const [countries,    setCountries]    = useState([]);
  const [loading,      setLoading]      = useState(true);
  const [total,        setTotal]        = useState(0);
  const [totalPages,   setTotalPages]   = useState(1);
  const [page,         setPage]         = useState(1);
  const [filters,      setFilters]      = useState(INITIAL_FILTERS);
  const [selectedLead, setSelectedLead] = useState(null);
  const [error,        setError]        = useState('');
  const [selected,     setSelected]     = useState(new Set());
  const [bulkListOpen, setBulkListOpen] = useState(false);
  const [bulkAssigning,setBulkAssigning]= useState(false);

  const perPage = DEFAULT_PER_PAGE;

  const load = useCallback(async () => {
    setLoading(true);
    try {
      // Pro can filter by country, status, etc. Free: basic search/status only
      const params = { page, per_page: perPage };
      if (filters.status)  params.status  = filters.status;
      if (filters.search)  params.search  = filters.search;
      if (filters.list_id) params.list_id = filters.list_id;
      if (filters.orderby) params.orderby = filters.orderby;
      if (filters.order)   params.order   = filters.order;

      const data = await fetchLeads(params);
      setLeads(data.data    || []);
      setTotal(data.total   || 0);
      setTotalPages(data.pages || 1);
    } catch (e) {
      setError(e.message);
    } finally {
      setLoading(false);
    }
  }, [filters, page, perPage]);

  useEffect(() => {
    fetchLists().then(d => setLists(d.data || [])).catch(() => {});
    if (isPro) fetchLeadCountries().then(d => setCountries(d.data || [])).catch(() => {});
  }, [isPro]);

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

  const changeFilter = (key, val) => { setPage(1); setFilters(f => ({ ...f, [key]: val })); };

  const handleAssignList = async (leadId, listId) => {
    try { await assignLeadList(leadId, listId); load(); } catch (e) { alert(e.message); }
  };

  const handleDelete = async (lead) => {
    if (!window.confirm(`Delete lead "${lead.email}"?`)) return;
    try { await deleteLead(lead.id); load(); } catch (e) { alert(e.message); }
  };

  const toggleSelect  = (id) => setSelected(s => { const n = new Set(s); n.has(id) ? n.delete(id) : n.add(id); return n; });
  const toggleAll     = ()   => setSelected(s => s.size === leads.length ? new Set() : new Set(leads.map(l => l.id)));

  const handleBulkAssign = async (listId) => {
    setBulkAssigning(true);
    try {
      const res = await bulkAssignLeads(Array.from(selected), listId);
      if (res.success) { setSelected(new Set()); setBulkListOpen(false); load(); }
    } catch (e) { alert(e.message); } finally { setBulkAssigning(false); }
  };

  return (
    <div className="space-y-4 animate-fade-in">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
        <div>
          <h2 className="text-xl font-bold text-slate-900">Leads</h2>
          <p className="text-sm text-slate-500 mt-0.5">
            {total > 0 ? `${total.toLocaleString()} leads captured` : 'Manage your captured and abandoned leads.'}
          </p>
        </div>
        <div className="flex items-center gap-2">
          {/* Bulk assign — available in free too */}
          {selected.size > 0 && (
            <div className="flex items-center gap-2">
              <span className="text-sm text-indigo-600 font-semibold">{selected.size} selected</span>
              <div className="relative">
                <button onClick={() => setBulkListOpen(o => !o)} disabled={bulkAssigning}
                  className="inline-flex items-center gap-1.5 px-3.5 py-2 text-xs font-semibold text-white bg-indigo-600 hover:bg-indigo-700 rounded-lg disabled:opacity-50">
                  {bulkAssigning ? 'Assigning…' : '📋 Assign to List'}
                </button>
                {bulkListOpen && (
                  <>
                    <div className="fixed inset-0 z-10" onClick={() => setBulkListOpen(false)} />
                    <div className="absolute z-20 right-0 top-full mt-1.5 w-52 bg-white border border-slate-200 rounded-xl py-1 shadow-lg overflow-hidden">
                      <button onClick={() => handleBulkAssign(null)} className="w-full text-left px-3.5 py-2 text-xs text-slate-500 italic hover:bg-slate-50">Remove from list</button>
                      <div className="border-t border-slate-100 my-1" />
                      {lists.map(l => (
                        <button key={l.id} onClick={() => handleBulkAssign(l.id)}
                          className="w-full text-left flex items-center gap-2 px-3.5 py-2 text-xs hover:bg-indigo-50 text-slate-700">
                          <span className="w-2 h-2 rounded-full shrink-0" style={{ background: l.color || '#6366f1' }} />
                          <span className="flex-1 truncate">{l.name}</span>
                        </button>
                      ))}
                    </div>
                  </>
                )}
              </div>
            </div>
          )}
          <button onClick={load} className="p-2 border border-slate-300 rounded-lg text-slate-600 hover:bg-slate-50" title="Refresh">
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
            </svg>
          </button>
        </div>
      </div>

      {/* Search + basic status filter (free). Pro gets full FilterBar via addon. */}
      <div className="flex flex-wrap gap-3">
        <div className="relative flex-1 min-w-[200px] max-w-xs">
          <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
          <input type="text" placeholder="Search by email…" value={filters.search}
            onChange={e => changeFilter('search', e.target.value)}
            className="w-full pl-9 pr-3 py-2 text-sm border border-slate-300 rounded-lg outline-none focus:ring-2 focus:ring-indigo-500" />
        </div>
        <select value={filters.status} onChange={e => changeFilter('status', e.target.value)}
          className="border border-slate-300 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-indigo-500">
          <option value="">All Statuses</option>
          <option value="active">Active</option>
          <option value="abandoned">Abandoned</option>
          <option value="recovered">Recovered</option>
          <option value="submitted">Submitted</option>
        </select>
        <select value={filters.list_id} onChange={e => changeFilter('list_id', e.target.value)}
          className="border border-slate-300 rounded-lg px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-indigo-500">
          <option value="">All Lists</option>
          {lists.map(l => <option key={l.id} value={l.id}>{l.name}</option>)}
        </select>
        {!isPro && (
          <span className="text-xs text-slate-400 self-center">
            Advanced filters (country, date) available in <a href={window.rescueFill?.upgradeUrl || 'https://themefreex.com/rescuefill-pro'} target="_blank" rel="noopener noreferrer" className="text-indigo-600 font-semibold hover:underline">Pro</a>.
          </span>
        )}
      </div>

      {error && <p className="text-sm text-red-700 bg-red-50 border border-red-200 rounded-lg px-4 py-3">{error}</p>}

      {/* Table */}
      <div className="bg-white rounded-xl border border-slate-200" style={{ boxShadow: '0 1px 3px rgba(0,0,0,0.06)' }}>
        {loading ? (
          <div className="py-14 flex flex-col items-center gap-3 text-slate-500">
            <div className="rf-spinner" />
            <span className="text-sm">Loading leads…</span>
          </div>
        ) : leads.length === 0 ? (
          <div style={{ display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', padding:'4rem 2rem', textAlign:'center' }}>
            <div style={{ fontSize:'3rem', marginBottom:'1rem', lineHeight:1 }}>👥</div>
            <p style={{ fontSize:'1rem', fontWeight:600, color:'#374151', margin:'0 0 0.375rem 0' }}>No leads captured yet.</p>
            <p style={{ fontSize:'0.875rem', color:'#9ca3af', maxWidth:'300px', lineHeight:1.5, margin:0 }}>
              Leads appear here once visitors start filling out forms on your site.
            </p>
          </div>
        ) : (
          <>
            <div style={{ overflowX:'auto' }}>
              <table className="w-full text-left text-sm" style={{ minWidth:'600px', tableLayout:'auto' }}>
                <thead className="bg-slate-50 border-b border-slate-200">
                  <tr>
                    <th style={{ paddingLeft:'20px', paddingRight:'8px', paddingTop:'12px', paddingBottom:'12px', width:'36px' }}>
                      <input type="checkbox" checked={selected.size === leads.length && leads.length > 0}
                        onChange={toggleAll} className="w-4 h-4 rounded border-slate-300 text-indigo-600" />
                    </th>
                    <th className="px-4 py-3 text-xs font-bold text-slate-500 uppercase tracking-wider">Email / Form</th>
                    <th className="px-4 py-3 text-xs font-bold text-slate-500 uppercase tracking-wider">Status</th>
                    {isPro && <th className="px-4 py-3 text-xs font-bold text-slate-500 uppercase tracking-wider hidden md:table-cell">Location</th>}
                    <th className="px-4 py-3 text-xs font-bold text-slate-500 uppercase tracking-wider">List</th>
                    <th className="px-4 py-3 text-xs font-bold text-slate-500 uppercase tracking-wider hidden lg:table-cell">Activity</th>
                    <th className="px-4 py-3 text-xs font-bold text-slate-500 uppercase tracking-wider" style={{ textAlign:'right' }}>Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {leads.map(lead => (
                    <tr key={lead.id} className={`border-t border-slate-100 hover:bg-slate-50 transition-colors ${selected.has(lead.id) ? 'bg-indigo-50' : ''}`}>
                      <td style={{ paddingLeft:'20px', paddingRight:'8px', paddingTop:'14px', paddingBottom:'14px' }}>
                        <input type="checkbox" checked={selected.has(lead.id)} onChange={() => toggleSelect(lead.id)} className="w-4 h-4 rounded border-slate-300 text-indigo-600" />
                      </td>
                      <td className="px-4 py-3.5">
                        <div className="font-semibold text-slate-900 text-sm">{lead.email}</div>
                        <div className="text-xs text-slate-400 mt-0.5">{lead.form_name || '—'}</div>
                      </td>
                      <td className="px-4 py-3.5"><StatusBadge status={lead.status} /></td>
                      {isPro && (
                        <td className="px-4 py-3.5 hidden md:table-cell">
                          {(lead.country_name || lead.country_code) ? (
                            <div>
                              <div className="text-xs font-medium text-slate-700">{lead.country_name || lead.country_code}</div>
                              {lead.city && <div className="text-xs text-slate-400">{lead.city}{lead.region ? `, ${lead.region}` : ''}</div>}
                            </div>
                          ) : <span className="text-xs text-slate-400">—</span>}
                        </td>
                      )}
                      <td className="px-4 py-3.5">
                        <ListAssignInline lead={lead} lists={lists} onAssign={handleAssignList} />
                      </td>
                      <td className="px-4 py-3.5 hidden lg:table-cell">
                        <div className="text-xs text-slate-500">
                          <div>{lead.last_activity ? new Date(lead.last_activity).toLocaleDateString() : '—'}</div>
                        </div>
                      </td>
                      <td className="px-4 py-3.5" style={{ textAlign:'right' }}>
                        <div style={{ display:'inline-flex', alignItems:'center', gap:'12px', justifyContent:'flex-end' }}>
                          <button onClick={() => setSelectedLead(lead)}
                            style={{ color:'#4f46e5', fontWeight:600, fontSize:'0.75rem', background:'none', border:'none', cursor:'pointer' }}>
                            View
                          </button>
                          <button onClick={() => handleDelete(lead)}
                            style={{ color:'#ef4444', fontWeight:600, fontSize:'0.75rem', background:'none', border:'none', cursor:'pointer' }}>
                            Delete
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            {totalPages > 1 && <Pagination page={page} totalPages={totalPages} total={total} perPage={perPage} onChange={setPage} />}
          </>
        )}
      </div>

      {selectedLead && (
        <Modal isOpen={!!selectedLead} onClose={() => setSelectedLead(null)} title={selectedLead.email} size="2xl"
          footer={<div className="flex justify-end"><Button variant="secondary" onClick={() => setSelectedLead(null)}>Close</Button></div>}>
          <LeadModal lead={selectedLead} isPro={isPro} onClose={() => setSelectedLead(null)}
            onUpdate={() => { setSelectedLead(null); load(); }} />
        </Modal>
      )}
    </div>
  );
}
