import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { getCurrentUser } from "@/lib/auth/dal";
import {
  getQuoteBySlug,
  listRelatedQuotes,
  incrementQuoteViewCount,
  listMostLikedQuotes,
  listMostViewedQuotes,
  listMostCommentedQuotes,
} from "@/lib/quotes/queries";
import { listCommentsForQuote } from "@/lib/quotes/comment-queries";
import { resolvePageMetadata } from "@/lib/seo/metadata";
import { truncateAtWordBoundary } from "@/lib/shared/text";
import { Breadcrumbs } from "@/components/seo/Breadcrumbs";
import { JsonLd } from "@/components/seo/JsonLd";
import { QuoteCard } from "@/components/quotes/QuoteCard";
import { QuoteCommentSection } from "@/components/quotes/QuoteCommentSection";
import { QuoteSidebar } from "@/components/quotes/QuoteSidebar";
import { FadeInSection } from "@/components/ui/FadeInSection";

type Props = {
  params: Promise<{ slug: string }>;
};

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const quote = await getQuoteBySlug(slug);
  if (!quote) return { title: "Söz Bulunamadı" };

  // <title> etiketi ~60 karakter civarında iyi görünür — uzun sözlerin tamamını koymak Google'da
  // kesilmesine yol açıyordu. Açıklamada ise daha uzun bir kesit tutuyoruz (arama sonucu
  // snippet'inde asıl arananın söz metni olması, tıklama oranı için önemli).
  const titleQuote = truncateAtWordBoundary(quote.text, 50);
  const title = quote.author ? `"${titleQuote}" — ${quote.author}` : `"${titleQuote}"`;

  const descQuote = truncateAtWordBoundary(quote.text, 110);
  const description = quote.author
    ? `"${descQuote}" — ${quote.author}. ${quote.category.name} kategorisinden bu güzel sözü oku, kopyala ya da sevdiğin birine gönder.`
    : `"${descQuote}" — ${quote.category.name} kategorisinden bu güzel sözü oku, kopyala ya da sevdiğin birine gönder.`;

  return resolvePageMetadata(`/sozler/soz/${slug}`, { title, description });
}

export default async function QuoteDetailPage({ params }: Props) {
  const { slug } = await params;
  const viewer = await getCurrentUser();
  const quote = await getQuoteBySlug(slug, viewer?.id);

  if (!quote) notFound();

  await incrementQuoteViewCount(quote.id);

  const [relatedQuotes, comments, mostLiked, mostViewed, mostCommented] = await Promise.all([
    listRelatedQuotes(quote.categoryId, quote.id, 6, viewer?.id),
    listCommentsForQuote(quote.id),
    listMostLikedQuotes(5, quote.id),
    listMostViewedQuotes(5, quote.id),
    listMostCommentedQuotes(5, quote.id),
  ]);

  return (
    <div className="relative overflow-hidden">
      <div className="pointer-events-none absolute -left-40 -top-20 h-[420px] w-[420px] rounded-full bg-[radial-gradient(circle,oklch(85%_0.07_335_/_.4),transparent_70%)]" />

      <div className="relative mx-auto max-w-5xl px-6 py-14">
        <JsonLd
          data={{
            "@context": "https://schema.org",
            "@type": "CreativeWork",
            text: quote.text,
            author: quote.author ? { "@type": "Person", name: quote.author } : undefined,
            about: quote.category.name,
          }}
        />

        <Breadcrumbs
          items={[
            { name: "Ana Sayfa", path: "/" },
            { name: "Güzel Sözler", path: "/sozler" },
            { name: quote.category.name, path: `/sozler/${quote.category.slug}` },
            {
              name: quote.author
                ? `${truncateAtWordBoundary(quote.text, 40)} — ${quote.author}`
                : truncateAtWordBoundary(quote.text, 60),
              path: `/sozler/soz/${quote.slug}`,
            },
          ]}
        />

        <div className="grid grid-cols-1 gap-8 lg:grid-cols-[minmax(0,1fr)_260px]">
          <div>
            <QuoteCard quote={quote} canSend={Boolean(viewer)} canLike={Boolean(viewer)} />

            <QuoteCommentSection
              quoteId={quote.id}
              comments={comments}
              viewerId={viewer?.id ?? null}
              isAdmin={viewer?.role === "ADMIN"}
            />

            {relatedQuotes.length > 0 && (
              <div className="mt-12 border-t border-border pt-8">
                <h2 className="mb-4 text-[16px] font-bold">
                  {quote.category.name} Kategorisinden Diğer Sözler
                </h2>
                <FadeInSection className="grid grid-cols-1 items-start gap-5 sm:grid-cols-2">
                  {relatedQuotes.map((related) => (
                    <QuoteCard key={related.id} quote={related} canSend={Boolean(viewer)} canLike={Boolean(viewer)} />
                  ))}
                </FadeInSection>
                <div className="mt-6 text-center">
                  <Link
                    href={`/sozler/${quote.category.slug}`}
                    className="text-[13px] font-semibold text-accent hover:underline"
                  >
                    {quote.category.name} kategorisindeki tüm sözleri gör →
                  </Link>
                </div>
              </div>
            )}
          </div>

          <aside className="lg:sticky lg:top-24 lg:self-start">
            <QuoteSidebar mostLiked={mostLiked} mostViewed={mostViewed} mostCommented={mostCommented} />
          </aside>
        </div>
      </div>
    </div>
  );
}
