'use client';

import { useEffect, useState } from 'react';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch } from '@/lib/api';
import { useToast } from '@/lib/toast';
import Modal from '@/components/Modal';
import { TableSkeleton } from '@/components/Skeletons';

type AdminUserRow = {
  id: number; name: string; email: string; isActive: boolean;
  twoFactorEnabled: boolean; role: { id: number; name: string }; lastLoginAt: string | null;
};
type RoleOption = { id: number; name: string };

export default function UsersPage() {
  const { accessToken, appSecretProof, user: me } = useAuth();
  const { show } = useToast();
  const [users, setUsers] = useState<AdminUserRow[]>([]);
  const [roles, setRoles] = useState<RoleOption[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showInvite, setShowInvite] = useState(false);
  const [inviting, setInviting] = useState(false);
  const [form, setForm] = useState({ name: '', email: '', phone: '', roleId: '' });

  async function load() {
    if (!accessToken || !appSecretProof) return;
    setLoading(true);
    try {
      const [u, r] = await Promise.all([
        adminApiFetch('/admin/users', accessToken, appSecretProof),
        adminApiFetch('/admin/users/roles-list', accessToken, appSecretProof).catch(() => ({ roles: [] })),
      ]);
      setUsers(u.users || []);
      setRoles(r.roles || []);
    } catch {
      setError('You do not have permission to view this page.');
    } finally {
      setLoading(false);
    }
  }
  useEffect(() => { load(); }, [accessToken, appSecretProof]); // eslint-disable-line react-hooks/exhaustive-deps

  async function resetPassword(id: number, name: string) {
    if (!accessToken || !appSecretProof) return;
    if (!window.confirm(`Reset ${name}'s password? They will be signed out everywhere and must set a new password next time.`)) return;
    try {
      const d = await adminApiFetch(`/admin/users/${id}/reset-password`, accessToken, appSecretProof, { method: 'POST' });
      if (d.invite?.tempPassword) window.prompt(`Could not e-mail ${name} (${d.invite.emailError || 'mailbox not set up yet'}). Temporary password — shown only once:`, d.invite.tempPassword);
      else show('success', `A new temporary password was e-mailed to ${name}.`);
    } catch { show('error', 'Could not reset that password.'); }
  }

  async function deactivate(id: number, name: string) {
    if (!accessToken || !appSecretProof) return;
    try {
      await adminApiFetch(`/admin/users/${id}/deactivate`, accessToken, appSecretProof, { method: 'PATCH' });
      setUsers((u) => u.map((row) => (row.id === id ? { ...row, isActive: false } : row)));
      show('success', `${name} has been deactivated.`);
    } catch {
      show('error', 'Could not deactivate that user.');
    }
  }

  async function submitInvite(e: React.FormEvent) {
    e.preventDefault();
    if (!accessToken || !appSecretProof || !form.roleId) return;
    setInviting(true);
    try {
      const d = await adminApiFetch('/admin/users', accessToken, appSecretProof, {
        method: 'POST',
        body: JSON.stringify({ ...form, roleId: Number(form.roleId) }),
      });
      if (d.invite?.tempPassword) {
        window.prompt(
          `Could not e-mail ${form.email} (${d.invite.emailError || 'mailbox not set up yet'}). Copy this temporary password and hand it to them securely — it is shown only once:`,
          d.invite.tempPassword
        );
      } else {
        show('success', `Account created — a temporary password was e-mailed to ${form.email}.`);
      }
      setForm({ name: '', email: '', phone: '', roleId: '' });
      setShowInvite(false);
      load();
    } catch (err) {
      const m = (err as Error).message;
      show('error', m === 'EMAIL_ALREADY_REGISTERED' ? 'That e-mail is already registered.' : m === 'ONLY_SUPER_ADMIN_CAN_CREATE_SUPER_ADMIN' ? 'Only a Super Admin can create another Super Admin.' : 'Could not create that account — check the details and try again.');
    } finally {
      setInviting(false);
    }
  }

  if (error) return <p className="text-sm text-brand-red">{error}</p>;

  return (
    <div>
      <div className="flex items-center justify-between mb-4">
        <h1 className="text-lg font-bold">User Management</h1>
        <button onClick={() => setShowInvite(true)} className="bg-brand-red text-white text-sm px-4 py-2 rounded-lg transition-transform hover:scale-[1.03] active:scale-[0.98]">
          Invite Admin
        </button>
      </div>

      {loading ? <TableSkeleton rows={4} cols={6} /> : (
        <div className="bg-white border border-brand-border rounded-xl overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-brand-bg text-left text-xs text-gray-500">
              <tr>
                <th className="px-4 py-2">Name</th>
                <th className="px-4 py-2">Email</th>
                <th className="px-4 py-2">Role</th>
                <th className="px-4 py-2">2FA</th>
                <th className="px-4 py-2">Status</th>
                <th className="px-4 py-2">Last Login</th>
                <th className="px-4 py-2"></th>
              </tr>
            </thead>
            <tbody>
              {users.map((u) => (
                <tr key={u.id} className="border-t border-brand-border transition-colors hover:bg-brand-bg">
                  <td className="px-4 py-2 font-medium">{u.name}</td>
                  <td className="px-4 py-2 text-gray-500">{u.email}</td>
                  <td className="px-4 py-2"><span className="text-[11px] bg-brand-bg border border-brand-border rounded-full px-2 py-0.5">{u.role.name}</span></td>
                  <td className="px-4 py-2">{u.twoFactorEnabled ? '✅' : '⚠️ not enrolled'}</td>
                  <td className="px-4 py-2">{u.isActive ? 'Active' : 'Deactivated'}</td>
                  <td className="px-4 py-2 text-gray-500">{u.lastLoginAt ? new Date(u.lastLoginAt).toLocaleString() : '—'}</td>
                  <td className="px-4 py-2 text-right space-x-2">
                    {u.id !== me?.id && (
                      <button onClick={() => resetPassword(u.id, u.name)} className="text-xs text-gray-500 transition-colors hover:text-brand-charcoal">Reset password</button>
                    )}
                    {u.isActive && u.id !== me?.id && (
                      <button onClick={() => deactivate(u.id, u.name)} className="text-xs text-brand-red transition-colors hover:text-red-800">Deactivate</button>
                    )}
                  </td>
                </tr>
              ))}
              {users.length === 0 && <tr><td colSpan={7} className="p-6 text-center text-gray-400">No admin users yet.</td></tr>}
            </tbody>
          </table>
        </div>
      )}

      {showInvite && (
        <Modal title="Invite Admin" onClose={() => setShowInvite(false)}>
          <form onSubmit={submitInvite} className="space-y-3">
            <div>
              <label className="text-xs font-medium text-gray-600">Full name</label>
              <input required value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })}
                className="mt-1 w-full border border-brand-border rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-brand-red" />
            </div>
            <div>
              <label className="text-xs font-medium text-gray-600">Email</label>
              <input required type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })}
                className="mt-1 w-full border border-brand-border rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-brand-red" />
            </div>
            <div>
              <label className="text-xs font-medium text-gray-600">Phone (optional)</label>
              <input value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })}
                className="mt-1 w-full border border-brand-border rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-brand-red" />
            </div>
            <div>
              <label className="text-xs font-medium text-gray-600">Role</label>
              <select required value={form.roleId} onChange={(e) => setForm({ ...form, roleId: e.target.value })}
                className="mt-1 w-full border border-brand-border rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-brand-red">
                <option value="">Select a role…</option>
                {roles.map((r) => <option key={r.id} value={r.id}>{r.name}</option>)}
              </select>
            </div>
            <p className="text-[11px] text-gray-400">A temporary password is generated and sent to the invitee — they'll be forced through the same password-reset + 2FA enrollment you just went through.</p>
            <button disabled={inviting} className="w-full bg-brand-red text-white text-sm font-semibold py-2.5 rounded-lg disabled:opacity-60">
              {inviting ? 'Sending…' : 'Send Invite'}
            </button>
          </form>
        </Modal>
      )}
    </div>
  );
}
