const ContactEditModal = ({ contact, accountId, onSave, onClose }) => {
    const isNew = !contact;
    const [form, setForm] = React.useState({
        first_name:  contact?.first_name  || '',
        last_name:   contact?.last_name   || '',
        title:       contact?.title       || '',
        role:        contact?.role        || '',
        department:  contact?.department  || '',
        location:    contact?.location    || '',
        notes:       contact?.notes       || '',
        is_primary:  contact?.is_primary  || false,
    });
    const [emails, setEmails] = React.useState(contact?.emails ? [...contact.emails] : []);
    const [phones, setPhones] = React.useState(contact?.phones ? [...contact.phones] : []);
    const [saving, setSaving] = React.useState(false);
    const [error,  setError]  = React.useState('');

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

    const addEmail = () => setEmails(p => [...p, { value: '', type: 'work', is_primary: p.length === 0, _new: true }]);
    const addPhone = () => setPhones(p => [...p, { value: '', type: 'work', is_primary: p.length === 0, _new: true }]);

    const updateEmail = (i, k, v) => setEmails(p => p.map((e, idx) => idx === i ? { ...e, [k]: v } : e));
    const updatePhone = (i, k, v) => setPhones(p => p.map((ph, idx) => idx === i ? { ...ph, [k]: v } : ph));

    const removeEmail = async (i) => {
        const e = emails[i];
        if (!e._new && e.id && !isNew) await api.deleteContactEmail(contact.id, e.id).catch(console.error);
        setEmails(p => p.filter((_, idx) => idx !== i));
    };
    const removePhone = async (i) => {
        const ph = phones[i];
        if (!ph._new && ph.id && !isNew) await api.deleteContactPhone(contact.id, ph.id).catch(console.error);
        setPhones(p => p.filter((_, idx) => idx !== i));
    };

    const handleSave = async (e) => {
        e.preventDefault();
        if (!form.first_name.trim()) { setError('First name is required.'); return; }
        setSaving(true); setError('');
        try {
            let contactId;
            if (isNew) {
                const created = await api.createContact({ ...form, account_id: accountId });
                contactId = created.id;
            } else {
                await api.updateContact(contact.id, form);
                contactId = contact.id;
            }

            // Sync emails
            for (const em of emails) {
                if (!em.value.trim()) continue;
                if (em._new || isNew) {
                    await api.addContactEmail(contactId, { value: em.value, type: em.type, is_primary: em.is_primary });
                } else if (em.id) {
                    await api.updateContactEmail(contactId, em.id, { value: em.value, type: em.type, is_primary: em.is_primary });
                }
            }
            // Sync phones
            for (const ph of phones) {
                if (!ph.value.trim()) continue;
                if (ph._new || isNew) {
                    await api.addContactPhone(contactId, { value: ph.value, type: ph.type, is_primary: ph.is_primary });
                } else if (ph.id) {
                    await api.updateContactPhone(contactId, ph.id, { value: ph.value, type: ph.type, is_primary: ph.is_primary });
                }
            }

            await onSave();
            onClose();
        } catch (err) {
            setError(err.message);
        } finally {
            setSaving(false);
        }
    };

    return (
        <div className="modal-overlay" onClick={(e) => e.target === e.currentTarget && onClose()}>
            <div className="modal modal-medium">
                <div className="modal-header">
                    <h2 className="modal-title">{isNew ? 'New Contact' : `Edit: ${contact.first_name} ${contact.last_name || ''}`}</h2>
                    <button className="modal-close-btn" onClick={onClose}>&times;</button>
                </div>
                <div className="modal-body">
                    <form onSubmit={handleSave}>
                        {error && <div className="api-error">{error}</div>}

                        <div className="form-section">
                            <h4>Contact Info</h4>
                            <div className="form-grid">
                                <div className="form-group">
                                    <label className="form-label">First Name *</label>
                                    <input className="form-input" value={form.first_name} onChange={set('first_name')} required autoFocus />
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Last Name</label>
                                    <input className="form-input" value={form.last_name} onChange={set('last_name')} />
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Title</label>
                                    <input className="form-input" value={form.title} onChange={set('title')} placeholder="e.g. Pastor, Principal" />
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Role</label>
                                    <input className="form-input" value={form.role} onChange={set('role')} placeholder="e.g. treasurer, coordinator" />
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Department</label>
                                    <input className="form-input" value={form.department} onChange={set('department')} />
                                </div>
                                <div className="form-group">
                                    <label className="form-label">Location / Office</label>
                                    <input className="form-input" value={form.location} onChange={set('location')} />
                                </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')} style={{ minHeight: 60 }} />
                                </div>
                                <div className="form-group">
                                    <label style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', cursor: 'pointer', marginTop: '0.25rem' }}>
                                        <input type="checkbox" checked={form.is_primary} onChange={set('is_primary')} /> Primary Contact
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div className="form-section">
                            <h4>Email Addresses</h4>
                            {emails.map((em, i) => (
                                <div key={i} className="ep-row">
                                    <input value={em.value} onChange={e => updateEmail(i, 'value', e.target.value)} placeholder="email@example.com" type="email" />
                                    <select value={em.type} onChange={e => updateEmail(i, 'type', e.target.value)}>
                                        <option value="work">Work</option>
                                        <option value="personal">Personal</option>
                                        <option value="other">Other</option>
                                    </select>
                                    <label style={{ display: 'flex', alignItems: 'center', gap: '0.25rem', fontSize: '0.8125rem', whiteSpace: 'nowrap', cursor: 'pointer' }}>
                                        <input type="checkbox" checked={em.is_primary} onChange={e => updateEmail(i, 'is_primary', e.target.checked)} /> Primary
                                    </label>
                                    <button type="button" className="btn-icon-sm danger" onClick={() => removeEmail(i)}><i className="fas fa-times"></i></button>
                                </div>
                            ))}
                            <button type="button" className="btn btn-secondary btn-small" onClick={addEmail}><i className="fas fa-plus"></i> Add Email</button>
                        </div>

                        <div className="form-section">
                            <h4>Phone Numbers</h4>
                            {phones.map((ph, i) => (
                                <div key={i} className="ep-row">
                                    <input value={ph.value} onChange={e => updatePhone(i, 'value', e.target.value)} placeholder="555-0100" type="tel" />
                                    <select value={ph.type} onChange={e => updatePhone(i, 'type', e.target.value)}>
                                        <option value="work">Work</option>
                                        <option value="mobile">Mobile</option>
                                        <option value="home">Home</option>
                                        <option value="other">Other</option>
                                    </select>
                                    <label style={{ display: 'flex', alignItems: 'center', gap: '0.25rem', fontSize: '0.8125rem', whiteSpace: 'nowrap', cursor: 'pointer' }}>
                                        <input type="checkbox" checked={ph.is_primary} onChange={e => updatePhone(i, 'is_primary', e.target.checked)} /> Primary
                                    </label>
                                    <button type="button" className="btn-icon-sm danger" onClick={() => removePhone(i)}><i className="fas fa-times"></i></button>
                                </div>
                            ))}
                            <button type="button" className="btn btn-secondary btn-small" onClick={addPhone}><i className="fas fa-plus"></i> Add Phone</button>
                        </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> {isNew ? 'Create Contact' : 'Save Changes'}</>}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    );
};
