import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { updateProductSeo } 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 AdminProductSeoPage() {
  const products = await prisma.product.findMany({
    where: { active: true },
    include: { category: true },
    orderBy: { name: "asc" },
  });

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Product SEO</h1>
      <p className="mt-1 text-sm text-stone-500">
        Leave blank to fall back to the product name / description. Aim for titles under ~60 characters and descriptions under ~160.
      </p>

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

      <div className="space-y-3">
        {products.map((p) => (
          <div key={p.id} className="rounded-lg border border-rose-100 bg-white p-4">
            <div className="flex items-center justify-between">
              <Link href={`/iv-manage-84x2/products/${p.id}`} className="font-medium text-rose-700 hover:underline">
                {p.name}
              </Link>
              <span className="text-xs text-stone-400">{p.category.name}</span>
            </div>
            <form action={updateProductSeo.bind(null, p.id)} className="mt-3 space-y-2">
              <div>
                <label className="text-xs text-stone-500">
                  Meta title <LengthHint value={p.metaTitle ?? ""} ideal={60} />
                </label>
                <input
                  name="metaTitle"
                  defaultValue={p.metaTitle ?? ""}
                  placeholder={p.name}
                  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">
                  Meta description <LengthHint value={p.metaDescription ?? ""} ideal={160} />
                </label>
                <textarea
                  name="metaDescription"
                  rows={2}
                  defaultValue={p.metaDescription ?? ""}
                  placeholder={p.description.slice(0, 160)}
                  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>
  );
}
