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

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

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

    return (
        <div className="table-panel">
            <div className="panel-header">
                <h2>Users ({data.totalCount})</h2>
                <button className="btn-action" onClick={() => setShowForm(!showForm)}>
                    {showForm ? 'Cancel' : '+ Add User'}
                </button>
            </div>

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

            <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(user => (
                        <tr key={user.userId}>
                            <td>{user.email}</td>
                            <td>{user.displayName || '-'}</td>
                            <td><StatusBadge status={user.status} /></td>
                            <td>{user.clients?.map(c => `${c.clientName} (${c.role})`).join(', ') || '-'}</td>
                            <td>{new Date(user.createdAt).toLocaleDateString()}</td>
                            <td>
                                <button
                                    className="btn-small btn-danger"
                                    onClick={() => deleteUser(user.userId)}
                                >
                                    Deactivate
                                </button>
                            </td>
                        </tr>
                    ))}
                    {users.length === 0 && (
                        <tr><td colSpan="6" className="empty-row">No users found</td></tr>
                    )}
                </tbody>
            </table>
        </div>
    );
}

function CreateUserForm({ onSuccess, onCancel }) {
    const { apiCall } = useAdmin();
    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(() => {
        const loadClients = async () => {
            const result = await apiCall('/api/admin/clients?pageSize=100');
            if (result.ok) setClients(result.clients || []);
            setLoadingClients(false);
        };
        loadClients();
    }, [apiCall]);

    const handleSubmit = async (e) => {
        e.preventDefault();
        setLoading(true);
        setError(null);

        const result = await apiCall('/api/admin/users', 'POST', {
            email,
            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 User</h3>
            {error && <div className="error-message">{error}</div>}
            <form onSubmit={handleSubmit}>
                <div className="form-group">
                    <label>Email *</label>
                    <input
                        type="email"
                        value={email}
                        onChange={(e) => setEmail(e.target.value)}
                        placeholder="user@example.com"
                        disabled={loading}
                        required
                        autoFocus
                    />
                </div>
                <div className="form-group">
                    <label>Display Name</label>
                    <input
                        type="text"
                        value={displayName}
                        onChange={(e) => setDisplayName(e.target.value)}
                        placeholder="John 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 (invite 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 type="button" className="btn-cancel" onClick={onCancel} disabled={loading}>Cancel</button>
                    <button type="submit" className="btn-primary" disabled={loading || !email.trim()}>
                        {loading ? 'Creating...' : 'Create User'}
                    </button>
                </div>
            </form>
        </div>
    );
}

function StatusBadge({ status }) {
    const statusClass = {
        'Active': 'status-active',
        'Inactive': 'status-inactive',
    }[status] || 'status-default';
    return <span className={`status-badge ${statusClass}`}>{status}</span>;
}
