// 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 = {} }) => {
    const [form, setForm]   = React.useState({
        name: '', first_name: '', last_name: '', type: 'business', main_email: '', main_phone: '',
        notes: '', callback_date: '', parent_account_id: '', ...initial,
        // Pre-0011 records may still say 'organization' — normalize on edit.
        ...(initial.type === 'organization' ? { type: 'business' } : {}),
        // Columns are NULL until first save as personal — inputs need strings.
        ...(initial.first_name == null && initial.id ? { first_name: '' } : {}),
        ...(initial.last_name  == null && initial.id ? { last_name: '' }  : {}),
    });
    const [error, setError] = React.useState('');
    const [saving, setSaving] = React.useState(false);

    const set = (key) => (e) => setForm(p => ({ ...p, [key]: e.target.type === 'checkbox' ? e.target.checked : e.target.value }));

    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, ...rest } = form;
            await onSubmit({
                ...rest,
                ...(form.type === 'personal' ? { first_name, last_name } : { name }),
                parent_account_id: form.type === 'business' && form.parent_account_id
                    ? parseInt(form.parent_account_id) : null,
            });
        }
        catch (err) { setError(err.message); setSaving(false); }
    };

    return (
        <form onSubmit={handleSubmit}>
            {error && <div className="api-error"><i className="fas fa-exclamation-circle"></i> {error}</div>}
            <div className="form-grid">
                {/* Type first — it decides whether we ask for a business name or a person's name. */}
                <div className="form-group">
                    <label className="form-label">Type</label>
                    <select className="form-input" value={form.type} onChange={set('type')}>
                        <option value="business">Business</option>
                        <option value="personal">Personal</option>
                    </select>
                </div>
                {form.type === 'personal' ? (
                    <>
                        <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 />
                        </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">Account Name *</label>
                        <input type="text" className="form-input" value={form.name} onChange={set('name')} required />
                    </div>
                )}
                {form.type === 'business' && (
                    <div className="form-group">
                        {/* Server-side search, not a load-every-account select (IMP-1 kin). */}
                        <label className="form-label">Parent Account</label>
                        <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>
                )}
                <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 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 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…</> : <><i className="fas fa-check"></i> {initial.id ? 'Save Changes' : 'Create Account'}</>}
                </button>
            </div>
        </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>
    );
};
