// Users — invite/manage teammates + bulk account reassignment.
// Migrated from the old AdminPanel drawer (Users + Reassign tabs merged:
// moving accounts between reps IS user management, and one card reads
// better than two on the settings home).

const UsersSection = ({ currentUser, onUsersChange }) => {
    const [users, setUsers]     = React.useState([]);
    const [loading, setLoading] = React.useState(true);
    const [showCreateForm, setShowCreateForm] = React.useState(false);
    const [savingId, setSavingId] = React.useState(null);

    const [fromUser, setFromUser] = React.useState('');
    const [toUser, setToUser]     = React.useState('');
    const [reassigning, setReassigning] = React.useState(false);
    const [reassignResult, setReassignResult] = React.useState(null); // { ok, message } | null

    // onUsersChange keeps the settings home's "N active users" status line
    // honest after invites/deactivations made here.
    const refreshUsers = () => api.getUsers()
        .then(u => { setUsers(u); onUsersChange && onUsersChange(u); })
        .catch(console.error);
    React.useEffect(() => { refreshUsers().finally(() => setLoading(false)); }, []);

    const handleRoleChange = async (userId, newRole) => {
        setSavingId(userId);
        try { await api.updateUser(userId, { role: newRole }); await refreshUsers(); }
        catch (e) { alert('Error: ' + e.message); }
        finally { setSavingId(null); }
    };

    const handleToggleActive = async (user) => {
        setSavingId(user.id);
        try { await api.updateUser(user.id, { is_active: !user.is_active }); await refreshUsers(); }
        catch (e) { alert('Error: ' + e.message); }
        finally { setSavingId(null); }
    };

    const handleCreateUser = async (formData) => {
        const result = await api.createUser(formData);
        await refreshUsers();
        // Invite mode keeps the form open to display the one-time activation
        // link; password mode is done immediately.
        if (!result.invite_url) setShowCreateForm(false);
        return result;
    };

    const handleReinviteUser = async (user) => {
        try {
            const r = await api.reinviteUser(user.id);
            // Email went out from the admin's connected mailbox — nothing to copy.
            // No mailbox (or send hiccup) → fall back to the manual copy prompt.
            if (r.email && r.email.sent) {
                alert(`Fresh invite emailed to ${user.first_name} from ${r.email.from}. Link is single-use and expires in 7 days.`);
            } else {
                window.prompt(`Fresh activation link for ${user.first_name} (single-use, 7 days) — copy it:`, r.invite_url);
            }
        } catch (err) { alert(err.message); }
    };

    const handleResetLink = async (user) => {
        try {
            const r = await api.resetLinkUser(user.id);
            // Same email-or-copy contract as re-invite; reset links are short-
            // lived on purpose (they prove account ownership).
            if (r.email && r.email.sent) {
                alert(`Password-reset link emailed to ${user.first_name} from ${r.email.from}. Link is single-use and expires in 1 hour.`);
            } else {
                window.prompt(`Password-reset link for ${user.first_name} (single-use, 1 hour) — copy it:`, r.reset_url);
            }
        } catch (err) { alert(err.message); }
    };

    const handleCancelInvite = async (user) => {
        if (!window.confirm(`Cancel the invite for ${user.first_name} ${user.last_name}? Their activation link stops working and ${user.email} becomes usable again.`)) return;
        setSavingId(user.id);
        try { await api.cancelInvite(user.id); await refreshUsers(); }
        catch (e) { alert(e.message); }
        finally { setSavingId(null); }
    };

    const handleBulkReassign = async () => {
        if (!fromUser || !toUser) return;
        if (fromUser === toUser) { setReassignResult({ ok: false, message: 'Source and destination must be different.' }); return; }
        if (!window.confirm(`Move all accounts from the selected rep to the new owner?`)) return;
        setReassigning(true); setReassignResult(null);
        try {
            const r = await api.bulkReassign(parseInt(fromUser), parseInt(toUser));
            setReassignResult({ ok: true, message: r.message });
            await refreshUsers();
        } catch (e) { setReassignResult({ ok: false, message: e.message }); }
        finally { setReassigning(false); }
    };

    const activeUsers = users.filter(u => u.is_active);

    if (loading) return <div className="loading-state"><i className="fas fa-spinner fa-spin"></i>Loading…</div>;

    return (
        <div className="settings-form">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1rem' }}>
                <p style={{ fontSize: '0.875rem', color: 'var(--text-3)' }}>{users.length} users · {activeUsers.length} active</p>
                <button className="btn btn-primary btn-small" onClick={() => setShowCreateForm(s => !s)}>
                    <i className={`fas ${showCreateForm ? 'fa-times' : 'fa-plus'}`}></i>
                    {showCreateForm ? 'Cancel' : 'New User'}
                </button>
            </div>

            {showCreateForm && (
                <div className="admin-form-card">
                    <h4 style={{ marginBottom: '1rem' }}><i className="fas fa-user-plus" style={{ marginRight: '0.375rem' }}></i>Create New User</h4>
                    <CreateUserForm onSubmit={handleCreateUser} onCancel={() => setShowCreateForm(false)} />
                </div>
            )}

            <table className="user-table">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Role</th>
                        <th>Accounts</th>
                        <th>Status</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    {users.map(user => (
                        <tr key={user.id} className={!user.is_active ? 'inactive' : ''}>
                            <td style={{ fontWeight: 500 }}>{user.first_name} {user.last_name}</td>
                            <td style={{ color: 'var(--text-3)', fontSize: '0.8125rem' }}>{user.email}</td>
                            <td>
                                {currentUser.id === user.id ? (
                                    <span className={`role-badge ${user.role}`}>{user.role}</span>
                                ) : (
                                    <select
                                        className="inline-select"
                                        value={user.role}
                                        onChange={(e) => handleRoleChange(user.id, e.target.value)}
                                        disabled={savingId === user.id}
                                    >
                                        <option value="rep">rep</option>
                                        <option value="manager">manager</option>
                                        <option value="admin">admin</option>
                                    </select>
                                )}
                            </td>
                            <td style={{ color: 'var(--text)', fontWeight: 500 }}>{user.account_count || 0}</td>
                            <td>
                                <span style={{ fontSize: '0.75rem', color: user.invite_pending ? 'var(--warning)' : user.is_active ? 'var(--success)' : 'var(--text-3)', fontWeight: 500 }}>
                                    {user.invite_pending ? '◐ Invited' : user.is_active ? '● Active' : '○ Inactive'}
                                </span>
                            </td>
                            <td>
                                {user.invite_pending ? (
                                    <>
                                        <button
                                            className="btn-icon-sm"
                                            title="Resend the invite (email or fresh link)"
                                            onClick={() => handleReinviteUser(user)}
                                        >
                                            <i className="fas fa-envelope-open-text"></i>
                                        </button>
                                        <button
                                            className="btn-icon-sm danger"
                                            title="Cancel this invite (frees the email address)"
                                            onClick={() => handleCancelInvite(user)}
                                            disabled={savingId === user.id}
                                        >
                                            <i className="fas fa-user-xmark"></i>
                                        </button>
                                    </>
                                ) : user.is_active && (
                                    <button
                                        className="btn-icon-sm"
                                        title="Send a password-reset link (email or copy)"
                                        onClick={() => handleResetLink(user)}
                                    >
                                        <i className="fas fa-key"></i>
                                    </button>
                                )}
                                {currentUser.id !== user.id && (
                                    <button
                                        className="btn-icon-sm danger"
                                        title={user.is_active ? 'Deactivate user' : 'Reactivate user'}
                                        onClick={() => handleToggleActive(user)}
                                        disabled={savingId === user.id}
                                    >
                                        {savingId === user.id
                                            ? <i className="fas fa-spinner fa-spin"></i>
                                            : <i className={`fas ${user.is_active ? 'fa-user-slash' : 'fa-user-check'}`}></i>}
                                    </button>
                                )}
                            </td>
                        </tr>
                    ))}
                </tbody>
            </table>

            <div className="reassign-box">
                <h4><i className="fas fa-exchange-alt"></i>Move accounts between reps</h4>
                <p style={{ fontSize: '0.8125rem', color: 'var(--text-3)', marginBottom: '1rem' }}>
                    Useful when someone leaves the team or territories change.
                </p>
                <div className="reassign-row">
                    <div className="form-group" style={{ flex: 1, minWidth: 180 }}>
                        <label className="form-label">Move accounts FROM</label>
                        <select className="form-input" value={fromUser} onChange={e => { setFromUser(e.target.value); setReassignResult(''); }}>
                            <option value="">— Select rep —</option>
                            {users.map(u => (
                                <option key={u.id} value={u.id}>{u.first_name} {u.last_name} ({u.account_count || 0} accounts)</option>
                            ))}
                        </select>
                    </div>
                    <div style={{ paddingBottom: '0.25rem', color: 'var(--text-3)' }}><i className="fas fa-arrow-right"></i></div>
                    <div className="form-group" style={{ flex: 1, minWidth: 180 }}>
                        <label className="form-label">Assign TO</label>
                        <select className="form-input" value={toUser} onChange={e => { setToUser(e.target.value); setReassignResult(''); }}>
                            <option value="">— Select rep —</option>
                            {users.filter(u => u.is_active).map(u => (
                                <option key={u.id} value={u.id}>{u.first_name} {u.last_name}</option>
                            ))}
                        </select>
                    </div>
                    <div style={{ paddingBottom: '0.25rem' }}>
                        <button
                            className="btn btn-primary"
                            onClick={handleBulkReassign}
                            disabled={!fromUser || !toUser || reassigning}
                        >
                            {reassigning ? <><i className="fas fa-spinner fa-spin"></i> Moving…</> : <><i className="fas fa-exchange-alt"></i> Reassign</>}
                        </button>
                    </div>
                </div>
                {reassignResult && (
                    <div className={`note-box ${reassignResult.ok ? 'success' : 'danger'}`} style={{ marginTop: '0.75rem' }}>
                        {reassignResult.message}
                    </div>
                )}
            </div>
        </div>
    );
};

const CreateUserForm = ({ onSubmit, onCancel }) => {
    const [form, setForm]   = React.useState({ email: '', first_name: '', last_name: '', role: 'rep', password: '' });
    // 'invite' (default): no password — the response carries an activation
    // link the new user opens to set their own. 'password': classic create.
    const [mode, setMode]   = React.useState('invite');
    // Auto-email the invite from the admin's connected mailbox (on by
    // default). The link is always shown too — email is best-effort.
    const [sendEmail, setSendEmail] = React.useState(true);
    const [inviteResult, setInviteResult] = React.useState(null);   // { url, email }
    const [error, setError] = React.useState('');
    const [saving, setSaving] = React.useState(false);
    const set = (k) => (e) => setForm(p => ({ ...p, [k]: e.target.value }));

    const handleSubmit = async (e) => {
        e.preventDefault();
        if (mode === 'password' && form.password.length < 12) { setError('Password must be at least 12 characters.'); return; }
        setSaving(true); setError('');
        try {
            const payload = { ...form };
            if (mode === 'invite') { delete payload.password; payload.send_email = sendEmail; }
            const result = await onSubmit(payload);
            if (result && result.invite_url) { setInviteResult({ url: result.invite_url, email: result.email }); setSaving(false); }
        }
        catch (err) { setError(err.message); setSaving(false); }
    };

    if (inviteResult) {
        const em = inviteResult.email;
        const inviteUrl = inviteResult.url;
        return (
            <div>
                {em && em.sent ? (
                    <p style={{ fontSize: '0.875rem', marginBottom: '0.5rem' }}>
                        <i className="fas fa-check-circle" style={{ color: 'var(--success)', marginRight: '0.375rem' }}></i>
                        Invite emailed to <strong>{form.email}</strong> from {em.from}. Backup link (single-use, 7 days):
                    </p>
                ) : em && em.reason === 'no_mailbox' ? (
                    <p style={{ fontSize: '0.875rem', marginBottom: '0.5rem' }}>
                        <i className="fas fa-check-circle" style={{ color: 'var(--success)', marginRight: '0.375rem' }}></i>
                        User created. Send them this activation link — it works once and expires in 7 days.
                        (Connect your mailbox in Settings → Email to send these automatically.)
                    </p>
                ) : em ? (
                    <p style={{ fontSize: '0.875rem', marginBottom: '0.5rem' }}>
                        <i className="fas fa-triangle-exclamation" style={{ color: 'var(--warning)', marginRight: '0.375rem' }}></i>
                        User created, but the invite email didn't send — share this link manually (single-use, 7 days):
                    </p>
                ) : (
                    <p style={{ fontSize: '0.875rem', marginBottom: '0.5rem' }}>
                        <i className="fas fa-check-circle" style={{ color: 'var(--success)', marginRight: '0.375rem' }}></i>
                        User created. Send them this activation link — it works once and expires in 7 days:
                    </p>
                )}
                <div className="note-box success">
                    <code>{inviteUrl}</code>
                    <button className="btn btn-secondary btn-small" style={{ marginLeft: '0.5rem' }}
                            onClick={() => navigator.clipboard.writeText(inviteUrl)}>
                        <i className="fas fa-copy"></i> Copy
                    </button>
                </div>
                <div className="btn-group" style={{ marginTop: '0.75rem' }}>
                    <button type="button" className="btn btn-primary btn-small" onClick={onCancel}>Done</button>
                </div>
            </div>
        );
    }

    return (
        <form onSubmit={handleSubmit}>
            {error && <div className="api-error" style={{ marginBottom: '0.75rem' }}>{error}</div>}
            <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 />
                </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')} required />
                </div>
                <div className="form-group">
                    <label className="form-label">Email *</label>
                    <input type="email" className="form-input" value={form.email} onChange={set('email')} required />
                </div>
                <div className="form-group">
                    <label className="form-label">Role</label>
                    <select className="form-input" value={form.role} onChange={set('role')}>
                        <option value="rep">Rep</option>
                        <option value="manager">Manager</option>
                        <option value="admin">Admin</option>
                    </select>
                </div>
                <div className="form-group full-width">
                    <label className="form-label">How do they get in?</label>
                    <div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap' }}>
                        <button type="button" className={`btn btn-small ${mode === 'invite' ? 'btn-primary' : 'btn-secondary'}`} onClick={() => setMode('invite')}>
                            <i className="fas fa-envelope-open-text"></i> Activation link (they choose their password)
                        </button>
                        <button type="button" className={`btn btn-small ${mode === 'password' ? 'btn-primary' : 'btn-secondary'}`} onClick={() => setMode('password')}>
                            <i className="fas fa-key"></i> I'll set a password now
                        </button>
                    </div>
                </div>
                {mode === 'invite' && (
                    <div className="form-group full-width">
                        <button type="button" className={`btn btn-small ${sendEmail ? 'btn-primary' : 'btn-secondary'}`}
                                onClick={() => setSendEmail(s => !s)}>
                            <i className={`fas ${sendEmail ? 'fa-paper-plane' : 'fa-link'}`}></i>
                            {sendEmail ? ' Email the invite automatically' : " Don't email — I'll share the link myself"}
                        </button>
                    </div>
                )}
                {mode === 'password' && (
                    <div className="form-group full-width">
                        <label className="form-label">Password *</label>
                        <input type="password" className="form-input" value={form.password} onChange={set('password')} placeholder="Min 12 characters, not a common password" minLength={12} maxLength={72} required />
                    </div>
                )}
            </div>
            <div className="btn-group" style={{ marginTop: 0 }}>
                <button type="button" className="btn btn-secondary btn-small" onClick={onCancel} disabled={saving}>Cancel</button>
                <button type="submit" className="btn btn-primary btn-small" disabled={saving}>
                    {saving ? <><i className="fas fa-spinner fa-spin"></i> Creating…</> : <><i className="fas fa-user-plus"></i> {mode === 'invite' ? (sendEmail ? 'Create & Send Invite' : 'Create & Get Link') : 'Create User'}</>}
                </button>
            </div>
        </form>
    );
};
