// Shared record-entry forms (AccountForm, TaskForm, CommForm) — mounted from
// modals in several views, so they live together as components, not a view.

const AccountForm = ({ onSubmit, onCancel, initial = {}, onDirtyChange }) => {
    const blankPerson = () => ({ first_name: '', last_name: '', email: '', phone: '', title: '' });
    const [form, setForm]   = React.useState({
        name: '', first_name: '', last_name: '', type: 'business', main_email: '', main_phone: '',
        notes: '', callback_date: '', callback_note: '', parent_account_id: '',
        // New business accounts open with ONE person's card already there — the
        // common case is "the business and the person I talked to", so the
        // fields are waiting, not behind a button (owner's call 2026-08-22). An
        // untouched card is dropped on submit, never sent.
        contacts: initial.id ? [] : [blankPerson()],
        ...initial,
        // Pre-0011 records may still say 'organization' — normalize on edit.
        ...(initial.type === 'organization' ? { type: 'business' } : {}),
        // Columns are NULL until first save — inputs need strings.
        ...(initial.first_name == null && initial.id ? { first_name: '' } : {}),
        ...(initial.last_name  == null && initial.id ? { last_name: '' }  : {}),
        ...(initial.callback_note == null && initial.id ? { callback_note: '' } : {}),
    });
    const [error, setError] = React.useState('');
    const [saving, setSaving] = React.useState(false);
    // Dirty = the form differs from what it opened with. Drives the save bar
    // (muted when clean, lit when there's something to save) and lets the
    // host guard navigation so edits can't silently evaporate.
    const pristine = React.useRef(null);
    if (pristine.current === null) pristine.current = JSON.stringify(form);
    const dirty = JSON.stringify(form) !== pristine.current;
    React.useEffect(() => { onDirtyChange?.(dirty); }, [dirty]);
    React.useEffect(() => () => onDirtyChange?.(false), []);   // unmount = nothing pending

    const set = (key) => (e) => setForm(p => ({ ...p, [key]: e.target.type === 'checkbox' ? e.target.checked : e.target.value }));
    const setPerson = (i, key) => (e) => setForm(p => ({
        ...p, contacts: p.contacts.map((c, j) => j === i ? { ...c, [key]: e.target.value } : c),
    }));
    const addPerson = () => setForm(p => ({ ...p, contacts: [...p.contacts, blankPerson()] }));
    // Removing the last card leaves a fresh blank one — the section never
    // collapses to "nothing here, find the button".
    const removePerson = (i) => setForm(p => {
        const next = p.contacts.filter((_, j) => j !== i);
        return { ...p, contacts: next.length ? next : [blankPerson()] };
    });
    const isPersonal = form.type === 'personal';
    const isNew = !initial.id;

    const handleSubmit = async (e) => {
        e.preventDefault();
        setSaving(true); setError('');
        try {
            // A person has no parent org — relationships to businesses are links.
            // People submit first/last (display name is server-derived);
            // businesses submit name (server clears any stale person fields).
            const { name, first_name, last_name, contacts, ...rest } = form;
            // People typed on the create form ride along (business only, new
            // only — existing accounts add people on their Contacts tab). Cards
            // with no first name are dropped, not sent: the always-present blank
            // card shouldn't block saving.
            const people = (isNew && !isPersonal)
                ? contacts.filter(c => c.first_name && c.first_name.trim()) : null;
            await onSubmit({
                ...rest,
                // A note without a date is a note to nobody — it only saves with one.
                callback_note: form.callback_date ? (form.callback_note || null) : null,
                ...(isPersonal ? { first_name, last_name } : { name }),
                parent_account_id: !isPersonal && form.parent_account_id
                    ? parseInt(form.parent_account_id) : null,
                ...(people && people.length ? { contacts: people } : {}),
            });
        }
        catch (err) { setError(err.message); setSaving(false); }
    };

    // One button group, rendered at the TOP for edits (a long form buried
    // Save below the fold — owner, 2026-08-25) and at the bottom for creates
    // (short path, reads as a natural end). Sticky so it stays reachable.
    const buttons = (
        <div className={`btn-group form-save-bar${!isNew ? ' is-top' : ''}${dirty ? ' is-dirty' : ''}`}>
            {!isNew && <span className="form-save-status">{dirty ? 'Unsaved changes' : 'No changes'}</span>}
            <button type="button" className="btn btn-secondary" onClick={onCancel} disabled={saving}>Cancel</button>
            <button type="submit" className="btn btn-primary" disabled={saving || (!isNew && !dirty)}>
                {saving ? <><i className="fas fa-spinner fa-spin"></i> Saving…</> : <><i className="fas fa-check"></i> {isNew ? 'Create Account' : 'Save Changes'}</>}
            </button>
        </div>
    );

    return (
        <form onSubmit={handleSubmit} className="account-form">
            {!isNew && buttons}
            {error && <div className="api-error"><i className="fas fa-exclamation-circle"></i> {error}</div>}

            {/* Type first — it decides the whole shape below. A chip pair, not a
                select (no-checkbox-ui / chip-pairs-for-binary-modes rule). */}
            <div className="form-section account-type-row">
                <label className="form-label">Account type</label>
                <div className="seg-control" role="tablist" aria-label="Account type">
                    <button type="button" role="tab" aria-selected={!isPersonal}
                            className={`seg-btn ${!isPersonal ? 'on' : ''}`}
                            onClick={() => setForm(p => ({ ...p, type: 'business' }))}>
                        <i className="fas fa-building"></i> Business
                    </button>
                    <button type="button" role="tab" aria-selected={isPersonal}
                            className={`seg-btn ${isPersonal ? 'on' : ''}`}
                            onClick={() => setForm(p => ({ ...p, type: 'personal' }))}>
                        <i className="fas fa-user"></i> Personal
                    </button>
                </div>
                <span className="form-hint">
                    {isPersonal ? 'One person — the account is the person.' : 'A company — add the people you deal with below.'}
                </span>
            </div>

            {isPersonal ? (
                <div className="form-section">
                    <h4><i className="fas fa-user"></i> Person</h4>
                    <div className="form-grid">
                        <div className="form-group">
                            <label className="form-label">First name *</label>
                            <input type="text" className="form-input" value={form.first_name} onChange={set('first_name')} required autoFocus={isNew} />
                        </div>
                        <div className="form-group">
                            <label className="form-label">Last name</label>
                            <input type="text" className="form-input" value={form.last_name} onChange={set('last_name')} />
                        </div>
                        <div className="form-group">
                            <label className="form-label">Email</label>
                            <input type="email" className="form-input" value={form.main_email} onChange={set('main_email')} />
                        </div>
                        <div className="form-group">
                            <label className="form-label">Phone</label>
                            <input type="tel" className="form-input" value={form.main_phone} onChange={set('main_phone')} />
                        </div>
                    </div>
                </div>
            ) : (
                <div className="form-section">
                    <h4><i className="fas fa-building"></i> Business</h4>
                    <div className="form-grid">
                        <div className="form-group full-width">
                            <label className="form-label">Business name *</label>
                            <input type="text" className="form-input" value={form.name} onChange={set('name')} required autoFocus={isNew} />
                        </div>
                        <div className="form-group">
                            <label className="form-label">Main email</label>
                            <input type="email" className="form-input" value={form.main_email} onChange={set('main_email')} />
                        </div>
                        <div className="form-group">
                            <label className="form-label">Main phone</label>
                            <input type="tel" className="form-input" value={form.main_phone} onChange={set('main_phone')} />
                        </div>
                    </div>
                </div>
            )}

            {/* People at the business — new accounts only; an existing account
                manages people on its Contacts tab. One card per person, first
                card = primary contact. (Owner + Joe, 2026-08-22: "it didn't let
                you enter a person's name"; same day: one set of fields waiting,
                + to add more, no more five-boxes-in-a-row.) */}
            {!isPersonal && isNew && (
                <div className="form-section">
                    <h4><i className="fas fa-users"></i> People</h4>
                    {form.contacts.map((c, i) => (
                        <div key={i} className="person-card">
                            <div className="person-card-head">
                                <span className="person-card-title">
                                    {i === 0 ? 'Primary contact' : `Person ${i + 1}`}
                                </span>
                                {form.contacts.length > 1 && (
                                    <button type="button" className="btn btn-secondary btn-small" title="Remove this person" onClick={() => removePerson(i)}>
                                        <i className="fas fa-times"></i>
                                    </button>
                                )}
                            </div>
                            <div className="form-grid">
                                <div className="form-group">
                                    <label className="form-label">First name</label>
                                    <input type="text" className="form-input" value={c.first_name} onChange={setPerson(i, 'first_name')} />
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Last name</label>
                                    <input type="text" className="form-input" value={c.last_name} onChange={setPerson(i, 'last_name')} />
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Email</label>
                                    <input type="email" className="form-input" value={c.email} onChange={setPerson(i, 'email')} />
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Phone</label>
                                    <input type="tel" className="form-input" value={c.phone} onChange={setPerson(i, 'phone')} />
                                </div>
                                <div className="form-group full-width">
                                    <label className="form-label">Title / role</label>
                                    <input type="text" className="form-input" placeholder="Owner, Office manager…" value={c.title} onChange={setPerson(i, 'title')} />
                                </div>
                            </div>
                        </div>
                    ))}
                    <button type="button" className="btn btn-secondary btn-small" onClick={addPerson}>
                        <i className="fas fa-plus"></i> Add another person
                    </button>
                </div>
            )}

            <div className="form-section">
                <h4><i className="fas fa-phone"></i> Follow-up</h4>
                <div className="form-grid">
                    <div className="form-group">
                        <label className="form-label">Next follow-up</label>
                        <input type="date" className="form-input" value={form.callback_date || ''} onChange={set('callback_date')} />
                    </div>
                    <div className="form-group">
                        <label className="form-label">What for?</label>
                        <input type="text" className="form-input" maxLength={500}
                               placeholder={form.callback_date ? 'Call about the quote…' : 'Pick a date first'}
                               disabled={!form.callback_date}
                               value={form.callback_note || ''} onChange={set('callback_note')} />
                    </div>
                </div>
            </div>

            <div className="form-section">
                <h4><i className="fas fa-sticky-note"></i> Notes</h4>
                <textarea className="form-input form-textarea" value={form.notes || ''} onChange={set('notes')} />
            </div>

            {/* Parent last — most businesses are top-level, so the rare field
                sits out of the way (owner's call 2026-08-22). */}
            {!isPersonal && (
                <div className="form-section">
                    <h4><i className="fas fa-sitemap"></i> Parent business <span className="form-hint">optional</span></h4>
                    {/* Server-side search, not a load-every-account select (IMP-1 kin). */}
                    <AccountPicker
                        value={form.parent_account_id || ''}
                        initialName={initial.parent_account_name}
                        filters={{ type: 'business' }}
                        excludeId={initial.id}
                        placeholder="Search businesses… (blank = top-level)"
                        onChange={(id) => setForm(p => ({ ...p, parent_account_id: id }))}
                    />
                </div>
            )}

            {isNew && buttons}
        </form>
    );
};

// AccountPicker, not a load-everything <select>: the old accounts prop was the
// server-paged Accounts view page, so off-page accounts were unpickable and the
// default was whatever row sorted first.
const TaskForm = ({ onSubmit, onCancel, initial = {} }) => {
    // Edit mode when initial.id is set — same form both ways (AccountForm pattern).
    const [form, setForm]   = React.useState({
        title:      initial.title || '',
        account_id: initial.account_id || '',
        due_date:   initial.due_date ? String(initial.due_date).slice(0, 10) : '',
        priority:   initial.priority || 'normal',
        task_type:  initial.task_type || 'follow_up',
        notes:      initial.notes || '',
    });
    const [error, setError] = React.useState('');
    const [saving, setSaving] = React.useState(false);
    const set = (key) => (e) => setForm(p => ({ ...p, [key]: e.target.value }));

    const handleSubmit = async (e) => {
        e.preventDefault();
        // The picker isn't a native input, so "required" is enforced here.
        if (!form.account_id) { setError('Pick an account for this task.'); return; }
        setSaving(true); setError('');
        try { await onSubmit({ ...form, account_id: parseInt(form.account_id) }); }
        catch (err) { setError(err.message); setSaving(false); }
    };

    return (
        <form onSubmit={handleSubmit}>
            {error && <div className="api-error">{error}</div>}
            <div className="form-grid">
                <div className="form-group full-width">
                    <label className="form-label">Title *</label>
                    <input type="text" className="form-input" value={form.title} onChange={set('title')} required />
                </div>
                <div className="form-group">
                    <label className="form-label">Account *</label>
                    <AccountPicker value={form.account_id} initialName={initial.account_name} onChange={(id) => setForm(p => ({ ...p, account_id: id }))} />
                </div>
                <div className="form-group">
                    <label className="form-label">Due Date *</label>
                    <input type="date" className="form-input" value={form.due_date} onChange={set('due_date')} required />
                </div>
                <div className="form-group">
                    <label className="form-label">Priority</label>
                    <select className="form-input" value={form.priority} onChange={set('priority')}>
                        <option value="low">Low</option>
                        <option value="normal">Normal</option>
                        <option value="high">High</option>
                        <option value="urgent">Urgent</option>
                    </select>
                </div>
                <div className="form-group">
                    <label className="form-label">Type</label>
                    <select className="form-input" value={form.task_type} onChange={set('task_type')}>
                        <option value="follow_up">Follow Up</option>
                        <option value="check_in">Check In</option>
                        <option value="appointment">Appointment</option>
                        <option value="reminder">Reminder</option>
                        <option value="call">Call</option>
                        <option value="email">Email</option>
                    </select>
                </div>
                <div className="form-group full-width">
                    <label className="form-label">Notes</label>
                    <textarea className="form-input form-textarea" value={form.notes} onChange={set('notes')} />
                </div>
            </div>
            <div className="btn-group">
                <button type="button" className="btn btn-secondary" onClick={onCancel} disabled={saving}>Cancel</button>
                <button type="submit" className="btn btn-primary" disabled={saving}>
                    {saving ? <><i className="fas fa-spinner fa-spin"></i> Saving…</> : initial.id ? <><i className="fas fa-check"></i> Save Changes</> : <><i className="fas fa-plus"></i> Create Task</>}
                </button>
            </div>
        </form>
    );
};

// CommForm is create-only on purpose — the comms log is append-only (owner,
// 2026-08-10): entries record what happened and are never rewritten.
const CommForm = ({ accountId, contacts, onSubmit, onCancel }) => {
    const [form, setForm]   = React.useState({ type: 'phone', direction: 'outbound', subject: '', content: '', contact_id: '' });
    const [error, setError] = React.useState('');
    const [saving, setSaving] = React.useState(false);
    const accountContacts = contacts.filter(c => c.account_id === accountId);
    const set = (key) => (e) => setForm(p => ({ ...p, [key]: e.target.value }));

    const handleSubmit = async (e) => {
        e.preventDefault();
        setSaving(true); setError('');
        try {
            await onSubmit({ ...form, account_id: accountId, contact_id: form.contact_id ? parseInt(form.contact_id) : null });
        } catch (err) { setError(err.message); setSaving(false); }
    };

    return (
        <form onSubmit={handleSubmit}>
            {error && <div className="api-error">{error}</div>}
            <div className="form-grid">
                <div className="form-group">
                    <label className="form-label">Type</label>
                    <select className="form-input" value={form.type} onChange={set('type')}>
                        <option value="phone">Phone</option>
                        <option value="email">Email</option>
                        <option value="meeting">Meeting</option>
                        <option value="note">Note</option>
                        <option value="sms">SMS</option>
                    </select>
                </div>
                <div className="form-group">
                    <label className="form-label">Direction</label>
                    <select className="form-input" value={form.direction} onChange={set('direction')}>
                        <option value="outbound">Outbound</option>
                        <option value="inbound">Inbound</option>
                        <option value="internal">Internal</option>
                    </select>
                </div>
                {accountContacts.length > 0 && (
                    <div className="form-group full-width">
                        <label className="form-label">Contact (optional)</label>
                        <select className="form-input" value={form.contact_id} onChange={set('contact_id')}>
                            <option value="">— None —</option>
                            {accountContacts.map(c => <option key={c.id} value={c.id}>{c.first_name} {c.last_name}</option>)}
                        </select>
                    </div>
                )}
                <div className="form-group full-width">
                    <label className="form-label">Subject</label>
                    <input type="text" className="form-input" value={form.subject} onChange={set('subject')} />
                </div>
                <div className="form-group full-width">
                    <label className="form-label">Notes / Content</label>
                    <textarea className="form-input form-textarea" value={form.content} onChange={set('content')} />
                </div>
            </div>
            <div className="btn-group">
                <button type="button" className="btn btn-secondary" onClick={onCancel} 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-plus"></i> Log Communication</>}
                </button>
            </div>
        </form>
    );
};
