import type { Metadata } from "next";
import heroImg from "@/app/blog/_assets/blog-hero.png";
import { Container } from "@/app/components/layout/Container";
import { ChevronsLeftIcon, ChevronsRightIcon } from "lucide-react";
import fetchGraphQL from "@/app/graphql/graphql";
import Image from "next/image";
import Link from "next/link";
import { redirect } from "next/navigation";
import Heading from "@/app/components/ui/Heading";

import type { PostsData } from "@/app/types";

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>;
}): Promise<Metadata> {
  const { slug } = await params;
  const categoryName = slug
    .split("-")
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join(" ");

  const categoryDescQuery = `query GetCategory($id: ID!) {
    category(id: $id, idType: SLUG) {
      description
    }
  }`

  const categoryDescData: { category: { description?: string } | null } = await fetchGraphQL(categoryDescQuery, {
    id: slug,
  });

  const description = categoryDescData?.category?.description || "";

  return {
    title: `${categoryName} Archives - Basmati Pakistan`,
    description,
    alternates: {
      canonical: `https://basmatipakistan.com/category/${slug}/`,
    },
    openGraph: {
      title: `${categoryName} Archives - Basmati Pakistan`,
      description,
      url: `https://basmatipakistan.com/category/${slug}/`,
      type: "website",
    },
    twitter: {
      card: "summary_large_image",
      title: `${categoryName} Archives - Basmati Pakistan`,
      description,
    },
  };
}

export default async function CategoryPage({
  searchParams,
  params,
}: {
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
  params: Promise<{ slug: string }>;
}) {
  const { page } = await searchParams;
  const { slug } = await params;
  const currentPage = Number(page) || 1;

  if (currentPage < 1 || currentPage > 5) {
    redirect(`/category/${slug}`);
  }

  const categoryName = slug
    .split("-")
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join(" ");

  const categoryDescQuery = `query GetCategory($id: ID!) {
    category(id: $id, idType: SLUG) {
      description
    }
  }`

  const categoryDescData: { category: { description?: string } | null } = await fetchGraphQL(categoryDescQuery, {
    id: slug,
  });

  const query = `query GetPosts($offset: Int!, $size: Int!, $categoryName: String) {
        posts ( where: {categoryName: $categoryName, offsetPagination: {offset: $offset, size: $size}}) {
            nodes {
                title
                slug
                featuredImage {
                    node {
                        altText
                        sourceUrl
                    }
                }
            }
            pageInfo {
                offsetPagination {
                    hasPrevious
                    hasMore
                    total
                }
            }
        }
    }`;

  const res: PostsData = await fetchGraphQL(query, {
    offset: (currentPage - 1) * 4,
    size: 4,
    categoryName: categoryName,
  });
  const posts = res.posts.nodes;

  const rawTotalPages = Math.ceil(
    res.posts.pageInfo.offsetPagination.total / 4,
  );
  const totalPages = Math.min(rawTotalPages, 5);

  return (
    <>
      <section className="relative h-[65vh] w-full">
        <Image
          src={heroImg}
          alt={`${categoryName} Hero`}
          fill
          placeholder="blur"
          className="absolute top-0 left-0 w-full h-full object-cover object-center"
          priority
          fetchPriority="high"
          loading="eager"
        />
        <div className="relative bg-black/60 w-full h-full flex items-center">
          <Container>
              <Heading
                as="h1"
                variant="title"
                className="text-white"
              >
                {categoryName}
              </Heading>
              <p className="text-white">{categoryDescData?.category?.description}</p>
          </Container>
        </div>
        <div className="absolute z-10 bottom-0 w-full bg-white h-24 [clip-path:polygon(100%_100%,100%_0,0_100%)]"></div>
      </section>

      <section className="my-12">
        <Container>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-10 max-w-4xl mx-auto">
            {posts.map((post, index) => (
              <div
                key={index}
                className="shadow-xs hover:shadow-lg transition-all duration-300 rounded-2xl overflow-hidden border border-gray-200 bg-white flex flex-col gap-2"
              >
                <Link href={`/${post.slug}`} className="block w-full overflow-hidden">
                  <div className="relative w-full aspect-16/9 sm:aspect-21/9 md:h-64">
                    <Image
                      src={post.featuredImage?.node?.sourceUrl || heroImg}
                      alt={post.featuredImage?.node?.altText || post.title}
                      width={1200}
                      height={675}
                      className="w-full h-auto hover:scale-105 transition-transform duration-500"
                    />
                  </div>
                </Link>
                <div className="p-6 md:p-4 text-primary flex flex-col justify-between gap-6">
                  <Link href={`/${post.slug}`}>
                    <Heading as="h3" variant="card" className="hover:text-accent">
                      {post.title}
                    </Heading>
                  </Link>
                  <Link
                    className="flex gap-1.5 items-center text-sm font-semibold tracking-wide bg-primary text-white p-2 px-4 rounded-full transition-colors w-fit"
                    href={`/${post.slug}`}
                  >
                    <span>Read More</span>
                  </Link>
                </div>
              </div>
            ))}
          </div>
        </Container>
      </section>

      <section className="mt-12">
        <Container>
          <div className="flex justify-center gap-3 text-xl text-primary font-medium">
            <Link
              aria-disabled={currentPage <= 1}
              href={
                currentPage <= 1 ? `#` : `/category/${slug}?page=${currentPage - 1}`
              }
              className="flex gap-1 items-center text-primary aria-disabled:opacity-60 aria-disabled:cursor-not-allowed"
            >
              <ChevronsLeftIcon size={18} />
              <p>Previous</p>
            </Link>
            {Array.from({ length: totalPages }).map((_, index) => (
              <Link
                key={index}
                href={`/category/${slug}?page=${index + 1}`}
                aria-disabled={index + 1 === currentPage}
                className="text-primary text-xl aria-disabled:opacity-60"
              >
                <p>{index + 1}</p>
              </Link>
            ))}
            <Link
              aria-disabled={currentPage >= totalPages}
              href={
                currentPage >= totalPages
                  ? `#`
                  : `/category/${slug}?page=${currentPage + 1}`
              }
              className="flex gap-1 items-center text-primary aria-disabled:opacity-60 aria-disabled:cursor-not-allowed"
            >
              <p>Next</p>
              <ChevronsRightIcon size={18} />
            </Link>
          </div>
        </Container>
      </section>
    </>
  );
}
