import { prisma } from "@/lib/prisma";
import { updatePageSeo } from "@/lib/actions/seo";
import SeoTabs from "@/components/admin/SeoTabs";
import SaveIconButton from "@/components/admin/SaveIconButton";

function LengthHint({ value, ideal }: { value: string; ideal: number }) {
  const len = value.length;
  if (len === 0) return <span className="text-stone-400">not set</span>;
  const over = len > ideal;
  return <span className={over ? "text-amber-600" : "text-stone-400"}>{len} chars{over ? ` (over ${ideal})` : ""}</span>;
}

export default async function AdminPageSeoPage() {
  const pages = await prisma.pageSeo.findMany({ orderBy: { path: "asc" } });

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Page SEO</h1>
      <p className="mt-1 text-sm text-stone-500">Title and description for the site&apos;s fixed pages (Home, About, policies, etc.).</p>

      <SeoTabs active="/iv-manage-84x2/seo/pages" />

      <div className="space-y-3">
        {pages.map((p) => (
          <div key={p.id} className="rounded-lg border border-rose-100 bg-white p-4">
            <div className="flex items-center justify-between">
              <span className="font-medium text-stone-800">{p.label}</span>
              <span className="text-xs text-stone-400">{p.path}</span>
            </div>
            <form action={updatePageSeo.bind(null, p.id)} className="mt-3 space-y-2">
              <div>
                <label className="text-xs text-stone-500">
                  Title <LengthHint value={p.title ?? ""} ideal={60} />
                </label>
                <input
                  name="title"
                  defaultValue={p.title ?? ""}
                  className="mt-1 block w-full rounded-md border border-stone-300 px-2 py-1.5 text-sm"
                />
              </div>
              <div>
                <label className="text-xs text-stone-500">
                  Description <LengthHint value={p.description ?? ""} ideal={160} />
                </label>
                <textarea
                  name="description"
                  rows={2}
                  defaultValue={p.description ?? ""}
                  className="mt-1 block w-full rounded-md border border-stone-300 px-2 py-1.5 text-sm"
                />
              </div>
              <SaveIconButton />
            </form>
          </div>
        ))}
      </div>
    </div>
  );
}
