import type { Metadata } from "next";
import Link from "next/link";
import Image from "next/image";
import { ContentCard } from "@/components/site/ContentCard";
import { ContactSection } from "@/components/site/ContactSection";
import { CreatorIntro } from "@/components/site/CreatorIntro";
import { VideoCard } from "@/components/site/VideoCard";
import { getAboutImages } from "@/lib/about-images";
import { prisma } from "@/lib/prisma";
import { siteUrl } from "@/lib/utils";

type HomePageProps = {
  searchParams: Promise<{ contact?: string }>;
};

function seoKeywords(value?: string | null) {
  return value?.split(",").map((keyword) => keyword.trim()).filter(Boolean);
}

export async function generateMetadata(): Promise<Metadata> {
  const page = await prisma.pageContent.findUnique({ where: { key: "HOME" } }).catch(() => null);

  return {
    title: page?.seoTitle ?? page?.title ?? "Just Chill Nepal",
    description: page?.seoDescription ?? page?.subtitle ?? "Explore Nepal through blogs, videos, gallery moments, culture, food, travel, and local stories.",
    keywords: seoKeywords(page?.seoKeywords),
    alternates: { canonical: siteUrl("/") },
    openGraph: {
      title: page?.seoTitle ?? page?.title ?? "Just Chill Nepal",
      description: page?.seoDescription ?? page?.subtitle ?? "Explore Nepal through blogs, videos, gallery moments, culture, food, travel, and local stories.",
      images: page?.heroImage ? [{ url: page.heroImage, alt: page.title }] : undefined,
      url: siteUrl("/"),
      type: "website"
    },
    twitter: {
      card: page?.heroImage ? "summary_large_image" : "summary",
      title: page?.seoTitle ?? page?.title ?? "Just Chill Nepal",
      description: page?.seoDescription ?? page?.subtitle ?? "Explore Nepal through blogs, videos, gallery moments, culture, food, travel, and local stories.",
      images: page?.heroImage ? [page.heroImage] : undefined
    }
  };
}

export default async function HomePage({ searchParams }: HomePageProps) {
  const params = await searchParams;
  const [featuredVideos, galleryImages, latestPosts, about, reviews, contact, categories, aboutImages] = await Promise.all([
    prisma.video.findMany({
      where: { approvalStatus: "APPROVED", status: "PUBLISHED", kind: "VIDEO" },
      include: { category: true },
      orderBy: [{ featured: "desc" }, { publishedAt: "desc" }],
      take: 8
    }),
    prisma.galleryImage.findMany({
      where: { active: true, approvalStatus: "APPROVED" },
      orderBy: [{ sortOrder: "asc" }, { createdAt: "desc" }],
      take: 8
    }),
    prisma.post.findMany({
      where: { approvalStatus: "APPROVED", status: "PUBLISHED" },
      include: { category: true },
      orderBy: [{ featured: "desc" }, { publishedAt: "desc" }],
      take: 8
    }),
    prisma.pageContent.findUnique({ where: { key: "ABOUT" } }),
    prisma.review.findMany({ where: { active: true, approvalStatus: "APPROVED" }, orderBy: { createdAt: "desc" }, take: 8 }),
    prisma.contactSetting.findUnique({ where: { key: "contact" } }),
    prisma.category.findMany({
      include: {
        _count: {
          select: { posts: true, videos: true }
        }
      },
      orderBy: { name: "asc" }
    }),
    getAboutImages()
  ]);

  return (
    <main>
      <section className="container" id="hero">
        <div className="transparent-hero">
          <span className="pill">Just Chill Nepal</span>
          <h1 className="hero-title">Explore Nepal Through Blogs, Videos & Real Moments</h1>
          <p className="hero-copy">
            A Nepal-wide media platform for culture, people, food, travel, technology,
            lifestyle, and creative blogs from every corner of the country.
          </p>
          <div className="hero-actions">
            <Link className="btn" href="/videos">Watch Videos</Link>
            <Link className="btn btn-secondary" href="/gallery">Explore Gallery</Link>
          </div>
          {categories.length > 0 ? (
            <div className="hero-category-grid" aria-label="Explore by category">
              {categories.map((category) => (
                <Link className="hero-category-card" href={`/categories/${category.slug}`} key={category.id}>
                  <strong>{category.name}</strong>
                  <span>{category._count.videos} videos · {category._count.posts} blogs</span>
                </Link>
              ))}
            </div>
          ) : null}
        </div>
      </section>

      <section className="container" id="about">
        <CreatorIntro about={about} brandImage={aboutImages.brandImage} />
      </section>

      <section className="container" id="videos">
        <div className="section-head">
          <div>
            <span className="pill">Featured Videos</span>
            <h2 className="section-title">Nepal Videos</h2>
          </div>
          <Link className="btn btn-secondary" href="/videos">View all</Link>
        </div>
        <div className="youtube-grid">
          {featuredVideos.map((video) => (
            <VideoCard
              category={video.category?.name}
              date={video.publishedAt}
              description={video.description}
              href={`/videos/${video.slug}`}
              key={video.id}
              thumbnail={video.thumbnail}
              title={video.title}
              youtubeId={video.youtubeId}
            />
          ))}
        </div>
      </section>

      <section className="container" id="gallery">
        <div className="section-head">
          <div>
            <span className="pill">Gallery</span>
            <h2 className="section-title">Visual Moments</h2>
          </div>
        </div>
        <div className="gallery-grid">
          {galleryImages.map((image) => (
            <div className="gallery-item" key={image.id}>
              <Image alt={image.title} fill sizes="(max-width: 700px) 100vw, 33vw" src={image.imageUrl} unoptimized />
              <div className="gallery-caption">
                <span>{image.title}</span>
                <p>{image.description}</p>
              </div>
            </div>
          ))}
          {galleryImages.length === 0 ? <p className="muted">Admin panel bata gallery images add gara.</p> : null}
        </div>
        {galleryImages.length > 0 ? (
          <div className="section-action">
            <Link className="btn btn-secondary" href="/gallery">View Full Gallery</Link>
          </div>
        ) : null}
      </section>

      <section className="container" id="blogs">
        <div className="section-head">
          <div>
            <span className="pill">Blogs</span>
            <h2 className="section-title">Latest Blogs</h2>
          </div>
          <Link className="btn btn-secondary" href="/articles">View all</Link>
        </div>
        <div className="blog-grid">
          {latestPosts.map((post) => (
            <ContentCard
              category={post.category?.name}
              date={post.publishedAt}
              excerpt={post.excerpt}
              href={`/articles/${post.slug}`}
              image={post.coverImage}
              key={post.id}
              title={post.title}
            />
          ))}
        </div>
      </section>

      <section className="container" id="reviews">
        <div className="section-head">
          <div>
            <span className="pill">Viewer Reviews</span>
            <h2 className="section-title">People Feedback</h2>
          </div>
        </div>
        <div className="review-grid">
          {reviews.map((review) => (
            <div className="glass-panel content-card review-card" key={review.id}>
              <span className="pill">{"★".repeat(review.rating)}</span>
              <h3>{review.name}</h3>
              <p className="muted">{review.location}</p>
              <p style={{ lineHeight: 1.7 }}>{review.message}</p>
            </div>
          ))}
        </div>
      </section>

      <section className="container" id="contact">
        <ContactSection contact={contact} showSuccess={params.contact === "sent"} />
      </section>
    </main>
  );
}
