/* Pagina /fornecedores — CRUD pra corporate_payer. */

const { useState, useEffect } = React;


function SuppliersPage() {
    const [list, setList]           = useState(null);
    const [include_inactive, setIncludeInactive] = useState(false);
    const [loading, setLoading]     = useState(true);
    const [error, setError]         = useState(null);
    const [editing, setEditing]     = useState(null);   // null | {} | {id, ...}

    async function load() {
        setLoading(true);
        setError(null);
        try {
            const params = include_inactive ? '?include_inactive=true' : '';
            const data = await window.C7_API.get('/b2b/suppliers' + params);
            setList(data);
        } catch (e) {
            setError(e.message || 'erro ao carregar');
        } finally {
            setLoading(false);
        }
    }

    useEffect(() => { load(); }, [include_inactive]);

    async function on_deactivate(s) {
        if (!confirm('Desativar fornecedor "' + s.nome + '"?')) return;
        try {
            await window.C7_API._request('DELETE', '/b2b/suppliers/' + s.id);
            await load();
        } catch (e) {
            window.C7_Toast.show('Erro: ' + (e.message || 'desconhecido'), 'error');
        }
    }

    async function on_reactivate(s) {
        try {
            await window.C7_API._request('PATCH', '/b2b/suppliers/' + s.id, { ativo: true });
            await load();
        } catch (e) {
            window.C7_Toast.show('Erro: ' + (e.message || 'desconhecido'), 'error');
        }
    }

    const { AppShell } = window.C7_Layout;
    const { Alert }    = window.C7_Forms;

    return (
        <AppShell current_path="/fornecedores">
            <div className="c-card" style={{display:'flex', alignItems:'center', gap:12}}>
                <h2 style={{flex:1, margin:0}}>Fornecedores</h2>
                <label style={{fontSize:12, color:'rgba(200,200,205,0.6)', display:'flex',
                              alignItems:'center', gap:6}}>
                    <input type="checkbox" checked={include_inactive}
                           onChange={e => setIncludeInactive(e.target.checked)} />
                    incluir inativos
                </label>
                <button className="c-btn" onClick={() => setEditing({})}>+ Novo</button>
            </div>

            <Alert kind="error">{error}</Alert>

            {loading && <div className="c-card">
                <p style={{color:'rgba(200,200,205,0.6)'}}>carregando…</p>
            </div>}

            {!loading && list && (
                <div className="c-card">
                    {list.length === 0 ? (
                        <p style={{color:'rgba(200,200,205,0.6)', textAlign:'center', padding:24}}>
                            Nenhum fornecedor cadastrado.{' '}
                            <a href="#" onClick={e => { e.preventDefault(); setEditing({}); }}>
                                Adicionar o primeiro
                            </a>
                        </p>
                    ) : (
                        <table className="c-table">
                            <thead><tr>
                                <th>Nome</th>
                                <th>Documento</th>
                                <th>Wallet</th>
                                <th>Status</th>
                                <th style={{textAlign:'right'}}>Ações</th>
                            </tr></thead>
                            <tbody>
                                {list.map(s => (
                                    <tr key={s.id}>
                                        <td>{s.nome}</td>
                                        <td>{s.doc ? `${s.doc} (${s.doc_type})` : '—'}</td>
                                        <td className="c-mono" style={{fontSize: 11}}>
                                            {s.usdt_wallet.slice(0, 8)}…{s.usdt_wallet.slice(-6)}
                                        </td>
                                        <td>
                                            {s.ativo
                                                ? <span className="c-badge c-badge-ok">ativo</span>
                                                : <span className="c-badge c-badge-muted">inativo</span>}
                                        </td>
                                        <td style={{textAlign:'right', whiteSpace:'nowrap'}}>
                                            <button className="c-btn c-btn-ghost"
                                                    style={{padding:'4px 10px', fontSize:11}}
                                                    onClick={() => setEditing(s)}>
                                                editar
                                            </button>
                                            {' '}
                                            {s.ativo ? (
                                                <button className="c-btn c-btn-ghost"
                                                        style={{padding:'4px 10px', fontSize:11,
                                                                color:'#ff6b6b', borderColor:'rgba(217,54,44,0.4)'}}
                                                        onClick={() => on_deactivate(s)}>
                                                    desativar
                                                </button>
                                            ) : (
                                                <button className="c-btn c-btn-ghost"
                                                        style={{padding:'4px 10px', fontSize:11,
                                                                color:'#51cf66', borderColor:'rgba(55,178,77,0.4)'}}
                                                        onClick={() => on_reactivate(s)}>
                                                    reativar
                                                </button>
                                            )}
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    )}
                </div>
            )}

            {editing && (
                <SupplierModal
                    initial={editing}
                    on_close={() => setEditing(null)}
                    on_saved={() => { setEditing(null); load(); }}
                />
            )}
        </AppShell>
    );
}


function SupplierModal({ initial, on_close, on_saved }) {
    const editing = !!(initial && initial.id);
    const [nome,     setNome]     = useState(initial.nome || '');
    const [wallet,   setWallet]   = useState(initial.usdt_wallet || '');
    const [doc,      setDoc]      = useState(initial.doc || '');
    const [doc_type, setDocType]  = useState(initial.doc_type || 'CPF');
    const [notes,    setNotes]    = useState(initial.notes || '');
    const [loading,  setLoading]  = useState(false);
    const [error,    setError]    = useState(null);

    async function on_submit(e) {
        e.preventDefault();
        setError(null);
        setLoading(true);
        try {
            const payload = {
                nome: nome.trim(),
                doc:  doc.trim() || null,
                doc_type: doc.trim() ? doc_type : null,
                notes: notes.trim() || null,
            };
            if (editing) {
                await window.C7_API._request('PATCH', '/b2b/suppliers/' + initial.id, payload);
            } else {
                payload.usdt_wallet = wallet.trim();
                await window.C7_API.post('/b2b/suppliers', payload);
            }
            on_saved();
        } catch (err) {
            setError(err.message || 'erro');
        } finally {
            setLoading(false);
        }
    }

    const { Field, Alert } = window.C7_Forms;

    return (
        <div className="modal-backdrop" onClick={on_close}>
            <div className="c-card modal-content" onClick={e => e.stopPropagation()}>
                <h2 style={{marginTop: 0}}>{editing ? 'Editar fornecedor' : 'Novo fornecedor'}</h2>
                <Alert kind="error">{error}</Alert>
                <form onSubmit={on_submit}>
                    <Field label="Nome do fornecedor">
                        <input type="text" value={nome}
                               onChange={e => setNome(e.target.value)}
                               required maxLength={150} autoFocus />
                    </Field>
                    <Field label="Wallet USDT (TRC-20)"
                           hint={editing ? 'wallet não pode ser alterada' : 'endereço Tron começando com T'}>
                        <input type="text" value={wallet}
                               onChange={e => setWallet(e.target.value)}
                               required={!editing} disabled={editing}
                               pattern="^T[A-Za-z0-9]{29,63}$"
                               placeholder="T..." />
                    </Field>
                    <div className="c-field-row">
                        <Field label="Tipo de documento">
                            <select value={doc_type}
                                    onChange={e => setDocType(e.target.value)}>
                                <option value="CPF">CPF</option>
                                <option value="CNPJ">CNPJ</option>
                            </select>
                        </Field>
                        <Field label="Documento (opcional)">
                            <input type="text" value={doc}
                                   onChange={e => setDoc(e.target.value)}
                                   maxLength={20}
                                   placeholder="só números" />
                        </Field>
                    </div>
                    <Field label="Notas (opcional)">
                        <textarea value={notes}
                                  onChange={e => setNotes(e.target.value)}
                                  rows={3} maxLength={1000} />
                    </Field>
                    <div style={{display:'flex', gap:10, marginTop: 18}}>
                        <button type="submit" className="c-btn" disabled={loading}>
                            {loading ? 'salvando…' : (editing ? 'Salvar' : 'Criar fornecedor')}
                        </button>
                        <button type="button" className="c-btn c-btn-ghost" onClick={on_close}>
                            Cancelar
                        </button>
                    </div>
                </form>
                <style>{`
                    .modal-backdrop {
                        position: fixed; inset: 0;
                        background: rgba(0,0,0,0.6); backdrop-filter: blur(2px);
                        display: flex; align-items: center; justify-content: center;
                        z-index: 9999; padding: 20px;
                    }
                    .modal-content {
                        width: 100%; max-width: 540px; max-height: 90vh; overflow-y: auto;
                        margin: 0;
                    }
                `}</style>
            </div>
        </div>
    );
}


window.C7_SuppliersPage = SuppliersPage;
