import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { env } from "@/lib/env";
import { listSanityProductSeoRows } from "@/lib/sanity/queries";

type Props = {
  searchParams: Promise<{ key?: string }>;
};

type SeoRow = {
  url: string;
  type: "static" | "product";
  title: string;
  titleLength: number;
  descriptionLength: number;
  score: number;
  issues: string[];
};

export const metadata: Metadata = {
  title: "Admin SEO",
  robots: { index: false, follow: false },
};

const STATIC_ROWS_INPUT = [
  { url: "/", title: "Stylunique | Boutique personnalisable", description: "Cadeaux, gourmandises et papeterie personnalisés pour vos événements." },
  { url: "/boutique", title: "Boutique", description: "Parcourez tous les produits Stylunique et trouvez la création personnalisée idéale." },
  { url: "/en-savoir-plus", title: "En savoir plus", description: "Informations utiles sur la personnalisation, les délais et la qualité des créations." },
  { url: "/mentions-legales", title: "Mentions légales", description: "Informations légales du site Stylunique." },
  { url: "/politique-confidentialite", title: "Politique de confidentialité", description: "Traitement des données personnelles sur Stylunique." },
  { url: "/politique-cookies", title: "Politique cookies", description: "Gestion des cookies et du consentement sur Stylunique." },
];

function scoreSeo(input: { title: string; description: string; hasImage: boolean; slug: string }) {
  const issues: string[] = [];
  let score = 0;

  const titleLength = input.title.trim().length;
  const descriptionLength = input.description.trim().length;

  if (titleLength >= 20 && titleLength <= 70) score += 30;
  else if (titleLength > 0) {
    score += 15;
    issues.push("Title length hors plage idéale (20-70).");
  } else {
    issues.push("Title manquant.");
  }

  if (descriptionLength >= 80 && descriptionLength <= 170) score += 30;
  else if (descriptionLength > 0) {
    score += 15;
    issues.push("Meta description hors plage idéale (80-170).");
  } else {
    issues.push("Meta description manquante.");
  }

  if (input.hasImage) score += 20;
  else issues.push("Image principale manquante.");

  if (/^[a-z0-9-]+$/.test(input.slug)) score += 20;
  else issues.push("Slug non optimal (caractères non SEO-friendly).");

  return { score, issues, titleLength, descriptionLength };
}

function buildStaticRows(): SeoRow[] {
  return STATIC_ROWS_INPUT.map((row) => {
    const seo = scoreSeo({
      title: row.title,
      description: row.description,
      hasImage: true,
      slug: row.url === "/" ? "home" : row.url.replace(/^\//, "").replace(/\//g, "-"),
    });
    return {
      url: row.url,
      type: "static",
      title: row.title,
      titleLength: seo.titleLength,
      descriptionLength: seo.descriptionLength,
      score: seo.score,
      issues: seo.issues,
    };
  });
}

function buildProductRows(products: Awaited<ReturnType<typeof listSanityProductSeoRows>>): SeoRow[] {
  return products.map((product) => {
    const description = (product.shortDescription || product.description || "").trim();
    const hasImage = Boolean(product.imageUrl || product.gallery?.[0]?.url);
    const seo = scoreSeo({
      title: product.title || "",
      description,
      hasImage,
      slug: product.handle || "",
    });

    return {
      url: `/produits/${product.handle}`,
      type: "product",
      title: product.title || "",
      titleLength: seo.titleLength,
      descriptionLength: seo.descriptionLength,
      score: seo.score,
      issues: seo.issues,
    };
  });
}

export default async function AdminSeoPage({ searchParams }: Props) {
  const { key } = await searchParams;

  if (!env.seoAdminKey) {
    return (
      <section className="space-y-3 rounded-2xl border border-[#ffdede] bg-white p-6">
        <h1 className="font-serif text-3xl text-[var(--foreground)]">Admin SEO</h1>
        <p className="text-sm text-[var(--muted)]">Definis la variable d&apos;environnement <code>SEO_ADMIN_KEY</code> pour proteger cette page.</p>
      </section>
    );
  }

  if (key !== env.seoAdminKey) {
    notFound();
  }

  const [productRows, staticRows] = await Promise.all([listSanityProductSeoRows(1200), Promise.resolve(buildStaticRows())]);
  const rows = [...staticRows, ...buildProductRows(productRows)].sort((a, b) => a.score - b.score);

  const total = rows.length;
  const avgScore = total ? Math.round(rows.reduce((acc, row) => acc + row.score, 0) / total) : 0;
  const lowScore = rows.filter((row) => row.score < 60).length;
  const missingDescriptions = rows.filter((row) => row.descriptionLength === 0).length;
  const missingTitle = rows.filter((row) => row.titleLength === 0).length;

  return (
    <div className="space-y-6">
      <header className="rounded-[1.5rem] border border-[#ffdede] bg-white p-6">
        <p className="text-xs font-semibold uppercase tracking-[0.14em] text-[var(--accent-3)]">Admin</p>
        <h1 className="mt-1 font-serif text-4xl text-[var(--foreground)]">SEO Dashboard</h1>
        <p className="mt-2 text-sm text-[var(--muted)]">Vue globale + analyse page par page.</p>
      </header>

      <section className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
        <article className="rounded-xl border border-[var(--line)] bg-white p-4">
          <p className="text-xs text-[var(--muted)]">Pages auditees</p>
          <p className="mt-1 text-2xl font-semibold text-[var(--foreground)]">{total}</p>
        </article>
        <article className="rounded-xl border border-[var(--line)] bg-white p-4">
          <p className="text-xs text-[var(--muted)]">Score SEO moyen</p>
          <p className="mt-1 text-2xl font-semibold text-[var(--foreground)]">{avgScore}/100</p>
        </article>
        <article className="rounded-xl border border-[var(--line)] bg-white p-4">
          <p className="text-xs text-[var(--muted)]">Pages &lt; 60</p>
          <p className="mt-1 text-2xl font-semibold text-[var(--foreground)]">{lowScore}</p>
        </article>
        <article className="rounded-xl border border-[var(--line)] bg-white p-4">
          <p className="text-xs text-[var(--muted)]">Descriptions manquantes</p>
          <p className="mt-1 text-2xl font-semibold text-[var(--foreground)]">{missingDescriptions}</p>
        </article>
      </section>

      <section className="overflow-hidden rounded-xl border border-[var(--line)] bg-white">
        <div className="overflow-x-auto">
          <table className="min-w-full text-sm">
            <thead className="bg-[#fff7f7] text-left text-xs uppercase tracking-[0.08em] text-[var(--muted)]">
              <tr>
                <th className="px-4 py-3">URL</th>
                <th className="px-4 py-3">Type</th>
                <th className="px-4 py-3">Score</th>
                <th className="px-4 py-3">Title</th>
                <th className="px-4 py-3">Description</th>
                <th className="px-4 py-3">Issues</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((row) => (
                <tr key={row.url} className="border-t border-[var(--line)] align-top">
                  <td className="px-4 py-3 font-medium text-[var(--foreground)]">{row.url}</td>
                  <td className="px-4 py-3 text-[var(--muted)]">{row.type}</td>
                  <td className="px-4 py-3">
                    <span
                      className={`inline-flex rounded-full px-2 py-1 text-xs font-semibold ${
                        row.score >= 80 ? "bg-[#eef9f2] text-[#156b3f]" : row.score >= 60 ? "bg-[#fff7ea] text-[#8b5a14]" : "bg-[#fff0f0] text-[#9a1f1f]"
                      }`}
                    >
                      {row.score}/100
                    </span>
                  </td>
                  <td className="px-4 py-3 text-[var(--muted)]">{row.titleLength}</td>
                  <td className="px-4 py-3 text-[var(--muted)]">{row.descriptionLength}</td>
                  <td className="px-4 py-3 text-[var(--muted)]">
                    {row.issues.length ? row.issues.join(" | ") : "OK"}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>

      {missingTitle > 0 ? (
        <p className="text-xs text-[var(--muted)]">Attention: {missingTitle} page(s) ont un title vide.</p>
      ) : null}
    </div>
  );
}

