"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import {
  changeRoleAction,
  deleteUserAction,
  reassignArticlesAction,
} from "./_actions";

export type UserRow = {
  id: string;
  email: string;
  name: string;
  role: string;
  emailVerified: boolean;
  articleCount: number;
  apiTokenCount: number;
  createdAt: Date;
};

const ROLE_LABEL: Record<string, { label: string; cls: string }> = {
  admin: { label: "Admin", cls: "bg-rose-500/15 text-rose-300" },
  editor: { label: "Editor", cls: "bg-sky-500/15 text-sky-300" },
  user: { label: "User", cls: "bg-zinc-500/15 text-zinc-400" },
};

function fmt(d: Date): string {
  return new Intl.DateTimeFormat("vi-VN", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
  }).format(d);
}

export function UserActions({
  user,
  isMe,
  others,
}: {
  user: UserRow;
  isMe: boolean;
  others: Array<{ id: string; email: string }>;
}) {
  const router = useRouter();
  const [pending, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);
  const [showReassign, setShowReassign] = useState(false);

  function changeRole(role: string) {
    if (role === user.role) return;
    setError(null);
    startTransition(async () => {
      const res = await changeRoleAction(user.id, role);
      if (!res.ok) setError(res.error);
      else router.refresh();
    });
  }

  function remove() {
    if (!confirm(`Xóa user "${user.email}"?`)) return;
    setError(null);
    startTransition(async () => {
      const res = await deleteUserAction(user.id);
      if (!res.ok) setError(res.error);
      else router.refresh();
    });
  }

  function reassign(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const fd = new FormData(e.currentTarget);
    const toUserId = String(fd.get("toUserId") ?? "");
    if (!toUserId) return;
    setError(null);
    startTransition(async () => {
      const res = await reassignArticlesAction(user.id, toUserId);
      if (!res.ok) setError(res.error);
      else {
        setShowReassign(false);
        router.refresh();
      }
    });
  }

  return (
    <div className="flex flex-col items-end gap-1">
      {error && <div className="text-xs text-rose-300">{error}</div>}
      <div className="flex items-center gap-2">
        <select
          defaultValue={user.role}
          onChange={(e) => changeRole(e.target.value)}
          disabled={pending || isMe}
          className="text-xs px-2 py-1 rounded bg-bg-elevated border border-stroke-subtle disabled:opacity-50"
        >
          <option value="user">User</option>
          <option value="editor">Editor</option>
          <option value="admin">Admin</option>
        </select>
        {user.articleCount > 0 && !isMe && (
          <button
            type="button"
            onClick={() => setShowReassign(!showReassign)}
            className="text-xs text-amber-300 hover:underline"
          >
            Chuyển bài
          </button>
        )}
        {!isMe && user.articleCount === 0 && (
          <button
            type="button"
            onClick={remove}
            disabled={pending}
            className="text-xs text-rose-300 hover:underline disabled:opacity-50"
          >
            Xóa
          </button>
        )}
        {isMe && <span className="text-[10px] uppercase tracking-wider text-ink-muted/70">bạn</span>}
      </div>
      {showReassign && (
        <form onSubmit={reassign} className="flex gap-1.5 mt-1">
          <select name="toUserId" required className="text-xs px-2 py-1 rounded bg-bg-elevated border border-stroke-subtle">
            <option value="">— Chuyển sang —</option>
            {others.filter((o) => o.id !== user.id).map((o) => (
              <option key={o.id} value={o.id}>{o.email}</option>
            ))}
          </select>
          <button type="submit" disabled={pending} className="text-xs px-2 py-1 rounded bg-accent-primary text-white disabled:opacity-50">OK</button>
        </form>
      )}
    </div>
  );
}

export function UsersTable({
  users,
  meId,
}: {
  users: UserRow[];
  meId: string;
}) {
  const others = users.map((u) => ({ id: u.id, email: u.email }));
  return (
    <div className="rounded-xl border border-stroke-subtle overflow-hidden">
      <table className="w-full text-sm">
        <thead className="bg-bg-elevated/60 text-left">
          <tr className="border-b border-stroke-subtle">
            <th className="px-4 py-2.5 font-medium text-ink-muted">User</th>
            <th className="px-4 py-2.5 font-medium text-ink-muted">Role</th>
            <th className="px-4 py-2.5 font-medium text-ink-muted">Bài</th>
            <th className="px-4 py-2.5 font-medium text-ink-muted">Tokens</th>
            <th className="px-4 py-2.5 font-medium text-ink-muted">Tạo</th>
            <th className="px-4 py-2.5 font-medium text-ink-muted text-right">Hành động</th>
          </tr>
        </thead>
        <tbody>
          {users.map((u) => {
            const r = ROLE_LABEL[u.role] ?? ROLE_LABEL.user;
            return (
              <tr key={u.id} className="border-b border-stroke-subtle/60 last:border-0 hover:bg-bg-elevated/30 transition">
                <td className="px-4 py-3">
                  <div className="font-medium">{u.name}</div>
                  <div className="text-xs text-ink-muted mt-0.5">
                    {u.email}
                    {!u.emailVerified && (
                      <span className="ml-2 text-[10px] uppercase tracking-wider text-amber-300">unverified</span>
                    )}
                  </div>
                </td>
                <td className="px-4 py-3">
                  <span className={`text-xs px-2 py-0.5 rounded-full ${r.cls}`}>{r.label}</span>
                </td>
                <td className="px-4 py-3 text-sm text-ink-secondary">{u.articleCount}</td>
                <td className="px-4 py-3 text-sm text-ink-secondary">{u.apiTokenCount}</td>
                <td className="px-4 py-3 text-xs text-ink-muted">{fmt(u.createdAt)}</td>
                <td className="px-4 py-3 text-right">
                  <UserActions user={u} isMe={u.id === meId} others={others} />
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}
