"use client";

import { useRouter } from "next/navigation";
import { useState, useTransition } from "react";
import { faNumber } from "@/lib/format";
import { autoFixSeoAction } from "@/server/admin/seo";

export function AutoFixButton({ count }: { count: number }) {
  const router = useRouter();
  const [pending, start] = useTransition();
  const [msg, setMsg] = useState("");
  return (
    <div className="flex flex-wrap items-center gap-3">
      <button
        type="button"
        className="btn-primary h-11 px-6"
        disabled={pending || count === 0}
        onClick={() =>
          start(async () => {
            const { fixed } = await autoFixSeoAction();
            setMsg(`${faNumber(fixed)} مورد بهینه شد`);
            router.refresh();
          })
        }
      >
        {pending ? "در حال بهینه‌سازی…" : `بهینه‌سازی خودکار (${faNumber(count)} مورد)`}
      </button>
      {msg && <p role="status" className="text-sm">✓ {msg}</p>}
    </div>
  );
}
