import Image from "next/image";
import Link from "next/link";
import { notFound } from "next/navigation";
import ReactMarkdown from "react-markdown";
import { ArrowLeft, Clock, Crown, Send } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { GuideCard } from "@/components/guides/GuideCard";
import { AdSlot } from "@/components/shared/AdSlot";
import { CommunityBanner } from "@/components/shared/CommunityBanner";
import { Paywall } from "@/components/membership/Paywall";
import {
  getCurrentUser,
  userHasActiveMembership,
} from "@/lib/user-auth";
import {
  getAllArticleSlugs,
  getArticleBySlug,
  getRelatedArticles,
} from "@/lib/queries/articles";
import { siteConfig } from "@/lib/site-config";
import { toArticleCardData } from "@/lib/types";

interface GuidePageProps {
  params: Promise<{ slug: string }>;
}

export async function generateStaticParams() {
  const articles = await getAllArticleSlugs();
  return articles.map((a) => ({ slug: a.slug }));
}

export async function generateMetadata({ params }: GuidePageProps) {
  const { slug } = await params;
  const article = await getArticleBySlug(slug);
  if (!article) return { title: "指南未找到" };
  return {
    title: article.title,
    description: article.excerpt,
  };
}

export default async function GuideArticlePage({ params }: GuidePageProps) {
  const { slug } = await params;
  const article = await getArticleBySlug(slug);
  if (!article) notFound();

  const user = await getCurrentUser();
  const isMember = user ? await userHasActiveMembership(user.id) : false;
  const isPremium = article.accessLevel === "member";
  const canViewFull = !isPremium || isMember;

  const related = await getRelatedArticles(
    article.category,
    article.slug
  );

  return (
    <article className="py-8 sm:py-12">
      <div className="mx-auto max-w-4xl px-4 sm:px-6 lg:px-8">
        <Link
          href="/guides"
          className="mb-6 inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-primary"
        >
          <ArrowLeft className="size-4" />
          返回指南列表
        </Link>

        <div className="relative mb-8 aspect-[21/9] overflow-hidden rounded-2xl">
          <Image
            src={article.coverImage}
            alt={article.title}
            fill
            className="object-cover"
            sizes="(max-width: 896px) 100vw, 896px"
            priority
          />
        </div>

        <div className="flex flex-wrap items-center gap-3">
          <Badge className="bg-primary text-primary-foreground">
            {article.category}
          </Badge>
          {isPremium && (
            <Badge variant="outline" className="border-primary text-primary">
              <Crown className="mr-1 size-3" />
              會員專屬
            </Badge>
          )}
          <span className="flex items-center gap-1 text-sm text-muted-foreground">
            <Clock className="size-4" />
            {article.readTime} 分鐘閱讀
          </span>
          <span className="text-sm text-muted-foreground">
            {new Date(article.publishedAt).toLocaleDateString("zh-TW", {
              year: "numeric",
              month: "long",
              day: "numeric",
            })}
          </span>
        </div>

        <h1 className="mt-4 text-3xl font-bold leading-tight sm:text-4xl">
          {article.title}
        </h1>
        <p className="mt-4 text-lg text-muted-foreground">{article.excerpt}</p>

        {canViewFull ? (
          <div className="prose prose-invert prose-headings:text-primary prose-a:text-primary mt-10 max-w-none">
            <ReactMarkdown>{article.content}</ReactMarkdown>
          </div>
        ) : (
          <div className="mt-10">
            <Paywall
              title="此指南為會員專屬內容"
              description="訂閱會員即可閱讀完整老司機攻略，包含進階技巧與私房建議。"
            />
          </div>
        )}

        <div className="mt-10">
          <AdSlot slot="article_bottom" />
        </div>

        <div className="mt-12 flex justify-center">
          <Button
            render={
              <a
                href={siteConfig.telegramUrl}
                target="_blank"
                rel="noopener noreferrer"
              />
            }
            nativeButton={false}
            className="bg-primary text-primary-foreground"
          >
            <Send className="size-4" />
            在 Telegram 討論這篇指南
          </Button>
        </div>
      </div>

      {related.length > 0 && (
        <section className="mx-auto mt-16 max-w-7xl px-4 sm:px-6 lg:px-8">
          <h2 className="text-2xl font-bold">更多指南</h2>
          <div className="mt-6 grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
            {related.map((a, i) => (
              <GuideCard
                key={a.slug}
                article={toArticleCardData(a)}
                index={i}
              />
            ))}
          </div>
        </section>
      )}

      <section className="mx-auto mt-16 max-w-7xl px-4 sm:px-6 lg:px-8">
        <CommunityBanner />
      </section>
    </article>
  );
}