import React, { useState, useEffect } from 'react';
import { useAdmin } from '../../context/AdminContext';

// ─── Client Users Panel ───────────────────────────────────────────────────────
// Manages tbClientUser / tbClientUserRole — client planet only.
// No admin-plane concepts here.
// ─────────────────────────────────────────────────────────────────────────────

export default function ClientUsersPanel() {
    const { data, apiCall, refresh } = useAdmin();
    const [showForm, setShowForm] = useState(false);
    const users = data.users || [];

    const deactivate = async (userId) => {
        if (!confirm('Deactivate this client user?')) return;
        const result = await apiCall(`/api/admin/client-users/${userId}`, 'DELETE');
        if (result.ok) refresh();
        else alert(result.error || 'Failed to deactivate user');
    };

    return (
        <div className="table-panel">
            <div className="panel-header">
                <div>
                    <h2>Client Users ({data.totalCount ?? users.length})</h2>
                    <span style={{ fontSize: 13, color: 'var(--text-dim)' }}>
                        Users on the client platform
                    </span>
                </div>
                <button className="btn-action" onClick={() => setShowForm(!showForm)}>
                    {showForm ? 'Cancel' : '+ Add User'}
                </button>
            </div>

            {showForm && (
                <CreateClientUserForm
                    onSuccess={() => { setShowForm(false); refresh(); }}
                    onCancel={() => setShowForm(false)}
                    apiCall={apiCall}
                />
            )}

            <table className="data-table">
                <thead>
                    <tr>
                        <th>Email</th>
                        <th>Name</th>
                        <th>Status</th>
                        <th>Clients</th>
                        <th>Created</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    {users.map(u => (
                        <tr key={u.userId}>
                            <td>{u.email}</td>
                            <td>{u.displayName || '—'}</td>
                            <td><StatusBadge status={u.status} /></td>
                            <td>{u.clients?.map(c => `${c.clientName} (${c.role})`).join(', ') || '—'}</td>
                            <td>{u.createdAt ? new Date(u.createdAt).toLocaleDateString() : '—'}</td>
                            <td>
                                <button className="btn-small btn-danger" onClick={() => deactivate(u.userId)}>
                                    Deactivate
                                </button>
                            </td>
                        </tr>
                    ))}
                    {users.length === 0 && (
                        <tr><td colSpan="6" className="empty-row">No client users found</td></tr>
                    )}
                </tbody>
            </table>
        </div>
    );
}

function CreateClientUserForm({ onSuccess, onCancel, apiCall }) {
    const [email, setEmail]             = useState('');
    const [displayName, setDisplayName] = useState('');
    const [clientId, setClientId]       = useState('');
    const [role, setRole]               = useState('User');
    const [clients, setClients]         = useState([]);
    const [loading, setLoading]         = useState(false);
    const [loadingClients, setLoadingClients] = useState(true);
    const [error, setError]             = useState(null);

    useEffect(() => {
        apiCall('/api/admin/clients/list', 'POST', { pageSize: 100 }).then(r => {
            if (r.ok) setClients(r.clients || []);
            setLoadingClients(false);
        });
    }, [apiCall]);

    const handleSubmit = async () => {
        if (!email.trim()) return;
        setLoading(true);
        setError(null);
        const result = await apiCall('/api/admin/client-users', 'POST', {
            email: email.trim(),
            displayName: displayName || null,
            clientId: clientId || null,
            role,
        });
        if (result.ok) onSuccess();
        else setError(result.error || 'Failed to create user');
        setLoading(false);
    };

    return (
        <div className="admin-form">
            <h3>Create Client User</h3>
            {error && <div className="error-message">{error}</div>}
            <div className="form-group">
                <label>Email *</label>
                <input type="email" value={email} onChange={e => setEmail(e.target.value)}
                    placeholder="user@example.com" disabled={loading} autoFocus />
            </div>
            <div className="form-group">
                <label>Display Name</label>
                <input type="text" value={displayName} onChange={e => setDisplayName(e.target.value)}
                    placeholder="Jane Smith" disabled={loading} />
            </div>
            <div className="form-group">
                <label>Assign to Client</label>
                <select value={clientId} onChange={e => setClientId(e.target.value)}
                    disabled={loading || loadingClients}>
                    <option value="">— No client (assign later) —</option>
                    {clients.filter(c => c.status === 'Active').map(c => (
                        <option key={c.clientId} value={c.clientId}>{c.clientName}</option>
                    ))}
                </select>
            </div>
            {clientId && (
                <div className="form-group">
                    <label>Role</label>
                    <select value={role} onChange={e => setRole(e.target.value)} disabled={loading}>
                        <option value="Admin">Admin</option>
                        <option value="User">User</option>
                        <option value="ReadOnly">Read Only</option>
                    </select>
                </div>
            )}
            <div className="form-buttons">
                <button className="btn-cancel" onClick={onCancel} disabled={loading}>Cancel</button>
                <button className="btn-primary" onClick={handleSubmit} disabled={loading || !email.trim()}>
                    {loading ? 'Creating…' : 'Create User'}
                </button>
            </div>
        </div>
    );
}

function StatusBadge({ status }) {
    const style = status === 'Active'
        ? { background: '#dcfce7', color: '#166534', border: '1px solid #86efac' }
        : { background: '#f3f4f6', color: '#6b7280', border: '1px solid #d1d5db' };
    return <span className="status-badge" style={style}>{status}</span>;
}
