"use client";

import { useEffect, useState } from "react";

import CatSecHome from "./components/CatSecHome";
import ProductCard from "./components/ProductCard";
import HeroSlider from "./components/HeroSlider";
import ServiceSection from "./components/ServiceSection";
import ProductSliderColumns from "./components/ProductSliderColumns";
import OfferSection from "./components/OfferSection";
import BlogSection from "./components/HomeBlogSection";
import Footer from "./components/Footer";

const API_URL = "http://localhost:5000";

type Product = {
  id: number;
  category_id: number;
  subcategory_id: number;
  name: string;
  description: string | null;
  short_description: string | null;
  slug: string;
  sku: string | null;
  brand: string | null;
  manufacturer: string | null;
  barcode: string | null;
  buying_price: number;
  regular_price: number;
  sale_price: number | null;
  stock_quantity: number;
  prescription_required: number;
  image: string | null;
  status: "active" | "inactive";
  category_name: string | null;
  subcategory_name: string | null;

  is_top_rated: number;
  is_top_selling: number;
  is_trending: number;
};

type CardProduct = {
  id: number;
  image: string;
  category: string;
  title: string;
  price: number;
  oldPrice?: number;
  sale: boolean;
};

function formatProduct(product: Product): CardProduct {
  const regularPrice = Number(product.regular_price || 0);

  const salePrice =
    product.sale_price !== null
      ? Number(product.sale_price)
      : null;

  const hasSale =
    salePrice !== null &&
    salePrice > 0 &&
    salePrice < regularPrice;

  return {
    id: product.id,
    image: product.image || "/products/01_1_.jpg",
    category: product.category_name || "Pharmacy",
    title: product.name,
    price: hasSale ? salePrice! : regularPrice,
    oldPrice: hasSale ? regularPrice : undefined,
    sale: hasSale,
  };
}

export default function Home() {
  const [products, setProducts] = useState<CardProduct[]>([]);
  const [trendingProducts, setTrendingProducts] = useState<CardProduct[]>([]);
  const [topRatedProducts, setTopRatedProducts] = useState<CardProduct[]>([]);
  const [topSellingProducts, setTopSellingProducts] = useState<CardProduct[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchProducts() {
      try {
        const response = await fetch(`${API_URL}/api/products`);

        if (!response.ok) {
          throw new Error("Failed to fetch products");
        }

        const data: Product[] = await response.json();

        const activeProducts = data.filter(
          (product) => product.status === "active"
        );

        // Main homepage products:
        // Only products with a valid sale price
        const saleProducts = activeProducts
          .filter(
            (product) =>
              product.sale_price !== null &&
              Number(product.sale_price) > 0 &&
              Number(product.sale_price) <
                Number(product.regular_price)
          )
          .map(formatProduct);

        // Trending:
        // Only products manually selected in Admin
        const trending = activeProducts
          .filter(
            (product) => Number(product.is_trending) === 1
          )
          .map(formatProduct);

        // Top Rated:
        // Only products manually selected in Admin
        const topRated = activeProducts
          .filter(
            (product) => Number(product.is_top_rated) === 1
          )
          .map(formatProduct);

        // Top Selling:
        // Only products manually selected in Admin
        const topSelling = activeProducts
          .filter(
            (product) => Number(product.is_top_selling) === 1
          )
          .map(formatProduct);

        setProducts(saleProducts);
        setTrendingProducts(trending);
        setTopRatedProducts(topRated);
        setTopSellingProducts(topSelling);
      } catch (error) {
        console.error(
          "Failed to load homepage products:",
          error
        );
      } finally {
        setLoading(false);
      }
    }

    fetchProducts();
  }, []);

  return (
    <>
      <HeroSlider />

      <CatSecHome />

      {/* Main Sale Products */}
      <section className="py-10 lg:py-16 px-4 lg:px-0">
        <div className="max-w-7xl mx-auto">
          {loading ? (
            <div className="py-12 text-center">
              <p className="text-sm text-gray-400">
                Loading products...
              </p>
            </div>
          ) : products.length === 0 ? (
            <div className="py-12 text-center">
              <p className="text-sm text-gray-400">
                No products available.
              </p>
            </div>
          ) : (
            <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-6">
              {products.slice(0, 10).map((product) => (
                <ProductCard
                  key={product.id}
                   id={product.id}
                  image={product.image}
                  category={product.category}
                  title={product.title}
                  price={product.price}
                  oldPrice={product.oldPrice}
                  sale={product.sale}
                />
              ))}
            </div>
          )}
        </div>
      </section>

      <OfferSection />

      <ServiceSection />

      {/* Admin Controlled Product Sections */}
      <ProductSliderColumns
        trending={trendingProducts}
        topRated={topRatedProducts}
        topSelling={topSellingProducts}
      />

      <BlogSection />

      <Footer />
    </>
  );
}