"use client"
import ProductCard from "./product-card"
import { getOneCategory, getproductForcategory } from "@/lib/features/web/service"
import { useQuery } from "@tanstack/react-query"
import { CategoryDetailProps, ProductProps } from "@/lib/features/web/type"
import { url } from "@/lib/constant"
import Loading from "../loading"
import Categories from "./navbar"
import Header from "./header"
import Footer from "./footer"

interface Props {
  categoryId: string;
}

export default function Category({ categoryId }: Props) {


    // products
    const { data, isLoading, error } = useQuery({
      queryKey: ["products-for-category"],
      queryFn: () => getproductForcategory(categoryId),
    });

    // // get product
    const { data: categData, isLoading: isCategLoading, error: errorCateg } = useQuery({
      queryKey: ["category-details"],
      queryFn: () => getOneCategory(categoryId),
    });


    if (isLoading || isCategLoading) {
        return <Loading />;
    }

    if (error) return "Network error ";
    if (errorCateg) return "Network error ";

    const phones: ProductProps[] = data?.data || [];

    const details: CategoryDetailProps = categData?.data || null;


  return (
    <main className="min-h-screen">

      {/* Header */}
      <Header />



      {/* Navigation */}
      <Categories />


      {/* Products Section */}
      <section className="py-12 bg-gray-100">
        <div className="container-fluid mx-auto px-4">
          <h2 className="text-3xl font-bold text-center mb-10 flex items-center justify-center">
            <span className="border-t border-gray-400 w-16 mr-4"></span>
              {details?.tbl_product_categName}
            <span className="border-t border-gray-400 w-16 ml-4"></span>
          </h2>

          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6 gap-6">
            {phones?.map( (phoneItem) =>(

                <ProductCard  key={phoneItem?.tbl_productToken}
                    image={url+'img/'+phoneItem?.tbl_productPhoto}
                    title={phoneItem?.tbl_productBrand}
                    color="Gold"
                    price={new Intl.NumberFormat("en-US", {
                        minimumFractionDigits: 0,
                        maximumFractionDigits: 2,
                      }).format( Number(phoneItem?.tbl_productPrice) )}
                    
                    token={phoneItem?.tbl_productToken}
                />
            ))}

          </div>
        </div>
      </section>

      <br />


      <br />


      {/* WhatsApp Chat Button */}
      <Footer />
    </main>
  )
}
