// New Quote / New Invoice form — ONE implementation for both doc kinds and
// both entry points (the global Billing lists and an account's Quotes &
// Invoices tab). Extracted from QuotesView/InvoicesView, which each carried
// their own copy; the account-detail entry point made it three callers.
//
// lockedAccount: pass { id, name } to pin the doc to a known account — the
// picker is replaced by a static label so you can't file the doc under the
// wrong customer from inside their record.

const DOC_FORM_KIND = {
    quote:   { noun: 'Quote',   dateKey: 'expiry_date', dateLabel: 'Expiry Date' },
    invoice: { noun: 'Invoice', dateKey: 'due_date',    dateLabel: 'Due Date'    },
};

const DocFormModal = ({ kind, lockedAccount, onClose, onCreated }) => {
    const K = DOC_FORM_KIND[kind];
    const [form, setForm] = React.useState({
        account_id: lockedAccount ? String(lockedAccount.id) : '',
        contact_id: '', [K.dateKey]: '', 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 [products, setProducts] = React.useState([]);
    const setF = k => e => setForm(p => ({ ...p, [k]: e.target.value }));

    React.useEffect(() => { api.getProducts({ active: 'true' }).then(setProducts).catch(console.error); }, []);
    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 {
            const create = kind === 'quote' ? api.createQuote : api.createInvoice;
            const doc = await create({
                ...form,
                account_id: parseInt(form.account_id),
                contact_id: form.contact_id ? parseInt(form.contact_id) : null,
                items,
            });
            onCreated && onCreated(doc);
            onClose();
        } catch (err) { setFormErr(err.message); setSaving(false); }
    };

    return (
        <div className="modal-overlay" onClick={(e) => e.target === e.currentTarget && onClose()}>
            <div className="modal builder-modal">
                <div className="modal-header">
                    <h2 className="modal-title">New {K.noun}{lockedAccount ? ` — ${lockedAccount.name}` : ''}</h2>
                    <button className="modal-close-btn" onClick={onClose}>&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' }}>
                            {!lockedAccount && (
                                <div className="form-group">
                                    <label className="form-label">Account *</label>
                                    <AccountPicker value={form.account_id} onChange={(id) => setForm(p => ({ ...p, account_id: id, contact_id: '' }))} />
                                </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">{K.dateLabel}</label>
                                <input type="date" className="form-input" value={form[K.dateKey]} onChange={setF(K.dateKey)} />
                            </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={onClose} 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 {K.noun}</>}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    );
};
