// Leads inbox — website-form leads land here for review (hybrid model:
// exact-email matches to an existing contact were already auto-promoted by
// the server and show under the Promoted filter). Promote → account+contact
// (new, or attach via the type-ahead picker). Dismiss → kept on record.
// Intake API keys are managed in Settings → Website Leads.

const LeadsView = ({ currentUser, onSelectAccount }) => {
    const [leads, setLeads]       = React.useState([]);
    const [loading, setLoading]   = React.useState(true);
    const [statusFilter, setStatusFilter] = React.useState('new');
    const [openLead, setOpenLead] = React.useState(null);   // lead being reviewed
    const [attachTo, setAttachTo] = React.useState('');     // account id for attach-promote
    const [busy, setBusy]         = React.useState(false);
    const [err, setErr]           = React.useState('');

    const load = () => api.getLeads(statusFilter ? { status: statusFilter } : {})
        .then(setLeads).catch(console.error).finally(() => setLoading(false));
    React.useEffect(() => { setLoading(true); load(); }, [statusFilter]);

    const run = async (fn) => {
        setBusy(true); setErr('');
        try { await fn(); await load(); }
        catch (e) { setErr(e.message); }
        finally { setBusy(false); }
    };

    const promote = (lead, accountId) => run(async () => {
        await api.promoteLead(lead.id, accountId ? { account_id: parseInt(accountId) } : {});
        setOpenLead(null); setAttachTo('');
    });
    const dismiss = (lead) => {
        if (!window.confirm('Dismiss this lead? It stays on record but leaves the inbox.')) return;
        run(async () => { await api.dismissLead(lead.id); setOpenLead(null); });
    };

    const typeIcons = { contact: 'fa-envelope-open-text', hardware_spec: 'fa-sliders-h', bug: 'fa-bug', speaker_request: 'fa-volume-up' };
    const spec = openLead?.context?.spec;

    return (
        <div className="view-content">
            <div className="list-view-header">
                <div className="list-view-title"><i className="fas fa-inbox" style={{ marginRight: '0.5rem', color: '#3b82f6' }}></i>Leads</div>
                <div className="list-view-actions">
                    <select className="form-input" style={{ width: 140 }} value={statusFilter} onChange={e => setStatusFilter(e.target.value)}>
                        <option value="new">New</option>
                        <option value="promoted">Promoted</option>
                        <option value="dismissed">Dismissed</option>
                        <option value="">All</option>
                    </select>
                </div>
            </div>

            {err && <div className="api-error">{err}</div>}

            {loading ? <div className="loading-state"><i className="fas fa-spinner fa-spin"></i><p>Loading…</p></div> : (
                <table className="data-table">
                    <thead><tr><th>Received</th><th>Source</th><th>Type</th><th>From</th><th>Message</th><th>Status</th><th></th></tr></thead>
                    <tbody>
                        {leads.length === 0
                            ? <tr><td colSpan={7} style={{ textAlign: 'center', color: 'var(--text-3)', padding: '2rem' }}>
                                {statusFilter === 'new' ? 'Inbox zero — no new leads.' : 'Nothing here.'}
                              </td></tr>
                            : leads.map(l => (
                                <tr key={l.id} className="row-clickable" onClick={() => { setOpenLead(l); setAttachTo(''); }}>
                                    <td style={{ whiteSpace: 'nowrap' }}>{formatDate(l.created_at)}</td>
                                    <td><span className="badge secondary">{l.source}</span></td>
                                    <td><i className={`fas ${typeIcons[l.type] || 'fa-file-alt'}`} style={{ marginRight: '0.35rem', color: 'var(--text-3)' }}></i>{l.type}</td>
                                    <td>
                                        <div style={{ fontWeight: 500 }}>{l.name || '—'}</div>
                                        <div style={{ fontSize: '0.75rem', color: 'var(--text-3)' }}>{l.email || l.phone || ''}</div>
                                    </td>
                                    <td style={{ maxWidth: 320, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{l.message}</td>
                                    <td>
                                        {l.status === 'new' && <span className="badge success">new</span>}
                                        {l.status === 'promoted' && (
                                            <span className="badge" title={l.auto_promoted ? 'Matched an existing contact automatically' : `Promoted by ${l.handled_by_name || '—'}`}>
                                                {l.auto_promoted ? 'auto → ' : '→ '}{l.account_name || 'account'}
                                            </span>
                                        )}
                                        {l.status === 'dismissed' && <span className="badge secondary">dismissed</span>}
                                    </td>
                                    <td onClick={e => e.stopPropagation()}>
                                        {l.status === 'new' && (
                                            <div style={{ display: 'flex', gap: '0.25rem' }}>
                                                <button className="btn-icon-sm" title="Review" onClick={() => { setOpenLead(l); setAttachTo(''); }}><i className="fas fa-folder-open"></i></button>
                                                <button className="btn-icon-sm danger" title="Dismiss" onClick={() => dismiss(l)}><i className="fas fa-times"></i></button>
                                            </div>
                                        )}
                                        {l.status === 'promoted' && l.account_id && onSelectAccount && (
                                            <button className="btn-icon-sm" title="Open account" onClick={() => onSelectAccount({ id: l.account_id })}><i className="fas fa-building"></i></button>
                                        )}
                                    </td>
                                </tr>
                            ))}
                    </tbody>
                </table>
            )}

            {openLead && (
                <div className="modal-overlay" onClick={(e) => e.target === e.currentTarget && setOpenLead(null)}>
                    <div className="modal modal-medium">
                        <div className="modal-header">
                            <h2 className="modal-title">Lead — {openLead.source} · {openLead.type}</h2>
                            <button className="modal-close-btn" onClick={() => setOpenLead(null)}>&times;</button>
                        </div>
                        <div className="modal-body">
                            <div className="form-grid" style={{ marginBottom: '0.75rem' }}>
                                <div className="form-group"><label className="form-label">Name</label><div>{openLead.name || '—'}</div></div>
                                <div className="form-group"><label className="form-label">Email</label><div>{openLead.email || '—'}</div></div>
                                <div className="form-group"><label className="form-label">Phone</label><div>{openLead.phone || '—'}</div></div>
                                <div className="form-group"><label className="form-label">Page</label><div>{openLead.context?.page || '—'}</div></div>
                            </div>
                            <label className="form-label">Message</label>
                            <div style={{ whiteSpace: 'pre-line', marginBottom: '0.75rem' }}>{openLead.message}</div>

                            {spec && (
                                <div style={{ marginBottom: '0.75rem' }}>
                                    <label className="form-label">Spec</label>
                                    {['need', 'use', 'extras'].filter(k => Array.isArray(spec[k]) && spec[k].length).map(k => (
                                        <div key={k} style={{ marginBottom: '0.35rem' }}>
                                            <span style={{ fontSize: '0.75rem', color: 'var(--text-3)', textTransform: 'uppercase', marginRight: '0.5rem' }}>{k}</span>
                                            {spec[k].map((v, i) => <span key={i} className="tag-pill" style={{ marginRight: '0.25rem' }}>{String(v)}</span>)}
                                        </div>
                                    ))}
                                </div>
                            )}

                            {openLead.status === 'new' ? (
                                <div style={{ borderTop: '1px solid var(--border)', paddingTop: '0.75rem' }}>
                                    <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap', alignItems: 'center' }}>
                                        <button className="btn btn-primary" disabled={busy} onClick={() => promote(openLead, null)}>
                                            <i className="fas fa-user-plus"></i> Promote to new account
                                        </button>
                                        <span style={{ color: 'var(--text-3)', fontSize: '0.8125rem' }}>or attach to</span>
                                        <div style={{ minWidth: 220, flex: 1 }}>
                                            <AccountPicker value={attachTo} onChange={(id) => setAttachTo(id)} placeholder="Search existing accounts…" />
                                        </div>
                                        <button className="btn btn-secondary" disabled={busy || !attachTo} onClick={() => promote(openLead, attachTo)}>
                                            <i className="fas fa-link"></i> Attach
                                        </button>
                                        <button className="btn btn-secondary" style={{ color: '#ef4444', marginLeft: 'auto' }} disabled={busy} onClick={() => dismiss(openLead)}>
                                            <i className="fas fa-times"></i> Dismiss
                                        </button>
                                    </div>
                                </div>
                            ) : (
                                <div style={{ color: 'var(--text-3)', fontSize: '0.8125rem' }}>
                                    {openLead.status === 'promoted'
                                        ? `Promoted${openLead.auto_promoted ? ' automatically (matched an existing contact)' : ` by ${openLead.handled_by_name || '—'}`} → ${openLead.account_name || 'account'}`
                                        : `Dismissed by ${openLead.handled_by_name || '—'}`}
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};
