import Link from "next/link";
import { headers } from "next/headers";
import { notFound } from "next/navigation";
import { connection } from "next/server";
import { Mic, Share2 } from "lucide-react";
import CVHeader from "@/components/layout/CVHeader";
import CVFooter from "@/components/layout/CVFooter";
import GrammarQuiz from "@/components/grammar/GrammarQuiz";
import {
  getGrammarCategories,
  getGrammarPost,
  getGrammarQuizQuestions,
  getReadingTime,
  stripHtml,
} from "@/lib/grammar";
import { getContentMetadataForRequest, getRequestMetadataInput } from "@/lib/siteSeo";

export async function generateMetadata({ params }) {
  const { category, slug } = await params;
  const post = await getGrammarPost(category, slug);
  if (!post) return {};

  const description = post.summary || stripHtml(post.content || '').slice(0, 160);

  return getContentMetadataForRequest({
    ...getRequestMetadataInput(await headers(), {
      pathname: `/grammar/${category}/${slug}`,
    }),
    title: `${post.title} | Cambridge Veritas Grammar`,
    description,
    keywords: post.keywords,
    image: post.image,
    imageAlt: post.title,
    type: 'article',
    publishedTime: post.created_at || undefined,
    section: post.category_title || 'English Grammar',
  });
}

export default async function GrammarPostPage({ params }) {
  await connection();

  const { category, slug } = await params;
  const post = await getGrammarPost(category, slug);

  if (!post) notFound();

  const [categories, questions] = await Promise.all([
    getGrammarCategories(),
    getGrammarQuizQuestions(post.quiz_id),
  ]);

  const categoryData = categories.find((item) => Number(item.id) === Number(post.category_id));
  const categoryTitle = categoryData?.title || post.category_title || "Grammar";
  const categoryEmoji = categoryData?.emoji || post.category_emoji || "📚";
  const postEmoji = post.emoji || categoryEmoji;
  const shareText = `Check out this grammar lesson: "${post.title}" — practice your English for free!`;

  return (
    <div className="min-h-screen bg-[#FAF5F0]">
      <CVHeader />

      <main className="bg-[#FAF5F0]">
        <article className="mx-auto max-w-5xl px-4 py-8 sm:px-6 sm:py-12">
          <div className="mb-6 flex items-center justify-between gap-4">
            <Link
              href="/grammar"
              className="flex items-center gap-2 text-sm font-semibold text-[#7A5C65] transition hover:text-[#4A1429]"
            >
              ← All Grammar Lessons
            </Link>
            <a
              href={`https://wa.me/?text=${encodeURIComponent(shareText)}`}
              target="_blank"
              rel="noopener noreferrer"
              className="flex items-center gap-2 rounded-xl border border-[#25D366]/20 bg-[#25D366]/10 px-3 py-2 text-xs font-bold text-[#128C7E] transition hover:shadow-sm"
            >
              <Share2 className="h-3.5 w-3.5" aria-hidden="true" />
              Share with a friend
            </a>
          </div>

          <header className="relative mb-6 overflow-hidden rounded-2xl border border-[#D4B038]/25 bg-gradient-to-br from-[#4A1429] to-[#6B1E3D] p-5 sm:rounded-3xl sm:p-7">
            <div className="pointer-events-none absolute right-0 top-0 h-32 w-32 translate-x-[20%] -translate-y-[20%] rounded-full bg-[radial-gradient(circle,rgba(212,176,56,.125),transparent_70%)] sm:h-40 sm:w-40" />
            <div className="mb-3 text-3xl sm:text-4xl">{postEmoji}</div>
            <h1 className="mb-2 text-xl font-black leading-snug text-white sm:text-2xl">
              {post.title}
            </h1>
            {post.summary ? (
              <p className="text-sm leading-relaxed text-white/70">{post.summary}</p>
            ) : null}
            <div className="mt-4 flex flex-wrap items-center gap-2">
              <span className="rounded-full border border-emerald-600/20 bg-emerald-50 px-3 py-1.5 text-xs font-black uppercase tracking-widest text-emerald-600">
                {categoryEmoji} {categoryTitle}
              </span>
              <span className="rounded-full border border-[#D4B038]/25 bg-[#FFFBEB] px-3 py-1.5 text-xs font-black uppercase tracking-widest text-[#92400E]">
                ⏱️ {getReadingTime(post)}
              </span>
            </div>
          </header>

          <div
            className="grammar-content max-w-none"
            dangerouslySetInnerHTML={{ __html: post.content || "" }}
          />

          <GrammarQuiz questions={questions} />

          <section className="mt-10 overflow-hidden rounded-3xl border border-[#D4B038]/25 bg-white shadow-lg">
            <div className="bg-gradient-to-br from-[#4A1429] to-[#6B1E3D] px-6 py-7 text-center">
              <div className="mb-3 text-4xl">🎤</div>
              <h2 className="mb-2 text-xl font-black text-white">
                Now Put It Into Practice — Out Loud
              </h2>
              <p className="mx-auto mb-5 max-w-md text-sm leading-relaxed text-white/70">
                Reading grammar is step one. Saying it fluently is step two. Cambridge Veritas AI analyses your speaking in real time — pronunciation, fluency, grammar, and vocabulary.
              </p>
              <div className="flex flex-col items-center justify-center gap-3 sm:flex-row">
                <Link
                  href="/tools/speech-analyser"
                  className="flex items-center gap-2.5 rounded-2xl bg-gradient-to-br from-[#D4B038] to-[#F5D060] px-6 py-3.5 text-sm font-black text-[#4A1429] shadow-lg transition hover:scale-[1.02] hover:opacity-90"
                >
                  <Mic className="h-4 w-4" aria-hidden="true" />
                  Start Speaking Practice
                </Link>
                <a
                  href="https://wa.me/918068212576?text=Hello"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center gap-2.5 rounded-2xl border border-white/20 px-6 py-3.5 text-sm font-bold text-white transition hover:bg-white/10"
                >
                  <span className="text-base">💬</span>
                  Ask a Question on WhatsApp
                </a>
              </div>
              <p className="mt-4 text-xs text-white/30">
                4,500+ students assessed · 87 countries · Start free
              </p>
            </div>
            <div className="flex items-center justify-between gap-4 border-t border-[#FDE68A] bg-[#FFFBEB] px-6 py-4">
              <p className="text-xs font-semibold text-[#92400E]">📚 Know someone learning English? Share this lesson with them!</p>
              <a
                href={`https://wa.me/?text=${encodeURIComponent(shareText)}`}
                target="_blank"
                rel="noopener noreferrer"
                className="shrink-0 rounded-xl bg-[#25D366] px-3 py-2 text-xs font-black text-white transition hover:opacity-80"
              >
                WhatsApp
              </a>
            </div>
          </section>
        </article>
      </main>

      <CVFooter />
    </div>
  );
}
