"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { Button, Card } from "@/components/ui";
import { Field, inputClass } from "@/components/ui/form";
import { addRedirectAction, deleteRedirectAction } from "@/lib/actions/site-admin";

export interface RedirectRow { id: string; fromPath: string; toPath: string; permanent: boolean }

export function RedirectsPanel({ siteId, rows }: { siteId: string; rows: RedirectRow[] }) {
  const router = useRouter();
  const [from, setFrom] = useState("");
  const [to, setTo] = useState("");
  const [permanent, setPermanent] = useState(true);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
  const [pending, start] = useTransition();

  function add() {
    setErrors({}); setMsg(null);
    start(async () => {
      const r = await addRedirectAction(siteId, { fromPath: from, toPath: to, permanent });
      if (r.ok) { setFrom(""); setTo(""); setMsg({ ok: true, text: "Redirect added" }); router.refresh(); }
      else { setErrors(r.fieldErrors ?? {}); setMsg({ ok: false, text: r.error }); }
    });
  }
  function remove(id: string) {
    start(async () => { const r = await deleteRedirectAction(id); if (r.ok) router.refresh(); else setMsg({ ok: false, text: r.error }); });
  }

  return (
    <div className="space-y-4">
      <Card className="p-4">
        <h2 className="mb-3 text-sm font-semibold">Add a redirect</h2>
        <div className="grid gap-3 sm:grid-cols-[1fr_1fr_auto_auto] sm:items-end">
          <Field id="rd-from" label="From path" error={errors.fromPath}><input id="rd-from" className={inputClass} placeholder="/old-page" value={from} onChange={(e) => setFrom(e.target.value)} aria-invalid={errors.fromPath ? true : undefined} /></Field>
          <Field id="rd-to" label="To path or URL" error={errors.toPath}><input id="rd-to" className={inputClass} placeholder="/new-page" value={to} onChange={(e) => setTo(e.target.value)} aria-invalid={errors.toPath ? true : undefined} /></Field>
          <label className="flex items-center gap-2 pb-2 text-sm"><input type="checkbox" checked={permanent} onChange={(e) => setPermanent(e.target.checked)} />Permanent (308)</label>
          <Button onClick={add} disabled={pending || !from || !to}>Add</Button>
        </div>
        <p role="status" aria-live="polite" className={msg ? (msg.ok ? "mt-2 text-sm text-success" : "mt-2 text-sm text-danger") : "sr-only"}>{msg?.text}</p>
      </Card>
      <Card>
        {rows.length === 0 ? <p className="p-4 text-sm text-muted-foreground">No redirects yet.</p> : (
          <table className="w-full text-left text-sm">
            <thead className="border-b border-border text-xs text-muted-foreground"><tr><th className="px-4 py-2 font-medium">From</th><th className="px-4 py-2 font-medium">To</th><th className="px-4 py-2 font-medium">Type</th><th className="px-4 py-2"><span className="sr-only">Actions</span></th></tr></thead>
            <tbody className="divide-y divide-border">
              {rows.map((r) => (
                <tr key={r.id}>
                  <td className="px-4 py-2 font-mono text-xs">{r.fromPath}</td>
                  <td className="px-4 py-2 font-mono text-xs break-all">{r.toPath}</td>
                  <td className="px-4 py-2">{r.permanent ? "Permanent" : "Temporary"}</td>
                  <td className="px-4 py-2 text-right"><Button variant="ghost" disabled={pending} aria-label={`Remove redirect from ${r.fromPath}`} onClick={() => remove(r.id)}>Remove</Button></td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </Card>
    </div>
  );
}
