"use client";

import { useState, useTransition } from "react";
import { bulkReanalyzeAction, type BulkReanalyzeResult } from "./_actions";

export function ReanalyzeButton() {
  const [pending, startTransition] = useTransition();
  const [result, setResult] = useState<BulkReanalyzeResult | null>(null);
  const [publishedOnly, setPublishedOnly] = useState(false);

  function run() {
    if (
      !confirm(
        publishedOnly
          ? "Chạy lại analyzer cho TẤT CẢ bài đã publish? Cập nhật trực tiếp DB."
          : "Chạy lại analyzer cho TẤT CẢ bài (kể cả draft)? Cập nhật trực tiếp DB.",
      )
    )
      return;
    setResult(null);
    startTransition(async () => {
      try {
        const r = await bulkReanalyzeAction({ publishedOnly });
        setResult(r);
      } catch (e) {
        setResult({
          ok: false,
          scanned: 0,
          updated: 0,
          improved: 0,
          worsened: 0,
          unchanged: 0,
          avgBefore: 0,
          avgAfter: 0,
          error: e instanceof Error ? e.message : "Lỗi không xác định",
        });
      }
    });
  }

  return (
    <div className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 p-4 mb-6">
      <div className="flex items-center justify-between gap-3 flex-wrap">
        <div>
          <h2 className="font-display font-semibold text-sm">Bulk re-analyze</h2>
          <p className="text-xs text-ink-muted mt-0.5">
            Chạy lại 19 SEO checks cho toàn bộ bài. Hữu ích sau khi import WP hoặc
            nâng cấp analyzer.
          </p>
        </div>

        <div className="flex items-center gap-2">
          <label className="flex items-center gap-1.5 text-xs text-ink-secondary cursor-pointer">
            <input
              type="checkbox"
              checked={publishedOnly}
              onChange={(e) => setPublishedOnly(e.target.checked)}
              className="rounded border-stroke-subtle"
            />
            Chỉ bài đã publish
          </label>
          <button
            type="button"
            onClick={run}
            disabled={pending}
            className="text-xs px-3 py-1.5 rounded-lg bg-accent-primary/15 text-accent-primary border border-accent-primary/40 hover:bg-accent-primary/25 disabled:opacity-50"
          >
            {pending ? "Đang chạy…" : "↻ Chạy lại tất cả"}
          </button>
        </div>
      </div>

      {result && (
        <div
          className={`mt-3 text-xs rounded-lg border px-3 py-2 ${
            result.ok
              ? "bg-emerald-500/10 border-emerald-500/30 text-emerald-200"
              : "bg-rose-500/10 border-rose-500/30 text-rose-200"
          }`}
        >
          {result.ok ? (
            <>
              ✅ Đã quét <strong>{result.scanned}</strong> bài, cập nhật{" "}
              <strong>{result.updated}</strong>. Trung bình{" "}
              <span className="font-mono">{result.avgBefore}</span> →{" "}
              <span className="font-mono font-bold">{result.avgAfter}</span> điểm. Tăng{" "}
              <span className="text-emerald-300 font-semibold">{result.improved}</span> ·
              giảm{" "}
              <span className="text-rose-300 font-semibold">{result.worsened}</span> ·
              giữ nguyên{" "}
              <span className="text-ink-muted">{result.unchanged}</span>.
            </>
          ) : (
            <>❌ {result.error}</>
          )}
        </div>
      )}
    </div>
  );
}
