const LineItemsEditor = ({ items, setItems, products }) => {
    const addItem = () => setItems(p => [...p, { description: '', quantity: 1, unit_price: 0, product_id: null, total: 0 }]);
    const removeItem = (i) => setItems(p => p.filter((_, idx) => idx !== i));
    const updateItem = (i, key, val) => setItems(p => p.map((row, idx) => {
        if (idx !== i) return row;
        const updated = { ...row, [key]: val };
        if (key === 'product_id' && val) {
            const prod = products.find(p => p.id === parseInt(val));
            if (prod) { updated.description = prod.name; updated.unit_price = parseFloat(prod.unit_price); }
        }
        // parseFloat, not parseInt — quantity is fractional (NUMERIC), and the
        // displayed total must match what the server bills.
        updated.total = parseFloat(updated.quantity || 0) * parseFloat(updated.unit_price || 0);
        return updated;
    }));

    return (
        <div>
            <table className="line-items-table">
                <thead><tr><th style={{ width: '35%' }}>Description</th><th style={{ width: '18%' }}>Product</th><th style={{ width: '10%' }}>Qty</th><th style={{ width: '14%' }}>Unit Price</th><th style={{ width: '14%' }}>Total</th><th style={{ width: '9%' }}></th></tr></thead>
                <tbody>
                    {items.map((row, i) => (
                        <tr key={i}>
                            <td><input value={row.description} onChange={e => updateItem(i, 'description', e.target.value)} placeholder="Item description" /></td>
                            <td>
                                <select value={row.product_id || ''} onChange={e => updateItem(i, 'product_id', e.target.value || null)}>
                                    <option value="">Custom</option>
                                    {products.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
                                </select>
                            </td>
                            <td><input type="number" min="1" step="1" value={row.quantity} onChange={e => updateItem(i, 'quantity', e.target.value)} /></td>
                            <td><input type="number" min="0" step="0.01" value={row.unit_price} onChange={e => updateItem(i, 'unit_price', e.target.value)} /></td>
                            <td style={{ fontWeight: 500 }}>${(parseFloat(row.quantity || 0) * parseFloat(row.unit_price || 0)).toFixed(2)}</td>
                            <td><button type="button" className="btn-icon-sm danger" onClick={() => removeItem(i)}><i className="fas fa-times"></i></button></td>
                        </tr>
                    ))}
                </tbody>
            </table>
            <button type="button" className="btn btn-secondary btn-small" onClick={addItem}><i className="fas fa-plus"></i> Add Line Item</button>
        </div>
    );
};

const TotalsBlock = ({ items, taxRate, onTaxChange }) => {
    const subtotal  = items.reduce((s, i) => s + parseFloat(i.quantity || 0) * parseFloat(i.unit_price || 0), 0);
    const taxAmount = subtotal * (parseFloat(taxRate || 0) / 100);
    const total     = subtotal + taxAmount;
    return (
        <div className="totals-block">
            <div className="totals-row"><span>Subtotal</span><span>${subtotal.toFixed(2)}</span></div>
            <div className="totals-row">
                <span>Tax <input type="number" min="0" max="100" step="0.1" value={taxRate} onChange={e => onTaxChange(e.target.value)} style={{ width: '4rem', padding: '0.2rem 0.4rem', border: '1px solid #d1d5db', borderRadius: '0.25rem', fontSize: '0.8125rem', marginLeft: '0.5rem' }} />%</span>
                <span>${taxAmount.toFixed(2)}</span>
            </div>
            <div className="totals-row total-final"><span>Total</span><span>${total.toFixed(2)}</span></div>
        </div>
    );
};

const QuotesView = ({ accounts, currentUser }) => {
    const [quotes, setQuotes]   = React.useState([]);
    const [loading, setLoading] = React.useState(true);
    const [statusFilter, setStatusFilter] = React.useState('');
    const [showForm, setShowForm] = React.useState(false);
    const [products, setProducts] = React.useState([]);

    // New quote form state
    const [form, setForm]   = React.useState({ account_id: '', contact_id: '', expiry_date: '', notes: '', tax_rate: 0 });
    const [items, setItems] = React.useState([]);
    const [saving, setSaving] = React.useState(false);
    const [formErr, setFormErr] = React.useState('');
    const [contacts, setContacts] = React.useState([]);
    const setF = k => e => setForm(p => ({ ...p, [k]: e.target.value }));

    const load = () => api.getQuotes(statusFilter ? { status: statusFilter } : {}).then(setQuotes).catch(console.error).finally(() => setLoading(false));
    React.useEffect(() => { load(); api.getProducts({ active: 'true' }).then(setProducts).catch(console.error); }, [statusFilter]);
    React.useEffect(() => {
        if (form.account_id) api.getContacts({ account_id: form.account_id }).then(setContacts).catch(console.error);
        else setContacts([]);
    }, [form.account_id]);

    const handleCreate = async (e) => {
        e.preventDefault();
        if (!form.account_id) { setFormErr('Account is required.'); return; }
        setSaving(true); setFormErr('');
        try {
            await api.createQuote({ ...form, account_id: parseInt(form.account_id), contact_id: form.contact_id ? parseInt(form.contact_id) : null, items });
            await load();
            setShowForm(false);
            setForm({ account_id: '', contact_id: '', expiry_date: '', notes: '', tax_rate: 0 });
            setItems([]);
        } catch(err) { setFormErr(err.message); }
        finally { setSaving(false); }
    };

    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 filtered = statusFilter ? quotes.filter(q => q.status === statusFilter) : quotes;

    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">
                    <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>

            {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>
                        {filtered.length === 0
                            ? <tr><td colSpan={7} style={{ textAlign: 'center', color: '#6b7280', padding: '2rem' }}>No quotes yet</td></tr>
                            : filtered.map(q => (
                                <tr key={q.id}>
                                    <td style={{ fontWeight: 600, fontFamily: 'monospace' }}>{q.quote_number}</td>
                                    <td>{q.account_name}</td>
                                    <td>
                                        <select className="inline-select" value={q.status} onChange={e => handleStatusChange(q, e.target.value)} style={{ color: statusColors[q.status] }}>
                                            {['draft','sent','accepted','declined','expired'].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>
                                        <div style={{ display: 'flex', gap: '0.25rem' }}>
                                            {(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>
                                            )}
                                            <button className="btn-icon-sm danger" title="Delete" onClick={() => handleDelete(q)}><i className="fas fa-trash"></i></button>
                                        </div>
                                    </td>
                                </tr>
                            ))
                        }
                    </tbody>
                </table>
            )}

            {/* New quote modal */}
            {showForm && (
                <div className="modal-overlay" onClick={(e) => e.target === e.currentTarget && setShowForm(false)}>
                    <div className="modal builder-modal">
                        <div className="modal-header">
                            <h2 className="modal-title">New Quote</h2>
                            <button className="modal-close-btn" onClick={() => setShowForm(false)}>&times;</button>
                        </div>
                        <div className="modal-body">
                            <form onSubmit={handleCreate}>
                                {formErr && <div className="api-error">{formErr}</div>}
                                <div className="form-grid" style={{ marginBottom: '1.25rem' }}>
                                    <div className="form-group">
                                        <label className="form-label">Account *</label>
                                        <select className="form-input" value={form.account_id} onChange={setF('account_id')} required>
                                            <option value="">— Select —</option>
                                            {accounts.map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
                                        </select>
                                    </div>
                                    <div className="form-group">
                                        <label className="form-label">Contact</label>
                                        <select className="form-input" value={form.contact_id} onChange={setF('contact_id')}>
                                            <option value="">— None —</option>
                                            {contacts.map(c => <option key={c.id} value={c.id}>{c.first_name} {c.last_name}</option>)}
                                        </select>
                                    </div>
                                    <div className="form-group">
                                        <label className="form-label">Expiry Date</label>
                                        <input type="date" className="form-input" value={form.expiry_date} onChange={setF('expiry_date')} />
                                    </div>
                                    <div className="form-group full-width">
                                        <label className="form-label">Notes</label>
                                        <textarea className="form-input" style={{ minHeight: 60 }} value={form.notes} onChange={setF('notes')} />
                                    </div>
                                </div>
                                <h4 style={{ marginBottom: '0.75rem', color: '#374151', fontSize: '0.9375rem' }}>Line Items</h4>
                                <LineItemsEditor items={items} setItems={setItems} products={products} />
                                <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '1rem' }}>
                                    <TotalsBlock items={items} taxRate={form.tax_rate} onTaxChange={v => setForm(p => ({ ...p, tax_rate: v }))} />
                                </div>
                                <div className="btn-group">
                                    <button type="button" className="btn btn-secondary" onClick={() => setShowForm(false)} disabled={saving}>Cancel</button>
                                    <button type="submit" className="btn btn-primary" disabled={saving}>{saving ? <><i className="fas fa-spinner fa-spin"></i> Saving…</> : <><i className="fas fa-check"></i> Create Quote</>}</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};
