"use client";

import Link from "next/link";
import { useState, useTransition, useMemo } from "react";
import { useRouter } from "next/navigation";
import {
  bulkPublishAction,
  bulkUnpublishAction,
  bulkDeleteAction,
  bulkChangeCategoryAction,
} from "./_actions";

export type ArticleRow = {
  id: string;
  slug: string;
  title: string;
  status: string;
  publishedAt: Date | null;
  scheduledFor: Date | null;
  updatedAt: Date;
  seoScore: number | null;
  viewCount: number;
  authorName: string;
  categoryName: string | null;
  categorySlug: string | null;
};

export type CategoryOption = { slug: string; name: string };

const STATUS_LABELS: Record<string, { label: string; cls: string }> = {
  draft: { label: "Nháp", cls: "bg-bg-overlay text-ink-muted" },
  published: { label: "Đã đăng", cls: "bg-emerald-500/15 text-emerald-300" },
  scheduled: { label: "Hẹn giờ", cls: "bg-amber-500/15 text-amber-300" },
  archived: { label: "Lưu trữ", cls: "bg-rose-500/15 text-rose-300" },
};

function fmtDate(d: Date | null): string {
  if (!d) return "—";
  return new Intl.DateTimeFormat("vi-VN", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  }).format(new Date(d));
}

function fmtNum(n: number): string {
  if (n >= 1000) return `${(n / 1000).toFixed(1)}K`;
  return String(n);
}

export function ArticlesTable({
  rows,
  categories,
}: {
  rows: ArticleRow[];
  categories: CategoryOption[];
}) {
  const router = useRouter();
  const [pending, startTransition] = useTransition();
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
  const [bulkCat, setBulkCat] = useState("");

  const allIds = useMemo(() => rows.map((r) => r.id), [rows]);
  const allSelected = selected.size > 0 && selected.size === allIds.length;
  const someSelected = selected.size > 0 && !allSelected;

  function toggleAll() {
    if (allSelected) setSelected(new Set());
    else setSelected(new Set(allIds));
  }

  function toggle(id: string) {
    const next = new Set(selected);
    if (next.has(id)) next.delete(id);
    else next.add(id);
    setSelected(next);
  }

  function ids(): string[] {
    return Array.from(selected);
  }

  function run(label: string, fn: () => Promise<{ ok: boolean; count: number; error?: string }>) {
    setMsg(null);
    startTransition(async () => {
      const res = await fn();
      if (!res.ok) setMsg({ ok: false, text: res.error ?? "Lỗi không rõ." });
      else {
        setMsg({ ok: true, text: `${label}: ${res.count} bài.` });
        setSelected(new Set());
        router.refresh();
      }
    });
  }

  function bulkPublish() {
    run("Đã xuất bản", () => bulkPublishAction(ids()));
  }
  function bulkUnpublish() {
    run("Đã gỡ", () => bulkUnpublishAction(ids()));
  }
  function bulkDelete() {
    if (!confirm(`Xóa ${selected.size} bài? Không thể hoàn tác.`)) return;
    run("Đã xóa", () => bulkDeleteAction(ids()));
  }
  function bulkMoveCat() {
    if (!bulkCat) {
      setMsg({ ok: false, text: "Chọn chuyên mục đích." });
      return;
    }
    run("Đã chuyển chuyên mục", () => bulkChangeCategoryAction(ids(), bulkCat));
  }

  return (
    <div>
      {selected.size > 0 && (
        <div className="sticky top-0 z-10 mb-3 rounded-xl border border-accent-primary/40 bg-bg-elevated/95 backdrop-blur p-3 flex flex-wrap items-center gap-3 shadow-lg">
          <span className="text-sm font-medium">
            Đã chọn <strong className="text-accent-primary">{selected.size}</strong> bài
          </span>
          <div className="flex flex-wrap gap-2 ml-auto">
            <button
              type="button"
              onClick={bulkPublish}
              disabled={pending}
              className="text-xs px-3 py-1.5 rounded bg-emerald-500/15 text-emerald-300 hover:bg-emerald-500/25 disabled:opacity-50"
            >
              Xuất bản
            </button>
            <button
              type="button"
              onClick={bulkUnpublish}
              disabled={pending}
              className="text-xs px-3 py-1.5 rounded bg-amber-500/15 text-amber-300 hover:bg-amber-500/25 disabled:opacity-50"
            >
              Gỡ
            </button>
            <select
              value={bulkCat}
              onChange={(e) => setBulkCat(e.target.value)}
              disabled={pending}
              className="text-xs px-2 py-1.5 rounded bg-bg-elevated border border-stroke-subtle"
            >
              <option value="">Chuyển chuyên mục…</option>
              {categories.map((c) => (
                <option key={c.slug} value={c.slug}>
                  {c.name}
                </option>
              ))}
            </select>
            <button
              type="button"
              onClick={bulkMoveCat}
              disabled={pending || !bulkCat}
              className="text-xs px-3 py-1.5 rounded bg-sky-500/15 text-sky-300 hover:bg-sky-500/25 disabled:opacity-50"
            >
              Chuyển
            </button>
            <button
              type="button"
              onClick={bulkDelete}
              disabled={pending}
              className="text-xs px-3 py-1.5 rounded bg-rose-500/15 text-rose-300 hover:bg-rose-500/25 disabled:opacity-50"
            >
              Xóa
            </button>
            <button
              type="button"
              onClick={() => setSelected(new Set())}
              className="text-xs px-3 py-1.5 rounded text-ink-muted hover:text-ink-primary"
            >
              Bỏ chọn
            </button>
          </div>
        </div>
      )}

      {msg && (
        <div
          className={`mb-3 rounded-lg border px-3 py-2 text-sm ${
            msg.ok
              ? "border-emerald-500/40 bg-emerald-500/10 text-emerald-300"
              : "border-rose-500/40 bg-rose-500/10 text-rose-300"
          }`}
        >
          {msg.text}
        </div>
      )}

      <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 w-10">
                <input
                  type="checkbox"
                  checked={allSelected}
                  ref={(el) => {
                    if (el) el.indeterminate = someSelected;
                  }}
                  onChange={toggleAll}
                />
              </th>
              <th className="px-4 py-2.5 font-medium text-ink-muted">Tiêu đề</th>
              <th className="px-4 py-2.5 font-medium text-ink-muted">Chuyên mục</th>
              <th className="px-4 py-2.5 font-medium text-ink-muted">Lượt xem</th>
              <th className="px-4 py-2.5 font-medium text-ink-muted">SEO</th>
              <th className="px-4 py-2.5 font-medium text-ink-muted">TT</th>
              <th className="px-4 py-2.5 font-medium text-ink-muted">Cập nhật</th>
            </tr>
          </thead>
          <tbody>
            {rows.map((a) => {
              const st = STATUS_LABELS[a.status] ?? STATUS_LABELS.draft;
              const isSelected = selected.has(a.id);
              const score = a.seoScore ?? 0;
              return (
                <tr
                  key={a.id}
                  className={`border-b border-stroke-subtle/60 last:border-0 transition ${
                    isSelected ? "bg-accent-primary/5" : "hover:bg-bg-elevated/30"
                  }`}
                >
                  <td className="px-4 py-3 align-top">
                    <input
                      type="checkbox"
                      checked={isSelected}
                      onChange={() => toggle(a.id)}
                    />
                  </td>
                  <td className="px-4 py-3">
                    <Link
                      href={`/admin/articles/${a.id}`}
                      className="font-medium text-ink-primary hover:text-accent-primary line-clamp-1"
                    >
                      {a.title}
                    </Link>
                    <div className="text-xs text-ink-muted font-mono mt-0.5">/{a.slug}</div>
                  </td>
                  <td className="px-4 py-3 text-ink-secondary">
                    {a.categoryName ?? <span className="text-ink-muted">—</span>}
                  </td>
                  <td className="px-4 py-3 text-sm text-ink-secondary">{fmtNum(a.viewCount)}</td>
                  <td className="px-4 py-3">
                    <span
                      className={`text-xs font-medium ${
                        score >= 70
                          ? "text-emerald-300"
                          : score >= 50
                            ? "text-amber-300"
                            : "text-rose-300"
                      }`}
                    >
                      {score}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <span className={`text-xs px-2 py-0.5 rounded-full ${st.cls}`}>
                      {st.label}
                    </span>
                    {a.status === "scheduled" && a.scheduledFor && (
                      <div className="text-[10px] text-amber-300/80 mt-1">
                        ← {fmtDate(a.scheduledFor)}
                      </div>
                    )}
                  </td>
                  <td className="px-4 py-3 text-xs text-ink-muted">{fmtDate(a.updatedAt)}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}
