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 { FaTrophy, FaBolt, FaHandshake } from "react-icons/fa";

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;
};

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;
};

async function getCategories() {
  try {
    const res = await fetch(
      `${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/product-master/categories/`,
      { cache: 'no-store' }
    );
    if (!res.ok) return [];
    return (await res.json()) as Category[];
  } catch (error) {
    console.error("Error fetching categories:", error);
    return [];
  }
}

async function getSubcategories() {
  try {
    const res = await fetch(
      `${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/product-master/subcategories/`,
      { cache: 'no-store' }
    );
    if (!res.ok) return [];
    return (await res.json()) as Subcategory[];
  } catch (error) {
    console.error("Error fetching subcategories:", error);
    return [];
  }
}

async function getNewArrivals() {
  try {
    const res = await fetch(
      `${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/b2b-admin/inwards/cards?is_new_arrival=true&is_active=true`,
      { cache: 'no-store' }
    );
    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(
      `${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/b2b-admin/inwards/cards?is_best_seller=true&is_active=true`,
      { cache: 'no-store' }
    );
    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(
      `${process.env.NEXT_PUBLIC_API_BASE_URL}/api/v1/b2b-admin/inwards/cards?is_active=true`,
      { cache: 'no-store' }
    );
    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;
  });
}

export default async function Home() {
  const [categories, subcategories, rawNewArrivals, rawBestSellers, rawAllProducts] = await Promise.all([
    getCategories(),
    getSubcategories(),
    getNewArrivals(),
    getBestSellers(),
    getAllProducts()
  ]);

  const newArrivals = getUniqueProducts(rawNewArrivals);
  const bestSellers = getUniqueProducts(rawBestSellers);
  const allProducts = getUniqueProducts(rawAllProducts);

  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>

          {subcategories.length > 0 ? (
            <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';
                const getCategoryImage = (name: string, i: number) => {
                  const lower = name.toLowerCase();
                  if (lower.includes("full face")) return "https://static.wixstatic.com/media/703249_3a76a53b765e46d4b3a5e4c3ec6ddd7e~mv2.png/v1/fill/w_1362,h_1002,al_c,q_90,usm_0.66_1.00_0.01,enc_avif,quality_auto/Full%20Face%20Helmet.png";
                  if (lower.includes("all")) return "https://static.wixstatic.com/media/703249_46aba2e374064d82ba3813a289618cc9~mv2.png/v1/fill/w_1362,h_1002,al_c,q_90,usm_0.66_1.00_0.01,enc_avif,quality_auto/All%20Products.png";
                  if (lower.includes("beanie") || lower.includes("accessories")) return "https://static.wixstatic.com/media/703249_3e03447acdd64d5bbe98b7a67cb23b2c~mv2.png/v1/fill/w_1362,h_1002,al_c,q_90,usm_0.66_1.00_0.01,enc_avif,quality_auto/Explore%20more%20(1).png";

                  const fallbacks = [
                    "https://static.wixstatic.com/media/703249_3a76a53b765e46d4b3a5e4c3ec6ddd7e~mv2.png/v1/fill/w_1362,h_1002,al_c,q_90,usm_0.66_1.00_0.01,enc_avif,quality_auto/Full%20Face%20Helmet.png",
                    "https://static.wixstatic.com/media/703249_3e03447acdd64d5bbe98b7a67cb23b2c~mv2.png/v1/fill/w_1362,h_1002,al_c,q_90,usm_0.66_1.00_0.01,enc_avif,quality_auto/Explore%20more%20(1).png",
                    "https://static.wixstatic.com/media/703249_46aba2e374064d82ba3813a289618cc9~mv2.png/v1/fill/w_1362,h_1002,al_c,q_90,usm_0.66_1.00_0.01,enc_avif,quality_auto/All%20Products.png"
                  ];
                  return fallbacks[i % fallbacks.length];
                };

                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('${getCategoryImage(subcat.name, index)}')` }}
                    />
                    <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>
          ) : (
            <p className="text-center text-foreground/60">
              No subcategories available at the moment.
            </p>
          )}

          {/* New Arrivals Section */}
          <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>
              {(() => {
                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 (
                  <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>

          {/* Best Sellers Section */}
          <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>
              {(() => {
                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 (
                  <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>

          {/* Dynamic Subcategory Sections */}
          {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>
            );
          })}

          {/* Why Choose Us Section */}
          <WhyChooseUsGrid />
        </div>
      </main>
    </div>
  );
}
