"use client";

import { useTransition } from "react";
import { Trash2 } from "lucide-react";
import { revokeApiTokenAction } from "./_actions";

type Token = {
  id: string;
  name: string;
  prefix: string;
  scopes: string[];
  ipAllowlist: string[];
  lastUsedAt: Date | null;
  expiresAt: Date | null;
  revoked: boolean;
  createdAt: Date;
};

export function TokenRow({ token }: { token: Token }) {
  const [pending, start] = useTransition();

  function onRevoke() {
    if (!confirm(`Thu hồi token "${token.name}"? Hành động không thể hoàn tác.`)) return;
    start(async () => {
      await revokeApiTokenAction(token.id);
    });
  }

  const status = token.revoked
    ? { label: "Đã thu hồi", cls: "text-rose-300 bg-rose-500/10 border-rose-500/30" }
    : token.expiresAt && token.expiresAt < new Date()
    ? { label: "Hết hạn", cls: "text-amber-300 bg-amber-500/10 border-amber-500/30" }
    : { label: "Hoạt động", cls: "text-emerald-300 bg-emerald-500/10 border-emerald-500/30" };

  return (
    <tr className="border-b border-stroke-subtle/60 last:border-b-0 hover:bg-bg-elevated/30">
      <td className="px-4 py-3 font-medium text-ink-primary">{token.name}</td>
      <td className="px-4 py-3 font-mono text-xs text-ink-muted">{token.prefix}…</td>
      <td className="px-4 py-3">
        <div className="flex flex-wrap gap-1">
          {token.scopes.map((s) => (
            <span
              key={s}
              className="text-[10px] font-mono px-1.5 py-0.5 rounded border border-stroke-subtle bg-bg-overlay"
            >
              {s}
            </span>
          ))}
        </div>
      </td>
      <td className="px-4 py-3 text-xs text-ink-muted">
        {token.lastUsedAt ? new Date(token.lastUsedAt).toLocaleString("vi-VN") : "—"}
      </td>
      <td className="px-4 py-3 text-xs text-ink-muted">
        {token.expiresAt ? new Date(token.expiresAt).toLocaleDateString("vi-VN") : "không"}
      </td>
      <td className="px-4 py-3">
        <span className={`inline-block text-[10px] uppercase tracking-wider px-2 py-0.5 rounded border ${status.cls}`}>
          {status.label}
        </span>
      </td>
      <td className="px-4 py-3 text-right">
        {!token.revoked ? (
          <button
            type="button"
            onClick={onRevoke}
            disabled={pending}
            className="inline-flex items-center gap-1 rounded-md border border-stroke-subtle px-2 py-1 text-xs text-rose-300 hover:bg-rose-500/10 disabled:opacity-50"
          >
            <Trash2 className="h-3 w-3" /> Thu hồi
          </button>
        ) : (
          <span className="text-xs text-ink-muted">—</span>
        )}
      </td>
    </tr>
  );
}
