import Image from "next/image";
import { Suspense } from "react";
import BGLoop from "../components/stories/bgLoop";
import storiesData from "@/public/data/stories.json";
import StoriesClient from "./StoriesClient";
import BreadcrumbList from "../components/common/BreadcrumbList";
import { Metadata } from "next";

export const metadata: Metadata = {
  title:
    "Stories | Custom Clothing Journeys, Craftsmanship & Brand Collaborations | Morni",
  description:
    "Explore custom clothing journeys, artisan craftsmanship, brand collaborations, and co-creation stories. See how ideas become wearable pieces through natural fabrics and Indian craftsmanship.",
  alternates: {
    canonical: "https://mymorni.com/stories",
  },
};

type Story = {
  id: number;
  slug: string;
  title: string;
  subtitle: string;
  thumbnail: string | undefined;
  pieceThumbnail: string | undefined;
  designHouse: string;
};

type FabricFamily = {
  id: number;
  name: string;
};

type ApiResponse = {
  success: boolean;
  data: Story[];
};
type Tag = {
  id: number;
  name: string;
  slug?: string;
};

type TagsResponse = {
  success: boolean;
  data: Tag[];
};

type Props = {
  initialStories: Story[];
  tags: Tag[];
  fabricFamilies: FabricFamily[];
};

async function getStories(): Promise<Story[]> {
  // Skip API calls during build time to prevent timeouts
  if (
    !process.env.NEXT_PUBLIC_BASE_URL ||
    process.env.NODE_ENV === "production"
  ) {
    return storiesData as Story[];
  }

  try {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 10000);

    const response = await fetch(
      `${process.env.NEXT_PUBLIC_BASE_URL}/api/stories`,
      {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        next: { revalidate: 300 }, // Cache for 5 minutes
        signal: controller.signal,
      },
    );

    clearTimeout(timeoutId);

    if (!response.ok) {
      console.warn(
        `API returned status ${response.status}, using fallback data`,
      );
      return storiesData as Story[];
    }

    const result: ApiResponse = await response.json();
    if (!result.success || !result.data) {
      console.warn("Invalid API response format, using fallback data");
      return storiesData as Story[];
    }

    return result.data;
  } catch (error) {
    if (error instanceof Error && error.name === "AbortError") {
      console.warn("Stories API request timed out, using fallback data");
    } else {
      console.error("Error fetching stories, using fallback data:", error);
    }
    return storiesData as Story[];
  }
}

async function getTags(): Promise<Tag[]> {
  // Skip API calls during build time
  if (
    !process.env.NEXT_PUBLIC_BASE_URL ||
    process.env.NODE_ENV === "production"
  ) {
    return [];
  }

  try {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 10000);

    const response = await fetch(
      `${process.env.NEXT_PUBLIC_BASE_URL}/api/stories/tags`,
      {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        next: { revalidate: 300 },
        signal: controller.signal,
      },
    );

    clearTimeout(timeoutId);

    if (!response.ok) {
      return [];
    }

    const result: TagsResponse = await response.json();
    return result.success && result.data ? result.data : [];
  } catch (error) {
    if (error instanceof Error && error.name === "AbortError") {
      console.warn("Tags API request timed out");
    } else {
      console.error("Error fetching tags:", error);
    }
    return [];
  }
}

async function getFabricFamilies(): Promise<FabricFamily[]> {
  // Skip API calls during build time
  if (
    !process.env.NEXT_PUBLIC_BASE_URL ||
    process.env.NODE_ENV === "production"
  ) {
    return [];
  }

  try {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 10000);

    const response = await fetch(
      `${process.env.NEXT_PUBLIC_BASE_URL}/api/stories/fabric-families`,
      {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        next: { revalidate: 300 },
        signal: controller.signal,
      },
    );

    clearTimeout(timeoutId);

    if (!response.ok) {
      return [];
    }

    const result = await response.json();

    if (!result.success || !result.data) {
      return [];
    }

    const families = result.data.fabric ?? result.data;

    return Array.isArray(families) ? families : [];
  } catch (error) {
    if (error instanceof Error && error.name === "AbortError") {
      console.warn("Fabric families API request timed out");
    } else {
      console.error("Error fetching fabric families:", error);
    }
    return [];
  }
}

export default async function StoriesPage() {
  const [stories, fabricFamilies] = await Promise.all([
    getStories(),
    getFabricFamilies(),
  ]);

  const storiesArray = Array.isArray(stories) ? stories : [];
  //const tagsArray = Array.isArray(tags) ? tags : [];
  const fabricFamiliesArray = Array.isArray(fabricFamilies)
    ? fabricFamilies
    : [];

  return (
    <>
      <BreadcrumbList
        items={[
          {
            name: "Home",
            url: "https://mymorni.com",
          },
          {
            name: "Stories",
            url: "https://mymorni.com/stories",
          },
        ]}
      />
      <div className="fixed top-0 left-0 h-lvh w-lvw">
        <div className="fixed top-0 left-0 h-lvh w-lvw bg-gradient-to-br from-[#003d46] to-[#00343b]">
          <div className="from-azure-blue/80 absolute -top-[5%] right-[10%] h-1/2 w-1/2 rotate-45 bg-gradient-to-br to-teal-600 opacity-75 blur-[64px]" />
          <div className="absolute bottom-0 left-0 h-2/3 w-2/3 -rotate-60 bg-gradient-to-br from-blue-600/80 to-teal-600 opacity-50 blur-[64px]" />
        </div>
        <div className="mob-noise absolute top-0 left-0 h-full w-full scale-180 opacity-25" />
        <div className="absolute top-0 -left-[20vw] h-[88vh] w-[48vw]">
          <Image
            src="/images/chakra.webp"
            alt="Chakra left"
            width={1200}
            height={1200}
            className="img-responsive"
          />
        </div>
        <div className="absolute top-[6vh] -right-[20vw] h-[88vh] w-[48vw]">
          <Image
            src="/images/chakra.webp"
            alt="Chakra left"
            width={1200}
            height={1200}
            className="img-responsive"
          />
        </div>
        <div className="absolute top-[48vh] flex w-full items-center justify-center align-middle">
          <BGLoop />
        </div>
      </div>
      <div className="relative z-20 min-h-lvh">
        <main className="wrapper relative py-13">
          <Suspense fallback={null}>
            <StoriesClient
              initialStories={storiesArray}
              // tags={tagsArray}
              fabricFamilies={fabricFamiliesArray}
            />
          </Suspense>
        </main>
      </div>
    </>
  );
}
