import type { Metadata } from "next";
import Link from "next/link";
import Image from "next/image";
import { notFound } from "next/navigation";
import { ArrowLeft, ArrowRight } from "lucide-react";
import DemoSection from "@/components/DemoSection";
import {
  RESOURCE_POSTS,
  RESOURCE_TABS,
  getPost,
  postsByTab,
} from "@/lib/resources-posts";

export function generateStaticParams() {
  return RESOURCE_POSTS.map((p) => ({ slug: p.slug }));
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>;
}): Promise<Metadata> {
  const { slug } = await params;
  const post = getPost(slug);
  if (!post) return { title: "Resource not found" };
  return {
    title: post.title,
    description: post.excerpt,
    alternates: { canonical: `/resources/${post.slug}` },
    openGraph: {
      type: "article",
      title: post.title,
      description: post.excerpt,
      publishedTime: post.date,
      authors: ["MxERP Content Team"],
    },
    twitter: {
      card: "summary_large_image",
      site: "@ACGInfotechLtd",
      creator: "@ACGInfotechLtd",
      title: post.title,
      description: post.excerpt,
    },
  };
}

function formatDate(iso: string): string {
  const d = new Date(iso + "T00:00:00");
  if (Number.isNaN(d.getTime())) return iso;
  return d.toLocaleDateString("en-IN", { day: "numeric", month: "short", year: "numeric" });
}

export default async function ResourceArticlePage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const post = getPost(slug);
  if (!post) notFound();

  const tabLabel = RESOURCE_TABS.find((t) => t.id === post.tab)?.label ?? post.tab;
  const siblings = postsByTab(post.tab).filter((p) => p.slug !== post.slug);
  const related = siblings.slice(0, 3);
  const idx = RESOURCE_POSTS.findIndex((p) => p.slug === post.slug);
  const prev = RESOURCE_POSTS[idx - 1];
  const next = RESOURCE_POSTS[idx + 1];

  return (
    <>
      <section className="bg-navy py-16 text-white max-md:py-12">
        <div className="mx-container max-w-3xl">
          <nav aria-label="Breadcrumb" className="flex items-center gap-2 font-mono text-xs text-faint">
            <Link href="/" className="hover:text-white">Home</Link>
            <span aria-hidden="true">/</span>
            <Link href="/resources" className="hover:text-white">Resources</Link>
            <span aria-hidden="true">/</span>
            <span className="text-white">{tabLabel}</span>
          </nav>
          <p className="mt-5 inline-flex items-center rounded-md bg-white/10 px-2.5 py-1 font-mono text-[10px] font-semibold tracking-[0.12em] text-herosub">
            {tabLabel.toUpperCase()}
          </p>
          <h1 className="mt-3 font-display text-[clamp(28px,3.4vw,42px)] font-bold leading-[1.12]">
            {post.title}
          </h1>
          <p className="mt-3 text-[14px] text-herosub">
            {formatDate(post.date)} · {post.readMins} min read · MxERP Content Team
          </p>
        </div>
      </section>

      <section className="py-14 max-md:py-10">
        <div className="mx-container max-w-3xl">
          {post.coverImage && (
            <div className="relative mb-8 aspect-[16/8] overflow-hidden rounded-2xl border border-line">
              <Image
                src={post.coverImage}
                alt={post.title}
                fill
                sizes="(max-width: 768px) 100vw, 768px"
                className="object-cover"
                priority
              />
            </div>
          )}
          <p className="rounded-xl bg-canvas px-5 py-4 text-[15px] font-medium leading-relaxed text-body">
            {post.excerpt}
          </p>
          <div
            className="article-body mt-8"
            dangerouslySetInnerHTML={{ __html: post.contentHtml }}
          />
          <div className="mt-10 flex flex-wrap items-center justify-between gap-3 border-t border-line pt-6">
            <Link
              href="/resources#guides"
              className="inline-flex min-h-[44px] items-center gap-2 rounded-lg border border-line bg-white px-5 text-sm font-semibold text-ink hover:border-brand hover:text-brand"
            >
              <ArrowLeft size={16} aria-hidden="true" />
              All resources
            </Link>
            <div className="flex gap-3">
              {prev && (
                <Link
                  href={`/resources/${prev.slug}`}
                  className="inline-flex min-h-[44px] items-center rounded-lg bg-canvas px-5 text-sm font-semibold text-ink hover:bg-brand-tint hover:text-brand"
                >
                  ← Newer
                </Link>
              )}
              {next && (
                <Link
                  href={`/resources/${next.slug}`}
                  className="inline-flex min-h-[44px] items-center rounded-lg bg-navy px-5 text-sm font-semibold text-white hover:bg-brand-dark"
                >
                  Older →
                </Link>
              )}
            </div>
          </div>
        </div>
      </section>

      {related.length > 0 && (
        <section className="bg-canvas py-14 max-md:py-10">
          <div className="mx-container max-w-5xl">
            <h2 className="font-display text-[24px] font-bold text-ink">
              Related reading
            </h2>
            <div className="mt-6 grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
              {related.map((r) => (
                <Link
                  key={r.slug}
                  href={`/resources/${r.slug}`}
                  className="group rounded-2xl border border-line bg-white p-6 shadow-soft"
                >
                  <h3 className="font-display text-[16px] font-bold leading-snug text-ink group-hover:text-brand">
                    {r.title}
                  </h3>
                  <p className="mt-2 line-clamp-2 text-[13.5px] leading-relaxed text-muted">
                    {r.excerpt}
                  </p>
                  <span className="mt-3 inline-flex items-center gap-1.5 text-[13px] font-semibold text-brand">
                    Read <ArrowRight size={14} aria-hidden="true" />
                  </span>
                </Link>
              ))}
            </div>
          </div>
        </section>
      )}

      <section className="py-14 max-md:py-10">
        <DemoSection />
      </section>
    </>
  );
}
