"use client";

import { useState, useTransition } from "react";
import { Save, RotateCcw, Plus, Trash2 } from "lucide-react";
import {
  saveRobotsConfig,
  resetRobotsConfig,
  type RobotsRule,
} from "./_actions";

const COMMON_AGENTS = [
  { value: "*", label: "* (tất cả bot)" },
  { value: "Googlebot", label: "Googlebot" },
  { value: "Googlebot-Image", label: "Googlebot-Image" },
  { value: "Bingbot", label: "Bingbot" },
  { value: "GPTBot", label: "GPTBot (ChatGPT)" },
  { value: "ClaudeBot", label: "ClaudeBot" },
  { value: "anthropic-ai", label: "anthropic-ai" },
  { value: "PerplexityBot", label: "PerplexityBot" },
  { value: "CCBot", label: "CCBot (Common Crawl)" },
  { value: "Bytespider", label: "Bytespider (TikTok)" },
];

function previewRobotsTxt(rules: RobotsRule[], host: string, sitemap: string): string {
  const lines: string[] = [];
  for (const rule of rules) {
    lines.push(`User-agent: ${rule.userAgent}`);
    for (const a of rule.allow.filter(Boolean)) lines.push(`Allow: ${a}`);
    for (const d of rule.disallow.filter(Boolean)) lines.push(`Disallow: ${d}`);
    if (rule.crawlDelay) lines.push(`Crawl-delay: ${rule.crawlDelay}`);
    lines.push("");
  }
  if (host) lines.push(`Host: ${host}`);
  if (sitemap) lines.push(`Sitemap: ${sitemap}`);
  return lines.join("\n");
}

export function RobotsEditor({
  initialRules,
  initialHost,
  sitemap,
}: {
  initialRules: RobotsRule[];
  initialHost: string;
  sitemap: string;
}) {
  const [rules, setRules] = useState<RobotsRule[]>(initialRules);
  const [host, setHost] = useState(initialHost);
  const [pending, startTransition] = useTransition();
  const [msg, setMsg] = useState<string | null>(null);
  const [err, setErr] = useState<string | null>(null);

  function update(idx: number, patch: Partial<RobotsRule>) {
    setRules((prev) => prev.map((r, i) => (i === idx ? { ...r, ...patch } : r)));
  }

  function updateList(
    idx: number,
    field: "allow" | "disallow",
    value: string,
  ) {
    const list = value
      .split("\n")
      .map((s) => s.trim())
      .filter(Boolean);
    update(idx, { [field]: list });
  }

  function addRule() {
    setRules((prev) => [
      ...prev,
      { userAgent: "*", allow: ["/"], disallow: [], crawlDelay: null },
    ]);
  }

  function removeRule(idx: number) {
    setRules((prev) => prev.filter((_, i) => i !== idx));
  }

  function save() {
    setMsg(null);
    setErr(null);
    const fd = new FormData();
    fd.set("rules", JSON.stringify(rules));
    fd.set("host", host);
    startTransition(async () => {
      const r = await saveRobotsConfig(fd);
      if (r.ok) setMsg("Đã lưu robots.txt — revalidate trong 1 phút.");
      else setErr(r.error ?? "Lỗi");
    });
  }

  function reset() {
    if (!confirm("Reset về mặc định?")) return;
    startTransition(async () => {
      await resetRobotsConfig();
      window.location.reload();
    });
  }

  const preview = previewRobotsTxt(rules, host, sitemap);

  return (
    <div className="grid lg:grid-cols-2 gap-6">
      <div className="space-y-4">
        <div className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 p-4">
          <label className="block text-sm">
            <span className="block text-xs text-ink-muted mb-1">Host (canonical)</span>
            <input
              type="url"
              value={host}
              onChange={(e) => setHost(e.target.value)}
              placeholder="https://v2.finzone.io.vn"
              className="w-full px-3 py-2 rounded-lg bg-bg-base border border-stroke-subtle text-sm font-mono focus:border-accent-primary focus:outline-none"
            />
          </label>
        </div>

        {rules.map((rule, i) => (
          <div
            key={i}
            className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 p-4 space-y-3"
          >
            <div className="flex items-center justify-between gap-2">
              <span className="text-xs text-ink-muted">Rule #{i + 1}</span>
              {rules.length > 1 && (
                <button
                  type="button"
                  onClick={() => removeRule(i)}
                  className="text-xs text-rose-300 hover:bg-rose-500/10 rounded px-2 py-1 flex items-center gap-1"
                >
                  <Trash2 className="h-3 w-3" /> Xóa
                </button>
              )}
            </div>

            <label className="block text-sm">
              <span className="block text-xs text-ink-muted mb-1">User-agent</span>
              <input
                list={`agents-${i}`}
                value={rule.userAgent}
                onChange={(e) => update(i, { userAgent: e.target.value })}
                className="w-full px-3 py-2 rounded-lg bg-bg-base border border-stroke-subtle text-sm font-mono focus:border-accent-primary focus:outline-none"
              />
              <datalist id={`agents-${i}`}>
                {COMMON_AGENTS.map((a) => (
                  <option key={a.value} value={a.value}>
                    {a.label}
                  </option>
                ))}
              </datalist>
            </label>

            <div className="grid grid-cols-2 gap-3">
              <label className="block text-sm">
                <span className="block text-xs text-emerald-300/80 mb-1">
                  Allow (mỗi dòng 1 path)
                </span>
                <textarea
                  value={rule.allow.join("\n")}
                  onChange={(e) => updateList(i, "allow", e.target.value)}
                  rows={4}
                  placeholder="/&#10;/public/"
                  className="w-full px-3 py-2 rounded-lg bg-bg-base border border-stroke-subtle text-xs font-mono focus:border-accent-primary focus:outline-none resize-none"
                />
              </label>
              <label className="block text-sm">
                <span className="block text-xs text-rose-300/80 mb-1">
                  Disallow (mỗi dòng 1 path)
                </span>
                <textarea
                  value={rule.disallow.join("\n")}
                  onChange={(e) => updateList(i, "disallow", e.target.value)}
                  rows={4}
                  placeholder="/api/&#10;/admin"
                  className="w-full px-3 py-2 rounded-lg bg-bg-base border border-stroke-subtle text-xs font-mono focus:border-accent-primary focus:outline-none resize-none"
                />
              </label>
            </div>

            <label className="block text-sm">
              <span className="block text-xs text-ink-muted mb-1">
                Crawl-delay (giây, để trống nếu không dùng)
              </span>
              <input
                type="number"
                min={0}
                value={rule.crawlDelay ?? ""}
                onChange={(e) =>
                  update(i, {
                    crawlDelay: e.target.value ? Number(e.target.value) : null,
                  })
                }
                className="w-32 px-3 py-2 rounded-lg bg-bg-base border border-stroke-subtle text-sm font-mono focus:border-accent-primary focus:outline-none"
              />
            </label>
          </div>
        ))}

        <div className="flex flex-wrap items-center gap-2">
          <button
            type="button"
            onClick={addRule}
            className="text-sm px-3 py-1.5 rounded-lg bg-bg-elevated border border-stroke-subtle hover:border-accent-primary/40 flex items-center gap-1"
          >
            <Plus className="h-4 w-4" /> Thêm rule
          </button>
          <button
            type="button"
            onClick={save}
            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 flex items-center gap-1"
          >
            <Save className="h-4 w-4" />
            {pending ? "Đang lưu…" : "Lưu robots.txt"}
          </button>
          <button
            type="button"
            onClick={reset}
            disabled={pending}
            className="text-sm px-3 py-1.5 rounded-lg bg-bg-elevated border border-stroke-subtle hover:border-rose-500/40 hover:text-rose-300 flex items-center gap-1"
          >
            <RotateCcw className="h-4 w-4" /> Reset mặc định
          </button>
        </div>

        {msg && (
          <div className="text-xs text-emerald-300 rounded bg-emerald-500/10 border border-emerald-500/30 px-3 py-2">
            ✓ {msg}
          </div>
        )}
        {err && (
          <div className="text-xs text-rose-300 rounded bg-rose-500/10 border border-rose-500/30 px-3 py-2">
            ❌ {err}
          </div>
        )}
      </div>

      <div className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 overflow-hidden lg:sticky lg:top-4 self-start">
        <div className="px-4 py-3 border-b border-stroke-subtle bg-bg-elevated/40 flex items-center justify-between">
          <h3 className="font-medium">Preview robots.txt</h3>
          <a
            href="/robots.txt"
            target="_blank"
            rel="noopener noreferrer"
            className="text-xs text-accent-primary hover:underline"
          >
            Mở /robots.txt ↗
          </a>
        </div>
        <pre className="p-4 text-xs font-mono text-ink-secondary leading-relaxed whitespace-pre-wrap min-h-[300px]">
          {preview}
        </pre>
      </div>
    </div>
  );
}
