// initialDetailId / onDetailChange: deep-link plumbing — MainApp seeds an open
// doc from the URL and mirrors open/close back into it (ref = quote number).
const QuotesView = ({ currentUser, initialDetailId, onDetailChange }) => {
    const [quotes, setQuotes]   = React.useState([]);
    const [loading, setLoading] = React.useState(true);
    const [statusFilter, setStatusFilter] = React.useState('');
    const [subsOnly, setSubsOnly] = React.useState(false); // subscription docs only (derived from items)
    const [archived, setArchived] = React.useState(false); // cancelled/declined live in the archive
    const [showForm, setShowForm] = React.useState(false); // new-quote form (shared DocFormModal)

    const [detailId, setDetailId] = React.useState(initialDetailId || null); // open quote in the detail modal (id or number)
    const openDetail  = (q) => { setDetailId(q.id); onDetailChange && onDetailChange(q.quote_number || q.id); };
    const closeDetail = () => { setDetailId(null); onDetailChange && onDetailChange(null); };
    // Browser Back/Forward changes the URL → MainApp updates initialDetailId —
    // but the view stays mounted, so the prop must be synced, not just seeded.
    React.useEffect(() => { setDetailId(initialDetailId || null); }, [initialDetailId]);

    // A failed fetch must not render as "No quotes yet" — surface it (swallowed-error rule).
    const [loadError, setLoadError] = React.useState(false);
    // Server-paged (IMP-1): the browser never loads every quote ever written.
    const PAGE = 100;
    const [total, setTotal] = React.useState(0);
    const load = (append) => {
        append = append === true; // guard: load is also an onClick/onChanged callback (first arg = event)
        return api.getQuotes({
            paged: 'true', limit: PAGE, offset: append ? quotes.length : 0,
            ...(statusFilter ? { status: statusFilter } : {}),
            ...(subsOnly ? { subscription: 'true' } : {}),
            ...(archived && !statusFilter ? { archived: 'true' } : {}),
        }).then(({ rows, total }) => {
            setQuotes(p => append ? [...p, ...rows] : rows);
            setTotal(total); setLoadError(false);
        }).catch(() => setLoadError(true)).finally(() => setLoading(false));
    };
    React.useEffect(() => { load(); }, [statusFilter, subsOnly, archived]);

    const handleStatusChange = async (q, status) => {
        try { await api.updateQuote(q.id, { status }); await load(); }
        catch(err) { alert(err.message); }
    };

    const handleDelete = async (q) => {
        if (!window.confirm(`Delete quote ${q.quote_number}?`)) return;
        try { await api.deleteQuote(q.id); await load(); } catch(err) { alert(err.message); }
    };

    const handleConvert = async (q) => {
        if (!window.confirm(`Convert ${q.quote_number} to an invoice?`)) return;
        try { await api.convertQuote(q.id, {}); await load(); alert('Invoice created!'); }
        catch(err) { alert(err.message); }
    };

    const statusColors = { draft: '#475569', sent: '#1d4ed8', accepted: '#065f46', declined: '#991b1b', expired: '#92400e' };

    return (
        <div className="view-content">
            <div className="list-view-header">
                <div className="list-view-title"><i className="fas fa-file-alt" style={{ marginRight: '0.5rem', color: '#3b82f6' }}></i>Quotes</div>
                <div className="list-view-actions">
                    <span className={'tag-pill tag-filter-chip'}
                          style={subsOnly ? { background: 'var(--accent, #3b82f6)', color: '#fff' } : {}}
                          onClick={() => setSubsOnly(v => !v)} title="Only quotes containing a subscription item">
                        <i className="fas fa-rotate" style={{ marginRight: '0.25rem' }}></i>Subscriptions
                    </span>
                    <span className={'tag-pill tag-filter-chip'}
                          style={archived ? { background: 'var(--accent, #3b82f6)', color: '#fff' } : {}}
                          onClick={() => setArchived(v => !v)} title="Cancelled and declined quotes">
                        <i className="fas fa-box-archive" style={{ marginRight: '0.25rem' }}></i>Archived
                    </span>
                    <select className="form-input" style={{ width: 140 }} value={statusFilter} onChange={e => setStatusFilter(e.target.value)}>
                        <option value="">All Statuses</option>
                        {['draft','sent','accepted','declined','expired'].map(s => <option key={s} value={s}>{s.charAt(0).toUpperCase() + s.slice(1)}</option>)}
                    </select>
                    <button className="btn btn-primary btn-small" onClick={() => setShowForm(true)}><i className="fas fa-plus"></i> New Quote</button>
                </div>
            </div>

            {loadError && !loading && (
                <LoadErrorBanner what="quotes" hasData={quotes.length > 0} onRetry={load} />
            )}

            {loading ? <div className="loading-state"><i className="fas fa-spinner fa-spin"></i><p>Loading…</p></div> : (
                <table className="data-table">
                    <thead><tr><th>Quote #</th><th>Account</th><th>Status</th><th>Issue Date</th><th>Expires</th><th>Total</th><th></th></tr></thead>
                    <tbody>
                        {quotes.length === 0
                            ? <tr><td colSpan={7} style={{ textAlign: 'center', color: '#6b7280', padding: '2rem' }}>No quotes yet</td></tr>
                            : quotes.map(q => (
                                <tr key={q.id} className="row-clickable" onClick={() => openDetail(q)}>
                                    <td style={{ fontWeight: 600, fontFamily: 'monospace' }}>
                                        <a className="doc-link" href={'/quotes/' + encodeURIComponent(q.quote_number)}
                                           onClick={(e) => { e.stopPropagation(); navClick(e, () => openDetail(q)); }}>{q.quote_number}</a>
                                        {q.is_subscription && <i className="fas fa-rotate" title="Subscription" style={{ marginLeft: '0.4rem', color: 'var(--accent, #3b82f6)', fontSize: '0.75rem' }}></i>}
                                    </td>
                                    <td>{q.account_name}</td>
                                    <td onClick={e => e.stopPropagation()}>
                                        <select className="inline-select" value={q.status} onChange={e => handleStatusChange(q, e.target.value)} style={{ color: statusColors[q.status] }}>
                                            {['draft','sent','accepted','declined','expired','cancelled'].map(s => <option key={s} value={s}>{s.charAt(0).toUpperCase() + s.slice(1)}</option>)}
                                        </select>
                                    </td>
                                    <td>{formatDate(q.issue_date)}</td>
                                    <td style={{ color: q.expiry_date && new Date(q.expiry_date) < new Date() ? '#ef4444' : '#374151' }}>{q.expiry_date ? formatDate(q.expiry_date) : '—'}</td>
                                    <td style={{ fontWeight: 600 }}>${parseFloat(q.total).toFixed(2)}</td>
                                    <td onClick={e => e.stopPropagation()}>
                                        <div style={{ display: 'flex', gap: '0.25rem' }}>
                                            <button className="btn-icon-sm" title="Open" onClick={() => openDetail(q)}><i className="fas fa-folder-open"></i></button>
                                            <button className="btn-icon-sm" title="Download PDF" onClick={() => api.downloadDocPdf('quote', q.id, `${q.quote_number}.pdf`).catch(err => alert(err.message))}><i className="fas fa-file-pdf"></i></button>
                                            {(q.status === 'draft' || q.status === 'accepted') && currentUser.role !== 'rep' && (
                                                <button className="btn-icon-sm" title="Convert to Invoice" onClick={() => handleConvert(q)}><i className="fas fa-file-invoice"></i></button>
                                            )}
                                            {(q.status === 'draft' || currentUser.role === 'admin') && (
                                                <button className="btn-icon-sm danger"
                                                        title={q.status === 'draft' ? 'Delete draft' : 'Delete quote (admin — audited)'}
                                                        onClick={() => handleDelete(q)}><i className="fas fa-trash"></i></button>
                                            )}
                                        </div>
                                    </td>
                                </tr>
                            ))
                        }
                    </tbody>
                </table>
            )}

            {!loading && quotes.length < total && (
                <div style={{ textAlign: 'center', padding: '0.75rem' }}>
                    <button className="btn btn-secondary btn-small" onClick={() => load(true)}>
                        <i className="fas fa-angles-down"></i> Load more ({quotes.length} of {total})
                    </button>
                </div>
            )}

            {detailId && (
                <DocDetailModal kind="quote" docId={detailId} currentUser={currentUser}
                    onClose={closeDetail} onChanged={load} />
            )}

            {showForm && (
                <DocFormModal kind="quote" onClose={() => setShowForm(false)} onCreated={load} />
            )}
        </div>
    );
};
