'use client';

import { useState, useTransition } from 'react';
import {
  setUserAdmin,
  adminResetPassword,
  deleteUser,
} from '@/app/main/admin/users/actions';

type UserRow = {
  id: string;
  email: string;
  name: string | null;
  isAdmin: boolean;
  createdAt: string;
  lastLoginAt: string | null;
  sessionCount: number;
  workoutCount: number;
};

function relativeAge(iso: string | null): string {
  if (!iso) return 'never';
  const ms = Date.now() - new Date(iso).getTime();
  const days = Math.floor(ms / 86_400_000);
  if (days < 1) return 'today';
  if (days === 1) return 'yesterday';
  if (days < 30) return `${days}d ago`;
  if (days < 365) return `${Math.floor(days / 30)}mo ago`;
  return `${Math.floor(days / 365)}y ago`;
}

export default function UsersTable({
  users,
  currentUserId,
}: {
  users: UserRow[];
  currentUserId: string;
}) {
  const [pending, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);
  const [info, setInfo] = useState<string | null>(null);
  const [activeReset, setActiveReset] = useState<string | null>(null);

  const flash = (msg: string, kind: 'error' | 'info') => {
    setError(null);
    setInfo(null);
    if (kind === 'error') setError(msg);
    else setInfo(msg);
    setTimeout(() => {
      setError(null);
      setInfo(null);
    }, 6000);
  };

  const onToggleAdmin = (u: UserRow) => {
    startTransition(async () => {
      const res = await setUserAdmin(u.id, !u.isAdmin);
      if (res.error) flash(res.error, 'error');
      else flash(`${u.email} is now ${!u.isAdmin ? 'an admin' : 'a regular user'}.`, 'info');
    });
  };

  const onDelete = (u: UserRow) => {
    if (
      !window.confirm(
        `Delete ${u.email}? This is permanent and removes their workouts, exercises, and sessions.`,
      )
    ) {
      return;
    }
    startTransition(async () => {
      const res = await deleteUser(u.id);
      if (res.error) flash(res.error, 'error');
      else flash(`Deleted ${u.email}.`, 'info');
    });
  };

  return (
    <div className="space-y-4">
      {error && (
        <div className="rounded bg-red-900/50 px-3 py-2 border border-red-800 text-xs text-red-400">
          {error}
        </div>
      )}
      {info && (
        <div className="rounded bg-emerald-900/40 px-3 py-2 border border-emerald-800 text-xs text-emerald-300">
          {info}
        </div>
      )}

      <div className="bg-zinc-900 rounded border border-zinc-800 overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-zinc-800/50 text-xs uppercase tracking-wider text-zinc-400">
            <tr>
              <th className="text-left px-4 py-3">User</th>
              <th className="text-left px-4 py-3 hidden sm:table-cell">Joined</th>
              <th className="text-left px-4 py-3 hidden md:table-cell">Last login</th>
              <th className="text-left px-4 py-3 hidden sm:table-cell">Workouts</th>
              <th className="text-left px-4 py-3">Role</th>
              <th className="text-right px-4 py-3">Actions</th>
            </tr>
          </thead>
          <tbody>
            {users.map((u) => {
              const isMe = u.id === currentUserId;
              return (
                <tr key={u.id} className="border-t border-zinc-800">
                  <td className="px-4 py-3">
                    <div className="text-white font-medium">{u.email}</div>
                    {u.name && <div className="text-xs text-zinc-500">{u.name}</div>}
                    {isMe && (
                      <span className="inline-block mt-1 text-[10px] uppercase tracking-wider bg-zinc-800 text-zinc-300 px-1.5 py-0.5 rounded">
                        you
                      </span>
                    )}
                  </td>
                  <td className="px-4 py-3 text-xs text-zinc-500 hidden sm:table-cell">
                    {new Date(u.createdAt).toLocaleDateString()}
                  </td>
                  <td
                    className={`px-4 py-3 text-xs hidden md:table-cell ${
                      u.lastLoginAt ? 'text-zinc-400' : 'text-zinc-600 italic'
                    }`}
                    title={u.lastLoginAt ?? 'never'}
                  >
                    {relativeAge(u.lastLoginAt)}
                  </td>
                  <td className="px-4 py-3 text-xs text-zinc-400 hidden sm:table-cell">
                    {u.workoutCount}
                  </td>
                  <td className="px-4 py-3">
                    <span
                      className={`text-xs uppercase tracking-wider ${
                        u.isAdmin ? 'text-white' : 'text-zinc-500'
                      }`}
                    >
                      {u.isAdmin ? 'Admin' : 'User'}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-right">
                    <div className="flex justify-end gap-2 flex-wrap">
                      <button
                        type="button"
                        onClick={() => onToggleAdmin(u)}
                        disabled={pending}
                        className="text-xs px-2 py-1 rounded border border-zinc-700 text-zinc-300 hover:bg-zinc-800 disabled:opacity-50"
                      >
                        {u.isAdmin ? 'Demote' : 'Promote'}
                      </button>
                      <button
                        type="button"
                        onClick={() =>
                          setActiveReset(activeReset === u.id ? null : u.id)
                        }
                        disabled={pending}
                        className="text-xs px-2 py-1 rounded border border-zinc-700 text-zinc-300 hover:bg-zinc-800 disabled:opacity-50"
                      >
                        Reset password
                      </button>
                      {!isMe && (
                        <button
                          type="button"
                          onClick={() => onDelete(u)}
                          disabled={pending}
                          className="text-xs px-2 py-1 rounded border border-red-900 text-red-400 hover:bg-red-900/30 disabled:opacity-50"
                        >
                          Delete
                        </button>
                      )}
                    </div>
                    {activeReset === u.id && (
                      <ResetPasswordRow
                        userId={u.id}
                        email={u.email}
                        onDone={(msg, ok) => {
                          flash(msg, ok ? 'info' : 'error');
                          if (ok) setActiveReset(null);
                        }}
                      />
                    )}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function ResetPasswordRow({
  userId,
  email,
  onDone,
}: {
  userId: string;
  email: string;
  onDone: (msg: string, ok: boolean) => void;
}) {
  const [pwd, setPwd] = useState('');
  const [busy, setBusy] = useState(false);

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    setBusy(true);
    const res = await adminResetPassword(userId, pwd);
    setBusy(false);
    if (res.error) {
      onDone(res.error, false);
    } else {
      onDone(
        `Password for ${email} reset.${
          (res.revoked ?? 0) > 0
            ? ` Revoked ${res.revoked} session${res.revoked === 1 ? '' : 's'}.`
            : ''
        }`,
        true,
      );
      setPwd('');
    }
  };

  return (
    <form onSubmit={submit} className="mt-3 flex gap-2 justify-end">
      <input
        type="password"
        value={pwd}
        onChange={(e) => setPwd(e.target.value)}
        placeholder="New password (8+ chars)"
        minLength={8}
        required
        autoFocus
        className="text-xs px-2 py-1 rounded border border-zinc-700 bg-zinc-800 text-white placeholder:text-zinc-500"
      />
      <button
        type="submit"
        disabled={busy}
        className="text-xs px-2 py-1 rounded bg-white text-black font-bold uppercase tracking-wider disabled:opacity-50"
      >
        {busy ? '...' : 'Save'}
      </button>
    </form>
  );
}
