import JournalList from "./JournalList";
import { Metadata } from "next";
import BreadcrumbList from "../components/common/BreadcrumbList";

export const revalidate = 3600; // ISR: Revalidate every hour
export const dynamic = "force-dynamic"; // Use dynamic rendering to avoid build timeouts

interface ItemProps {
  id: number;
  title: string;
  slug: string;
  excerpt: string;
  content: string;
  image: string;
}

export async function generateMetadata({
  searchParams,
}: {
  searchParams: Promise<Record<string, string>>;
}): Promise<Metadata> {
  const params = await searchParams;

  const category = params.category;

  return {
    alternates: {
      canonical: "https://mymorni.com/journal",
    },
    title: category
      ? "Journal | Sustainable Fashion, Natural Fabrics & Craftsmanship | Morni"
      : "Shop Sustainable Clothing Collections | Morni",

    description: category
      ? "Explore sustainable fashion insights, natural fabrics, artisan craftsmanship, clothing production, and conscious design stories from the Morni Journal."
      : "Browse sustainable clothing collections by category, fabric, design house and style.",
  };
}

async function getJournalList(): Promise<ItemProps[]> {
  try {
    const apiUrl = process.env.API_BASE_URL;

    if (!apiUrl) {
      console.error("API_BASE_URL is not defined");
      return [];
    }

    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), 8000); // 8 second timeout

    // Fetch directly from external API instead of internal API route
    const response = await fetch(`${apiUrl}/blog`, {
      method: "GET",
      headers: { "Content-Type": "application/json" },
      next: { revalidate: 3600 },
      signal: controller.signal,
      cache: "force-cache", // Cache the response
    });

    clearTimeout(timeout);

    if (!response.ok) {
      console.error(`API Error: ${response.status} - ${response.statusText}`);
      return [];
    }

    const data = await response.json();
    return Array.isArray(data?.data?.blog) ? data.data.blog : [];
  } catch (error) {
    console.error("Error fetching Journal list:", error);
    return [];
  }
}

export default async function JournalListPage() {
  const journals = await getJournalList();

  return (
    <>
      <BreadcrumbList
        items={[
          {
            name: "Home",
            url: "https://mymorni.com",
          },
          {
            name: "Journal",
            url: "https://mymorni.com/journal",
          },
        ]}
      />

      <div className="relative min-h-screen bg-gray-100">
        <div className="wrapper pt-20 pb-25">
          <h1 className="mb-6 text-4xl font-bold">Journal</h1>
          <JournalList initialItems={journals} />
        </div>
      </div>
    </>
  );
}
