// Send-a-template compose — the rep-facing side of email templates.
//
// Flow: pick template → pick recipient (from the account's contact emails)
// → live rendered preview → optional personal note (if the template carries
// a slot) → send via the rep's own connected mailbox. Locked templates show
// a read-only preview; unlocked ones open the rendered body for editing.
// A merge-field miss (contact has no first name) blocks the send with a
// human answer instead of shipping "Hi ,".

const TemplateSendModal = ({ account, contacts = [], onClose, onSent }) => {
    const [templates, setTemplates]   = React.useState(null);
    const [templateId, setTemplateId] = React.useState('');
    const [recipient, setRecipient]   = React.useState('');   // JSON: {contact_id, email}
    const [note, setNote]             = React.useState('');
    const [preview, setPreview]       = React.useState(null); // server render result
    const [bodyEdit, setBodyEdit]     = React.useState(null); // unlocked templates only
    const [sending, setSending]       = React.useState(false);
    const [error, setError]           = React.useState(null);

    // Every email on every contact of this account, flattened for the picker.
    // Contact email shape is { value, type, is_primary } (see AccountDetailView).
    const recipientOptions = contacts.flatMap(c =>
        (c.emails || []).filter(e => e.value).map(e => ({
            contact_id: c.id,
            email: e.value,
            label: `${c.first_name} ${c.last_name || ''} — ${e.value}${e.is_primary ? ' ★' : ''}`,
        }))
    );

    React.useEffect(() => { api.getTemplates().then(setTemplates).catch(() => setTemplates([])); }, []);

    const selected = templates?.find(t => String(t.id) === String(templateId));
    const chosen   = recipient ? JSON.parse(recipient) : null;

    // Re-render the preview whenever template/recipient/note changes. The
    // note is passed through so the preview is exactly what will arrive.
    React.useEffect(() => {
        setPreview(null); setBodyEdit(null); setError(null);
        if (!selected || !chosen) return;
        let stale = false;
        api.previewTemplate(selected.id, { account_id: account.id, contact_id: chosen.contact_id, note })
            .then(p => { if (!stale) setPreview(p); })
            .catch(err => { if (!stale) setError(err.message); });
        return () => { stale = true; };
    }, [templateId, recipient, note]);

    const handleSend = async () => {
        if (!selected || !chosen) return;
        setSending(true); setError(null);
        try {
            await api.sendTemplate(selected.id, {
                account_id: account.id,
                contact_id: chosen.contact_id,
                to: chosen.email,
                note: note || undefined,
                ...(bodyEdit !== null ? { body_override: bodyEdit } : {}),
            });
            onSent && onSent();
            onClose();
        } catch (err) { setError(err.message); }
        finally { setSending(false); }
    };

    const missing = preview && preview.ok === false ? preview.missing : null;

    return (
        <Modal isOpen={true} title="Send Email" onClose={onClose}>
            {templates === null ? (
                <p style={{ color: 'var(--text-3)' }}><i className="fas fa-spinner fa-spin"></i> Loading templates…</p>
            ) : templates.length === 0 ? (
                <p style={{ color: 'var(--text-3)', fontSize: '0.875rem' }}>
                    No templates yet. An admin or manager can create them in Settings → Email Templates.
                </p>
            ) : (
                <>
                    <div className="form-group">
                        <label className="form-label">Template</label>
                        <select className="form-input" value={templateId} onChange={e => setTemplateId(e.target.value)}>
                            <option value="">Choose a template…</option>
                            {templates.map(t => <option key={t.id} value={t.id}>{t.name}</option>)}
                        </select>
                    </div>
                    <div className="form-group">
                        <label className="form-label">To</label>
                        {recipientOptions.length === 0 ? (
                            <p style={{ color: 'var(--text-3)', fontSize: '0.8125rem' }}>
                                No contact emails on this account — add a contact with an email address first.
                            </p>
                        ) : (
                            <select className="form-input" value={recipient} onChange={e => setRecipient(e.target.value)}>
                                <option value="">Choose a recipient…</option>
                                {recipientOptions.map((o, i) => (
                                    <option key={i} value={JSON.stringify({ contact_id: o.contact_id, email: o.email })}>{o.label}</option>
                                ))}
                            </select>
                        )}
                    </div>

                    {selected && selected.has_note_slot && (
                        <div className="form-group">
                            <label className="form-label">Personal note <span style={{ fontWeight: 400, color: 'var(--text-3)' }}>(optional — drops into the template)</span></label>
                            <textarea className="form-input" rows={2} maxLength={2000} value={note}
                                      onChange={e => setNote(e.target.value)}
                                      placeholder="e.g. It was a blast getting to see the business you built up close." />
                        </div>
                    )}

                    {missing && (
                        <div style={{ background: 'var(--warning-bg, #fef3c7)', border: '1px solid var(--warning-border, #f59e0b55)', borderRadius: 8, padding: '0.625rem 0.875rem', fontSize: '0.8125rem', marginBottom: '1rem' }}>
                            <i className="fas fa-exclamation-triangle" style={{ marginRight: '0.4rem' }}></i>
                            Can't send yet — missing: <strong>{missing.join(', ')}</strong>. Fill those in on the record and this unblocks itself.
                        </div>
                    )}

                    {preview && preview.ok && (
                        <div className="form-group">
                            <label className="form-label">Preview — exactly what will arrive</label>
                            <div style={{ border: '1px solid var(--border)', borderRadius: 8, padding: '0.875rem 1rem', background: 'var(--bg-2, transparent)' }}>
                                <div style={{ fontWeight: 600, fontSize: '0.875rem', marginBottom: '0.5rem' }}>{preview.subject}</div>
                                {preview.locked || bodyEdit === null ? (
                                    <div style={{ fontSize: '0.875rem', whiteSpace: 'pre-wrap', lineHeight: 1.55 }}>{preview.text}</div>
                                ) : (
                                    <textarea className="form-input" rows={10} value={bodyEdit}
                                              onChange={e => setBodyEdit(e.target.value)} style={{ resize: 'vertical' }} />
                                )}
                                {!preview.locked && bodyEdit === null && (
                                    <button className="btn btn-secondary btn-small" style={{ marginTop: '0.625rem' }}
                                            onClick={() => setBodyEdit(preview.text)}>
                                        <i className="fas fa-pen"></i> Edit this email
                                    </button>
                                )}
                            </div>
                            {preview.locked && (
                                <p style={{ fontSize: '0.72rem', color: 'var(--text-3)', marginTop: '0.375rem' }}>
                                    <i className="fas fa-lock" style={{ marginRight: '0.3rem' }}></i>
                                    This template is locked — the personal note is the customizable part.
                                </p>
                            )}
                        </div>
                    )}

                    {error && <p style={{ color: 'var(--danger, #dc2626)', fontSize: '0.8125rem' }}>{error}</p>}

                    <div style={{ display: 'flex', gap: '0.75rem', justifyContent: 'flex-end', marginTop: '1rem' }}>
                        <button className="btn btn-secondary btn-small" onClick={onClose}>Cancel</button>
                        <button className="btn btn-primary btn-small" disabled={sending || !preview || !preview.ok || !chosen}
                                onClick={handleSend}>
                            {sending ? <><i className="fas fa-spinner fa-spin"></i> Sending…</> : <><i className="fas fa-paper-plane"></i> Send</>}
                        </button>
                    </div>
                </>
            )}
        </Modal>
    );
};
