"use client";

import { useState, useTransition } from "react";
import { Send } from "lucide-react";
import { pingSearchEnginesAction, type PingResult } from "./_actions";

export function PingButton() {
  const [pending, startTransition] = useTransition();
  const [result, setResult] = useState<PingResult | null>(null);

  function run() {
    setResult(null);
    startTransition(async () => {
      try {
        const r = await pingSearchEnginesAction();
        setResult(r);
      } catch (e) {
        setResult({
          ok: false,
          results: [],
          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">
      <h3 className="font-medium mb-2 flex items-center gap-2">
        <Send className="h-4 w-4 text-accent-primary" />
        Ping search engines
      </h3>
      <p className="text-xs text-ink-muted mb-3">
        Báo Bing & IndexNow rằng sitemap có thay đổi mới. Google đã ngưng ping API
        — dùng Search Console để submit.
      </p>

      <button
        type="button"
        onClick={run}
        disabled={pending}
        className="text-sm 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 ping…" : "Ping ngay"}
      </button>

      {result && (
        <div className="mt-3 space-y-1.5">
          {result.error ? (
            <div className="text-xs text-rose-300 rounded bg-rose-500/10 border border-rose-500/30 px-2 py-1.5">
              ❌ {result.error}
            </div>
          ) : (
            result.results.map((r) => (
              <div
                key={r.engine}
                className={`text-xs flex items-center justify-between rounded px-2 py-1.5 border ${
                  r.ok
                    ? "bg-emerald-500/10 border-emerald-500/30 text-emerald-200"
                    : "bg-amber-500/10 border-amber-500/30 text-amber-200"
                }`}
              >
                <span className="font-medium">{r.ok ? "✓" : "⚠"} {r.engine}</span>
                <span className="font-mono text-[11px]">{r.status}</span>
              </div>
            ))
          )}
        </div>
      )}
    </div>
  );
}
