// BUILD pack — the "Components" fold inside a product's edit form (hosted by
// core ProductsView via PACK_UI.productPanels). The BOM is where components
// are born: type a name + value + qty per unit; save replaces the list, and
// any (name, value) the workspace hasn't seen yet becomes a component row on
// the master list automatically.
//
// Own save button (not the product form's): the product save and the BOM
// save are different routes with different roles, and a builder editing a
// BOM shouldn't have to re-submit the whole product. Uses datalist-free
// typeahead: the known names/values come from the master list already
// loaded, so no per-keystroke fetch.

const BomPanel = ({ productId, canEdit }) => {
    const [rows, setRows]       = React.useState([]);
    const [known, setKnown]     = React.useState([]);
    const [dirty, setDirty]     = React.useState(false);
    const [saving, setSaving]   = React.useState(false);
    const [err, setErr]         = React.useState('');
    const [msg, setMsg]         = React.useState('');

    const load = React.useCallback(async () => {
        try {
            const [bom, comps] = await Promise.all([api.getProductBom(productId), api.getComponents()]);
            setRows(bom.map(r => ({ name: r.name, value: r.value, qty: r.qty_per_unit, have: r.qty_on_hand })));
            setKnown(comps);
            setDirty(false); setErr('');
        } catch (e) { setErr(e.message || 'Could not load components.'); }
    }, [productId]);
    React.useEffect(() => { load(); }, [load]);

    const edit = (i, k, v) => { setRows(rs => rs.map((r, j) => j === i ? { ...r, [k]: v } : r)); setDirty(true); setMsg(''); };
    const add  = () => { setRows(rs => [...rs, { name: '', value: '', qty: 1 }]); setDirty(true); };
    const del  = (i) => { setRows(rs => rs.filter((_, j) => j !== i)); setDirty(true); };

    const save = async () => {
        setSaving(true); setErr(''); setMsg('');
        try {
            const items = rows.filter(r => String(r.name).trim()).map(r => ({ name: r.name, value: r.value || '', qty: Number(r.qty) }));
            const saved = await api.saveProductBom(productId, items);
            setRows(saved.map(r => ({ name: r.name, value: r.value, qty: r.qty_per_unit, have: r.qty_on_hand })));
            setDirty(false); setMsg('Components saved.');
            api.getComponents().then(setKnown).catch(() => {});
        } catch (e) { setErr(e.message || 'Save failed.'); }
        setSaving(false);
    };

    // Distinct names, and values seen for the name on the current row.
    const names = [...new Set(known.map(k => k.name))].sort((a, b) => a.localeCompare(b));
    const valuesFor = (name) => known.filter(k => k.name.toLowerCase() === String(name || '').toLowerCase()).map(k => k.value).filter(Boolean);

    return (
        <details className="form-fold full-width" open={rows.length > 0}>
            <summary><span><i className="fas fa-microchip" style={{ marginRight: '0.4rem' }}></i>Components{rows.length ? ` (${rows.length})` : ''}</span></summary>
            <div style={{ padding: '0 0.9rem 0.9rem' }}>
                <p style={{ fontSize: '0.78rem', color: 'var(--text-3)', margin: '0 0 0.5rem' }}>
                    What goes into ONE of these. New parts are added to your Components list as you save.
                </p>
                {err && <div className="api-error">{err}</div>}
                <table className="data-table" style={{ margin: 0, boxShadow: 'none' }}>
                    <thead><tr><th>Part</th><th>Value</th><th style={{ width: 90 }}>Qty each</th><th style={{ width: 90 }}>On hand</th>{canEdit && <th style={{ width: 40 }}></th>}</tr></thead>
                    <tbody>
                        {rows.map((r, i) => (
                            <tr key={i}>
                                <td><input className="form-input" list={`bom-names-${productId}`} value={r.name} disabled={!canEdit}
                                           placeholder="e.g. Resistor" onChange={e => edit(i, 'name', e.target.value)} /></td>
                                <td><input className="form-input" list={`bom-values-${productId}-${i}`} value={r.value || ''} disabled={!canEdit}
                                           placeholder="e.g. 1.2k" onChange={e => edit(i, 'value', e.target.value)} />
                                    <datalist id={`bom-values-${productId}-${i}`}>{valuesFor(r.name).map(v => <option key={v} value={v} />)}</datalist></td>
                                <td><input className="form-input" type="number" min="1" step="1" value={r.qty} disabled={!canEdit}
                                           onChange={e => edit(i, 'qty', e.target.value)} /></td>
                                <td style={{ color: 'var(--text-2)' }}>{r.have ?? '—'}</td>
                                {canEdit && <td><button type="button" className="btn-icon" title="Remove" onClick={() => del(i)}><i className="fas fa-times"></i></button></td>}
                            </tr>
                        ))}
                        {!rows.length && <tr><td colSpan={5} style={{ color: 'var(--text-3)' }}>No components yet.</td></tr>}
                    </tbody>
                </table>
                <datalist id={`bom-names-${productId}`}>{names.map(n => <option key={n} value={n} />)}</datalist>
                {canEdit && (
                    <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center', marginTop: '0.6rem' }}>
                        <button type="button" className="btn btn-secondary btn-small" onClick={add}><i className="fas fa-plus"></i> Add part</button>
                        <button type="button" className="btn btn-primary btn-small" onClick={save} disabled={!dirty || saving}>
                            {saving ? 'Saving…' : 'Save components'}
                        </button>
                        {msg && <span style={{ fontSize: '0.8rem', color: 'var(--success)' }}>{msg}</span>}
                        {dirty && !msg && <span style={{ fontSize: '0.8rem', color: 'var(--text-3)' }}>Unsaved changes</span>}
                    </div>
                )}
            </div>
        </details>
    );
};
