"use client";

import { useState, useTransition } from "react";

import { useToast } from "@/components/admin/common/ToastProvider";
import type { NotFoundRow } from "@/lib/seo/intelligence";

export function RedirectsManager({ initial }: { initial: NotFoundRow[] }) {
  const [items, setItems] = useState(initial);
  const [pending, startTransition] = useTransition();
  const toast = useToast();
  const [path, setPath] = useState("");
  const [target, setTarget] = useState("");

  function disable(id: string) {
    if (!window.confirm("Onemogući ovaj redirect?")) return;
    startTransition(async () => {
      const res = await fetch("/api/admin/seo/redirects", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "disable", id }),
      });
      if (res.ok) {
        toast.success("Redirect onemogućen.");
        setItems((cur) => cur.filter((r) => r.id !== id));
      } else {
        toast.error("Greška.");
      }
    });
  }

  function addManual(e: React.FormEvent) {
    e.preventDefault();
    if (!path.startsWith("/") || !target) {
      toast.error("Putanja mora počinjati sa „/“ i target ne sme biti prazan.");
      return;
    }
    startTransition(async () => {
      const res = await fetch("/api/admin/seo/redirects", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "create", path, redirectTo: target }),
      });
      if (res.ok) {
        toast.success("Redirect dodat.");
        window.location.reload();
      } else {
        toast.error("Greška.");
      }
    });
  }

  return (
    <div className="space-y-6">
      <form onSubmit={addManual} className="surface space-y-3 rounded-2xl p-5">
        <h3 className="font-semibold">Ručno dodaj redirect</h3>
        <div className="grid gap-3 sm:grid-cols-2">
          <input
            type="text"
            value={path}
            onChange={(e) => setPath(e.target.value)}
            placeholder="/stara-putanja"
            className="rounded-xl border border-border bg-white px-3 py-2 text-sm"
          />
          <input
            type="text"
            value={target}
            onChange={(e) => setTarget(e.target.value)}
            placeholder="/nova-putanja"
            className="rounded-xl border border-border bg-white px-3 py-2 text-sm"
          />
        </div>
        <button type="submit" disabled={pending} className="primary-button inline-flex">
          Dodaj redirect
        </button>
      </form>

      <div className="surface overflow-x-auto rounded-2xl p-5">
        <h3 className="mb-3 font-semibold">Aktivni redirect-i</h3>
        <table className="w-full text-left text-sm">
          <thead className="text-xs uppercase tracking-wider text-muted-foreground">
            <tr>
              <th className="px-2 py-2">Od</th>
              <th className="px-2 py-2">Ka</th>
              <th className="px-2 py-2">Pogađaja</th>
              <th className="px-2 py-2">Akcija</th>
            </tr>
          </thead>
          <tbody>
            {items.map((r) => (
              <tr key={r.id} className="border-t border-border/40">
                <td className="px-2 py-2 font-mono text-xs">{r.path}</td>
                <td className="px-2 py-2 font-mono text-xs">{r.redirectTo}</td>
                <td className="px-2 py-2">{r.count}</td>
                <td className="px-2 py-2">
                  <button
                    type="button"
                    onClick={() => disable(r.id)}
                    disabled={pending}
                    className="rounded-full border border-rose-300 px-3 py-1 text-xs font-semibold text-rose-600 transition hover:bg-rose-500 hover:text-white"
                  >
                    Onemogući
                  </button>
                </td>
              </tr>
            ))}
            {items.length === 0 && (
              <tr>
                <td colSpan={4} className="px-2 py-6 text-center text-muted-foreground">
                  Nema aktivnih redirect-a.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
