// Email Settings — connect/disconnect the user's mailbox + the org-wide
// "never log" exclusion list. Per-user connection, so this lives off the
// top nav (not inside the admin-only panel).
// Messages for the OAuth bounce-back flag (/?email=...). The server keeps the
// real failure reason in its own log on purpose (it can contain provider
// details) — the browser only ever sees these generic outcomes.
const OAUTH_RESULT_MESSAGES = {
    connected: { kind: 'success', text: 'Mailbox connected.' },
    declined:  { kind: 'hint',    text: 'Connection cancelled — nothing was linked.' },
    error:     { kind: 'error',   text: 'Connecting your mailbox failed on the server. ' +
                 'Ask an admin to check the server log (journalctl -u crm) — common causes: ' +
                 'wrong client secret (pasted the secret ID instead of its value), or a redirect URI mismatch.' },
};

const EmailSettingsModal = ({ currentUser, oauthResult, onClose }) => {
    const [status, setStatus]         = React.useState(null);   // null = loading
    const [exclusions, setExclusions] = React.useState([]);
    const [newPattern, setNewPattern] = React.useState('');
    const [newNote, setNewNote]       = React.useState('');
    const [error, setError]           = React.useState('');
    const [busy, setBusy]             = React.useState(false);
    const [syncResult, setSyncResult] = React.useState(null); // { logged, scanned } after Sync now

    const isManager = currentUser.role === 'manager' || currentUser.role === 'admin';
    const oauthMsg  = OAUTH_RESULT_MESSAGES[oauthResult] || null;

    const load = () => {
        api.getEmailStatus().then(setStatus).catch(e => setError(e.message));
        api.getEmailExclusions().then(setExclusions).catch(() => {});
    };
    React.useEffect(load, []);

    const handleConnect = async (provider) => {
        setBusy(true); setError('');
        try {
            const { url } = await api.getEmailConnectUrl(provider);
            // Full-window redirect: Microsoft's consent page bounces back to
            // /api/email/callback, which lands the user back in the app.
            window.location.href = url;
        } catch (e) { setError(e.message); setBusy(false); }
    };

    const handleSyncNow = async () => {
        setBusy(true); setError(''); setSyncResult(null);
        try {
            setSyncResult(await api.syncEmailNow());
            load(); // refresh last_synced_at / any error surfaced on the connection
        } catch (e) { setError(e.message); }
        setBusy(false);
    };

    const handleDisconnect = async () => {
        if (!window.confirm('Disconnect this mailbox? The CRM forgets its access; you can also revoke it from your Microsoft account.')) return;
        setBusy(true); setError('');
        try { await api.disconnectEmail(); load(); } catch (e) { setError(e.message); }
        setBusy(false);
    };

    const handleAddExclusion = async (e) => {
        e.preventDefault();
        if (!newPattern.trim()) return;
        setError('');
        try {
            await api.addEmailExclusion(newPattern.trim(), newNote.trim() || undefined);
            setNewPattern(''); setNewNote('');
            api.getEmailExclusions().then(setExclusions);
        } catch (err) { setError(err.message); }
    };

    const conn = status?.connection;
    const providers = status?.configured_providers || [];

    return (
        <Modal isOpen={true} onClose={onClose} title="Email Settings">
            {oauthMsg && (
                <div style={{
                    background: oauthMsg.kind === 'error' ? '#fef2f2' : oauthMsg.kind === 'success' ? '#f0fdf4' : '#f9fafb',
                    border: `1px solid ${oauthMsg.kind === 'error' ? '#fecaca' : oauthMsg.kind === 'success' ? '#bbf7d0' : '#e5e7eb'}`,
                    color: oauthMsg.kind === 'error' ? '#dc2626' : oauthMsg.kind === 'success' ? '#16a34a' : '#6b7280',
                    padding: '0.75rem 1rem', borderRadius: '0.375rem', fontSize: '0.875rem', marginBottom: '1rem',
                }}>
                    {oauthMsg.text}
                </div>
            )}
            {error && <div className="api-error">{error}</div>}

            <h3 style={{ marginTop: 0 }}>Your mailbox</h3>
            {status === null ? (
                <p>Loading…</p>
            ) : conn ? (
                <div>
                    <p>
                        <i className="fas fa-check-circle" style={{ color: 'var(--success, #16a34a)' }}></i>{' '}
                        Connected: <strong>{conn.email_address}</strong> ({conn.provider})
                        {conn.status !== 'active' && <span> — status: {conn.status}</span>}
                    </p>
                    {conn.last_synced_at && (
                        <p className="form-hint">Last synced: {new Date(conn.last_synced_at).toLocaleString()}</p>
                    )}
                    {conn.last_error && <p className="form-hint">Last error: {conn.last_error}</p>}
                    {syncResult && (
                        <p className="form-hint">
                            {syncResult.skipped
                                ? 'A sync is already running — try again in a moment.'
                                : `Sync complete: ${syncResult.scanned} new message${syncResult.scanned === 1 ? '' : 's'} checked, ${syncResult.logged} logged to contacts.`}
                        </p>
                    )}
                    <div style={{ display: 'flex', gap: '0.5rem' }}>
                        <button className="btn btn-primary" onClick={handleSyncNow} disabled={busy}>
                            <i className="fas fa-sync-alt"></i> Sync now
                        </button>
                        <button className="btn btn-secondary" onClick={handleDisconnect} disabled={busy}>
                            Disconnect
                        </button>
                    </div>
                </div>
            ) : providers.length === 0 ? (
                <p className="form-hint">
                    No mail provider is configured on this server yet — an admin needs to set the
                    provider keys in <code>.env</code> (see <code>docs/EMAIL_SETUP.md</code>).
                </p>
            ) : (
                <div>
                    <p className="form-hint">
                        Connect your mailbox so the CRM can send email as you and (soon) log
                        customer conversations automatically. Only mail matching CRM contacts
                        is ever kept.
                    </p>
                    {providers.includes('microsoft') && (
                        <button className="btn btn-primary" onClick={() => handleConnect('microsoft')} disabled={busy}>
                            <i className="fab fa-microsoft"></i> Connect Microsoft / Outlook
                        </button>
                    )}
                </div>
            )}

            <hr style={{ margin: '1.25rem 0' }} />

            <h3>Never-log list</h3>
            <p className="form-hint">
                Mail to or from these domains/addresses is never logged, even when it matches a
                contact. Your own company domain belongs here.
            </p>
            {exclusions.length === 0
                ? <p className="form-hint"><em>Nothing excluded yet.</em></p>
                : (
                    <ul style={{ listStyle: 'none', padding: 0 }}>
                        {exclusions.map(x => (
                            <li key={x.id} style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', padding: '0.25rem 0' }}>
                                <code>{x.pattern}</code>
                                {x.note && <span className="form-hint">— {x.note}</span>}
                                {isManager && (
                                    <button className="btn-icon" title="Remove"
                                        onClick={() => api.removeEmailExclusion(x.id).then(() => api.getEmailExclusions().then(setExclusions))}>
                                        <i className="fas fa-times"></i>
                                    </button>
                                )}
                            </li>
                        ))}
                    </ul>
                )}
            {isManager && (
                <form onSubmit={handleAddExclusion} style={{ display: 'flex', gap: '0.5rem', marginTop: '0.5rem' }}>
                    <input className="form-input" placeholder="example.com or person@example.com"
                        value={newPattern} onChange={e => setNewPattern(e.target.value)} />
                    <input className="form-input" placeholder="note (optional)"
                        value={newNote} onChange={e => setNewNote(e.target.value)} />
                    <button className="btn btn-secondary" type="submit">Add</button>
                </form>
            )}
        </Modal>
    );
};
