import { useEffect, useState, useCallback } from 'react';
import api from '../../api/client.js';
import Spinner from '../../components/Spinner.jsx';
import { useToast } from '../../context/ToastContext.jsx';
import { useAuth } from '../../context/AuthContext.jsx';
import { useConfirm } from '../../context/ConfirmContext.jsx';

const blank = { name: '', email: '', password: '', role: 'USER' };

export default function AdminUsers() {
  const toast = useToast();
  const confirm = useConfirm();
  const { user: me } = useAuth();
  const [users, setUsers] = useState(null);
  const [search, setSearch] = useState('');
  const [form, setForm] = useState(blank);
  const [editingId, setEditingId] = useState(null);
  const [busy, setBusy] = useState(false);

  const load = useCallback(() => {
    api.get('/users', { params: search ? { search } : {} })
      .then(({ data }) => setUsers(data.users))
      .catch((e) => toast.error(e.message));
  }, [search, toast]);

  useEffect(() => { load(); }, [load]);

  const startEdit = (u) => {
    setEditingId(u.id);
    // Email is intentionally not editable; password is left blank to keep the current one.
    setForm({ name: u.name || '', email: u.email || '', password: '', role: u.role });
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const cancelEdit = () => {
    setEditingId(null);
    setForm(blank);
  };

  const submit = async (e) => {
    e.preventDefault();
    if (editingId) {
      if (form.password && form.password.length < 8) {
        return toast.error('Password must be at least 8 characters');
      }
      setBusy(true);
      try {
        // Email is never sent — it cannot be changed from the admin panel.
        const patch = { name: form.name, role: form.role };
        if (form.password) patch.password = form.password;
        await api.patch(`/users/${editingId}`, patch);
        toast.success(`User "${form.name}" updated`);
        cancelEdit();
        load();
      } catch (err) {
        toast.error(err.message);
      } finally {
        setBusy(false);
      }
      return;
    }

    if (form.password.length < 8) return toast.error('Password must be at least 8 characters');
    setBusy(true);
    try {
      await api.post('/users', form);
      toast.success(`User "${form.name}" created`);
      setForm(blank);
      load();
    } catch (err) {
      toast.error(err.message);
    } finally {
      setBusy(false);
    }
  };

  const toggleRole = async (u) => {
    const role = u.role === 'ADMIN' ? 'USER' : 'ADMIN';
    try {
      await api.patch(`/users/${u.id}`, { role });
      toast.success(`${u.name} is now ${role}`);
      load();
    } catch (err) {
      toast.error(err.message);
    }
  };

  const toggleActive = async (u) => {
    const isActive = !u.isActive;
    if (!isActive) {
      const ok = await confirm({
        title: `Deactivate ${u.name}?`,
        message: `${u.email} will be blocked from logging in until you reactivate the account.`,
        confirmLabel: 'Deactivate',
        tone: 'danger',
      });
      if (!ok) return;
    }
    try {
      await api.patch(`/users/${u.id}`, { isActive });
      toast.success(`${u.name} is now ${isActive ? 'active' : 'inactive'}`);
      load();
    } catch (err) {
      toast.error(err.message);
    }
  };

  const remove = async (u) => {
    const ok = await confirm({
      title: `Delete ${u.name}?`,
      message: `This permanently removes ${u.email} along with their attempts and purchases. This cannot be undone.`,
      confirmLabel: 'Delete user',
      tone: 'danger',
    });
    if (!ok) return;
    try {
      await api.delete(`/users/${u.id}`);
      toast.success('User deleted');
      if (editingId === u.id) cancelEdit();
      setUsers((list) => list.filter((x) => x.id !== u.id));
    } catch (err) {
      toast.error(err.message);
    }
  };

  return (
    <div className="grid admin-split">
      <div className="card">
        <h3>{editingId ? 'Edit user' : 'Add user'}</h3>
        <form onSubmit={submit}>
          <div className="field">
            <label className="label">Full name</label>
            <input className="input" value={form.name} required
              onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="Jane Doe" />
          </div>
          <div className="field">
            <label className="label">Email{editingId && <span className="muted"> (cannot be changed)</span>}</label>
            <input className="input" type="email" value={form.email} required={!editingId} disabled={!!editingId}
              onChange={(e) => setForm({ ...form, email: e.target.value })} placeholder="jane@example.com" />
          </div>
          <div className="field">
            <label className="label">Password{editingId && <span className="muted"> (leave blank to keep current)</span>}</label>
            <input className="input" type="text" value={form.password} required={!editingId}
              onChange={(e) => setForm({ ...form, password: e.target.value })}
              placeholder={editingId ? 'New password (optional)' : 'At least 8 characters'} />
          </div>
          <div className="field">
            <label className="label">Role</label>
            <select className="select" value={form.role}
              onChange={(e) => setForm({ ...form, role: e.target.value })}
              disabled={editingId === me.id}>
              <option value="USER">User</option>
              <option value="ADMIN">Admin</option>
            </select>
            {editingId === me.id && (
              <span className="muted" style={{ fontSize: '0.82rem' }}>You can't change your own role.</span>
            )}
          </div>
          <button className="btn btn-block" disabled={busy}>
            {busy ? 'Saving…' : editingId ? 'Save changes' : 'Add user'}
          </button>
          {editingId && (
            <button type="button" className="btn btn-ghost btn-block mt-2" onClick={cancelEdit}>Cancel</button>
          )}
        </form>
      </div>

      <div>
        <div className="field">
          <input className="input" value={search} placeholder="Search by name or email…"
            onChange={(e) => setSearch(e.target.value)} />
        </div>

        {!users ? <Spinner /> : (
          <div className="card table-card">
            <div className="table-scroll">
            <table className="table">
              <thead>
                <tr><th>User</th><th>Role</th><th>Status</th><th>Attempts</th><th>Owned</th><th>Joined</th><th>Actions</th></tr>
              </thead>
              <tbody>
                {users.map((u) => (
                  <tr key={u.id}>
                    <td>
                      <b>{u.name}</b>{u.id === me.id && <span className="badge" style={{ marginLeft: 6 }}>you</span>}
                      <div className="muted" style={{ fontSize: '0.85rem' }}>{u.email}</div>
                    </td>
                    <td>
                      <span className={`badge ${u.role === 'USER' ? '' : 'badge-amber'}`}>
                        {u.role === 'SUPER_ADMIN' ? 'SUPER ADMIN' : u.role}
                      </span>
                    </td>
                    <td>
                      <span className={`badge ${u.isActive ? 'badge-green' : 'badge-red'}`}>
                        {u.isActive ? 'Active' : 'Inactive'}
                      </span>
                    </td>
                    <td>{u._count?.attempts ?? 0}</td>
                    <td>{u._count?.purchases ?? 0}</td>
                    <td className="muted">{new Date(u.createdAt).toLocaleDateString()}</td>
                    <td>
                      <div className="table-actions">
                      {u.role === 'SUPER_ADMIN' ? (
                        <span className="muted" style={{ fontSize: '0.85rem' }}>Protected</span>
                      ) : (
                        <>
                          <button className="btn btn-sm btn-ghost" onClick={() => startEdit(u)}>Edit</button>
                          <button className="btn btn-sm btn-ghost" onClick={() => toggleRole(u)} disabled={u.id === me.id}
                            title={u.id === me.id ? "You can't change your own role" : ''}>
                            {u.role === 'ADMIN' ? 'Make user' : 'Make admin'}
                          </button>
                          <button className={`btn btn-sm ${u.isActive ? 'btn-ghost' : 'btn-success'}`}
                            onClick={() => toggleActive(u)} disabled={u.id === me.id}
                            title={u.id === me.id ? "You can't deactivate yourself" : ''}>
                            {u.isActive ? 'Deactivate' : 'Activate'}
                          </button>
                          <button className="btn btn-sm btn-danger" onClick={() => remove(u)} disabled={u.id === me.id}
                            title={u.id === me.id ? "You can't delete yourself" : ''}>
                            Delete
                          </button>
                        </>
                      )}
                      </div>
                    </td>
                  </tr>
                ))}
                {users.length === 0 && <tr><td colSpan="7" className="muted">No users found.</td></tr>}
              </tbody>
            </table>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
