import HeroSlider from "./components/HeroSlider";
import Link from "next/link";
import ProductCard from "./components/ProductCard";
import WhyChooseUsGrid from "./components/WhyChooseUsGrid";
import { generateSlug } from "@/utils/slugHelper";
import { Suspense } from "react";
import { resolveImage } from "@/utils/imageHelper";
import { API_BASE_URL } from "@/utils/apiHelper";

type Category = {
  name: string;
  is_active: boolean;
  category_id: string;
  created_by: string;
  created_at: string;
};

type Subcategory = {
  name: string;
  category_id: string;
  is_active: boolean;
  subcategory_id: string;
  card_image?: string | null;
};

type Product = {
  inward_id: string;
  submodel_id?: string;
  variant_id: string;
  sku_no: string;
  name: string;
  image: string | null;
  dealer_price: number;
  mrp: number;
  color?: string | null;
  size_name?: string | null;
  is_individual: boolean;
  is_carton: boolean;
  is_featured: boolean;
  is_new_arrival: boolean;
  is_best_seller: boolean;
  is_active: boolean;
  category_id: string | null;
  category_name: string | null;
  subcategory_id: string | null;
  subcategory_name: string | null;
};

// API Fetching Functions


async function getCategories() {
  try {
    const res = await fetch(
      `${API_BASE_URL}/api/v1/b2b-admin/inwards/categories/`,
      { next: { revalidate: 0 } }
    );
    if (!res.ok) return [];
    const data = await res.json();
    return (Array.isArray(data) ? data : (data.categories || [])) as Category[];
  } catch (error) {
    console.error("Error fetching categories:", error);
    return [];
  }
}

async function getSubcategories() {
  try {
    const res = await fetch(
      `${API_BASE_URL}/api/v1/b2b-admin/inwards/subcategories/`,
      { next: { revalidate: 0 } }
    );
    if (!res.ok) return [];
    const data = await res.json();
    return (Array.isArray(data) ? data : (data.subcategories || [])) as Subcategory[];
  } catch (error) {
    console.error("Error fetching subcategories:", error);
    return [];
  }
}

async function getNewArrivals() {
  try {
    const res = await fetch(
      `${API_BASE_URL}/api/v1/b2b-admin/inwards/cards?is_new_arrival=true&is_active=true`,
      { next: { revalidate: 0 } }
    );
    if (!res.ok) return [];
    return (await res.json()) as Product[];
  } catch (error) {
    console.error("Error fetching new arrivals:", error);
    return [];
  }
}

async function getBestSellers() {
  try {
    const res = await fetch(
      `${API_BASE_URL}/api/v1/b2b-admin/inwards/cards?is_best_seller=true&is_active=true`,
      { next: { revalidate: 0 } }
    );
    if (!res.ok) return [];
    return (await res.json()) as Product[];
  } catch (error) {
    console.error("Error fetching best sellers:", error);
    return [];
  }
}

async function getAllProducts() {
  try {
    const res = await fetch(
      `${API_BASE_URL}/api/v1/b2b-admin/inwards/cards?is_active=true`,
      { next: { revalidate: 0 } }
    );
    if (!res.ok) return [];
    return (await res.json()) as Product[];
  } catch (error) {
    console.error("Error fetching all products:", error);
    return [];
  }
}

function getUniqueProducts(products: Product[]): Product[] {
  const seen = new Set<string>();
  return products.filter((p) => {
    const id = p.submodel_id || p.name;
    if (seen.has(id)) return false;
    seen.add(id);
    return true;
  });
}

// Skeletons
function ExploreSkeleton() {
  return (
    <div className="grid grid-cols-1 md:grid-cols-2 gap-6 animate-pulse">
      {[1, 2, 3, 4].map((i) => (
        <div key={i} className="bg-gray-100 rounded-[2rem] aspect-[4/3] w-full" />
      ))}
    </div>
  );
}

function ProductGridSkeleton() {
  return (
    <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6 animate-pulse">
      {[1, 2, 3, 4].map((i) => (
        <div key={i} className="flex flex-col bg-white border border-gray-150 rounded-2xl overflow-hidden aspect-[4/5] p-4 gap-4">
          <div className="bg-gray-100 w-full aspect-square rounded-xl" />
          <div className="bg-gray-100 h-5 w-3/4 rounded" />
          <div className="bg-gray-100 h-4 w-1/2 rounded" />
        </div>
      ))}
    </div>
  );
}

// Section Components
async function CategoryExploreSection() {
  const [categories, subcategories] = await Promise.all([
    getCategories(),
    getSubcategories()
  ]);

  if (subcategories.length === 0) {
    return <p className="text-center text-foreground/60">No subcategories available.</p>;
  }

  // The fallback is now handled by resolveImage

  return (
    <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
      {subcategories.slice(0, 4).map((subcat, index) => {
        const parentCat = categories.find(c => c.category_id === subcat.category_id);
        const parentSlug = parentCat ? generateSlug(parentCat.name) : 'category';

        return (
          <Link
            href={`/category/${parentSlug}/${generateSlug(subcat.name)}`}
            key={subcat.subcategory_id}
            className="group relative overflow-hidden rounded-[2rem] bg-gray-100 shadow-sm hover:shadow-[0_20px_40px_rgb(0,0,0,0.12)] transition-all duration-500 transform hover:-translate-y-2 aspect-[4/3] w-full block"
          >
            <div
              className="absolute inset-0 bg-cover bg-center transition-transform duration-700 group-hover:scale-105"
              style={{ backgroundImage: `url('${resolveImage(subcat.card_image)}')` }}
            />
            <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/20 to-transparent"></div>
            <div className="absolute bottom-0 left-0 p-8 w-full">
              <h3 className="text-3xl font-black text-white mb-2 translate-y-2 group-hover:translate-y-0 transition-transform duration-500">{subcat.name}</h3>
              <span className="inline-flex items-center gap-2 text-white/80 font-bold opacity-0 group-hover:opacity-100 transition-opacity duration-500 delay-100">
                Explore Collection <span className="text-xl">→</span>
              </span>
            </div>
          </Link>
        );
      })}
    </div>
  );
}

async function NewArrivalsSection() {
  const [categories, rawNewArrivals] = await Promise.all([
    getCategories(),
    getNewArrivals()
  ]);
  const newArrivals = getUniqueProducts(rawNewArrivals);

  const helmetCategory = categories.find(c => c.name.toLowerCase().includes("helmet"));
  const viewAllLink = helmetCategory 
    ? `/category/${generateSlug(helmetCategory.name)}`
    : categories.length > 0 
      ? `/category/${generateSlug(categories[0].name)}`
      : "#";

  return (
    <div className="mt-32">
      <div className="flex flex-col md:flex-row md:items-end justify-between mb-12 gap-4">
        <div>
          <h2 className="text-4xl md:text-5xl font-black text-gray-900 tracking-tight mb-3">
            New Arrivals
          </h2>
          <p className="text-gray-500 font-medium text-lg">The latest additions to our premium collection.</p>
        </div>
        <Link href={viewAllLink} className="text-foreground font-bold hover:text-foreground/80 transition-colors flex items-center gap-2">
          View All <span className="text-xl">→</span>
        </Link>
      </div>

      {newArrivals && newArrivals.length > 0 ? (
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
          {newArrivals.slice(0, 8).map((product) => (
            <ProductCard key={product.submodel_id || product.inward_id || product.variant_id} product={product} />
          ))}
        </div>
      ) : (
        <p className="text-center text-foreground/60">
          No new arrivals available at the moment. Check back soon!
        </p>
      )}
    </div>
  );
}

async function BestSellersSection() {
  const [categories, rawBestSellers] = await Promise.all([
    getCategories(),
    getBestSellers()
  ]);
  const bestSellers = getUniqueProducts(rawBestSellers);

  const helmetCategory = categories.find(c => c.name.toLowerCase().includes("helmet"));
  const viewAllLink = helmetCategory 
    ? `/category/${generateSlug(helmetCategory.name)}`
    : categories.length > 0 
      ? `/category/${generateSlug(categories[0].name)}`
      : "#";

  return (
    <div className="mt-32">
      <div className="flex flex-col md:flex-row md:items-end justify-between mb-12 gap-4">
        <div>
          <h2 className="text-4xl md:text-5xl font-black text-gray-900 tracking-tight mb-3">
            Best Sellers
          </h2>
          <p className="text-gray-500 font-medium text-lg">Our most popular products chosen by top dealers.</p>
        </div>
        <Link href={viewAllLink} className="text-foreground font-bold hover:text-foreground/80 transition-colors flex items-center gap-2">
          View All <span className="text-xl">→</span>
        </Link>
      </div>

      {bestSellers && bestSellers.length > 0 ? (
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
          {bestSellers.slice(0, 8).map((product) => (
            <ProductCard key={product.submodel_id || product.inward_id || product.variant_id} product={product} />
          ))}
        </div>
      ) : (
        <p className="text-center text-foreground/60">
          No best sellers available at the moment. Check back soon!
        </p>
      )}
    </div>
  );
}

async function SubcategoryCollectionsSection() {
  const [categories, subcategories, rawAllProducts] = await Promise.all([
    getCategories(),
    getSubcategories(),
    getAllProducts()
  ]);
  const allProducts = getUniqueProducts(rawAllProducts);

  return (
    <>
      {subcategories.map((subcat) => {
        const subcatProducts = allProducts.filter(p => p.subcategory_id === subcat.subcategory_id);
        if (subcatProducts.length === 0) return null;

        const parentCat = categories.find(c => c.category_id === subcat.category_id);
        const parentSlug = parentCat ? generateSlug(parentCat.name) : 'category';
        const subcatSlug = generateSlug(subcat.name);
        const viewAllLink = `/category/${parentSlug}/${subcatSlug}`;

        return (
          <div key={subcat.subcategory_id} className="mt-32">
            <div className="flex flex-col md:flex-row md:items-end justify-between mb-12 gap-4">
              <div>
                <h2 className="text-4xl md:text-5xl font-black text-gray-900 tracking-tight mb-3">
                  {subcat.name}
                </h2>
                <p className="text-gray-500 font-medium text-lg">Premium collection of {subcat.name.toLowerCase()}.</p>
              </div>
              <Link href={viewAllLink} className="text-foreground font-bold hover:text-foreground/80 transition-colors flex items-center gap-2">
                View All <span className="text-xl">→</span>
              </Link>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
              {subcatProducts.slice(0, 4).map((product) => (
                <ProductCard
                  key={product.submodel_id || product.inward_id || product.variant_id}
                  product={{
                    ...product,
                    category_name: parentCat?.name || product.category_name,
                    subcategory_name: subcat.name || product.subcategory_name,
                  }}
                />
              ))}
            </div>
          </div>
        );
      })}
    </>
  );
}

export default function Home() {
  return (
    <div className="flex flex-col min-h-screen bg-transparent">
      <main className="flex-grow">
        <HeroSlider />
        <div className="max-w-[90rem] mx-auto px-4 sm:px-6 lg:px-8 py-20">
          <div className="flex flex-col md:flex-row md:items-end justify-between mb-12 gap-4">
            <div>
              <h2 className="text-4xl md:text-5xl font-black text-gray-900 tracking-tight mb-3">
                Explore Categories
              </h2>
              <p className="text-gray-500 font-medium text-lg">Find exactly what you're looking for.</p>
            </div>
            <div className="w-16 h-1.5 bg-gradient-to-r from-primary to-accent rounded-full md:hidden"></div>
          </div>

          <Suspense fallback={<ExploreSkeleton />}>
            <CategoryExploreSection />
          </Suspense>

          <Suspense fallback={<ProductGridSkeleton />}>
            <NewArrivalsSection />
          </Suspense>

          <Suspense fallback={<ProductGridSkeleton />}>
            <BestSellersSection />
          </Suspense>

          <Suspense fallback={<ProductGridSkeleton />}>
            <SubcategoryCollectionsSection />
          </Suspense>

          <WhyChooseUsGrid />
        </div>
      </main>
    </div>
  );
}
