import { Button } from "antd";
import { FC, useContext, useEffect, useState } from "react";
import {
  getDiscountPercent,
  getDiscountPercentHome,
} from "../../../constants/commonFunction";
import { baseUrl, web_url } from "../../../constants/urls";
import styles from "./categoryProduct.module.scss";
import cx from "classnames";
import { useRouter } from "next/router";
import { createBreadcrumb, getFlattenCategory } from "../../globalUtils/utils";
import shopConetxt from "../../../context/shopConetxt";
import * as CategoryAPI from "../../../pages/api/category";
import { get } from "lodash";
import Slider from "react-slick";

// Import slick carousel styles
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";

const CategoryProduct: FC<any> = ({
  title = "",
  type = "",
  bearingData = [],
  category = [],
  categoryTree = [],
}) => {
  const { setCategoryTreeNested, setCategoryBreadcrumb, categoryTreeNested } =
    useContext(shopConetxt);
  const [categoryData, setCaregoryData] = useState([]);
  const [categoryTreeData, setCaregoryTreeData] = useState([]);
  const router = useRouter();
  const [hoveredCard, setHoveredCard] = useState<number | null>(null);

  // Fix: Ensure bearingData has a fallback empty array
  const productsData = bearingData || [];

  const redirectUrl = (product: any) => {
    if (product?.lastCategory) {
      const flattenCategory = getFlattenCategory(categoryTreeNested);
      const breadCrumbData = createBreadcrumb(
        product?.lastCategory,
        flattenCategory
      );
      localStorage.setItem("breadCrumbData", JSON.stringify(breadCrumbData));
      setCategoryBreadcrumb(breadCrumbData);
    } else {
      setCategoryBreadcrumb([]);
      localStorage.removeItem("breadCrumbData");
    }
  };

  // Custom arrow components with proper accessibility
  function SampleNextArrow(props: any) {
    const { className, style, onClick } = props;
    return (
      <div
        className={className}
        style={{
          ...style,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          background: "#291C61",
          borderRadius: "50%",
          width: "40px",
          height: "40px",
          right: "-15px",
          zIndex: 1,
          cursor: "pointer",
        }}
        onClick={onClick}
      >
        <svg
          width="24"
          height="24"
          viewBox="0 0 24 24"
          fill="none"
          xmlns="http://www.w3.org/2000/svg"
        >
          <path
            d="M9 18L15 12L9 6"
            stroke="#fff"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          />
        </svg>
      </div>
    );
  }

  function SamplePrevArrow(props: any) {
    const { className, style, onClick } = props;
    return (
      <div
        className={className}
        style={{
          ...style,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          background: "#291C61",
          borderRadius: "50%",
          width: "40px",
          height: "40px",
          left: "-15px",
          zIndex: 1,
          cursor: "pointer",
        }}
        onClick={onClick}
      >
        <svg
          width="24"
          height="24"
          viewBox="0 0 24 24"
          fill="none"
          xmlns="http://www.w3.org/2000/svg"
        >
          <path
            d="M15 18L9 12L15 6"
            stroke="#fff"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          />
        </svg>
      </div>
    );
  }

  const sliderSettings = {
    dots: false,
    infinite: true,
    speed: 500,
    slidesToShow: 6,
    slidesToScroll: 1,
    autoplay: true,
    autoplaySpeed: 3000,
    arrows: true,
    nextArrow: <SampleNextArrow />,
    prevArrow: <SamplePrevArrow />,
    responsive: [
      {
        breakpoint: 1600,
        settings: {
          slidesToShow: 5,
        },
      },
      {
        breakpoint: 1280,
        settings: {
          slidesToShow: 4,
        },
      },
      {
        breakpoint: 1024,
        settings: {
          slidesToShow: 3,
        },
      },
      {
        breakpoint: 768,
        settings: {
          slidesToShow: 2,
        },
      },
      {
        breakpoint: 480,
        settings: {
          slidesToShow: 2,
          centerMode: true, // Always center mode on mobile for single column
          centerPadding: "0px",
        },
      },
    ],
  };

  useEffect(() => {
    setCaregoryTreeData(categoryTree);
    setCaregoryData(category);
  }, [category, categoryTree, categoryTreeNested]);

  const viewAllProduct = () => {
    router.push({
      pathname: `/products/All`,
      query: {
        search: title,
      },
    });
  };

  // Debug: Check if data is available

  return (
    <div className={styles.containerCategory} style={{background:title=="Motors"?"#F2F2F2":'transparent'}}>
      <div className="container">
        <div className="ant-row">
          <div
            className={cx(
              "ant-col-xl-24 ant-col-xs-24",
              styles.sectionSubTitle
            )}
          >
            {title}
          </div>
        </div>
        <div className={styles.cardContainer}>
          {/* Fix: Check if productsData has items before rendering slider */}
          {productsData.length > 0 ? (
            <Slider {...sliderSettings}>
              {productsData.map((product: any, idx: number) => {
               
                return (
                  <div
                    key={`${product.product_id}-${idx}`}
                    className={styles.slideItem}
                  >
                    <a
                      href={`/products/details/${product.url_key}-${product.product_id}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      onClick={() => {
                        redirectUrl(product);
                      }}
                    >
                      {/* <div className={styles.discountMain}>
                        {parseInt(product.special_price) > 0 ? (
                          product?.special_price ? (
                            <div className={styles.discountButton}>
                              {`${getDiscountPercentHome(product)}% OFF`}
                            </div>
                          ) : null
                        ) : null}
                      </div> */}
                      <div
                        className={styles.productImgParent}
                        style={{
                          width: "100%",
                          height:  180,
                          objectFit: "cover",
                          transition: "all 0.3s ease",
                        }}
                      >
                        {product?.base_image === null ? (
                          <img
                            src={baseUrl + "/" + product?.default_image}
                            className={cx("mb-5", styles.image)}
                            alt={product?.name || ""}
                          />
                        ) : (
                          <img
                            src={product?.s3_base_url + product?.base_image}
                            className={cx("mb-5", styles.image)}
                            alt={product?.name || ""}
                          />
                        )}
                      </div>

                      <div className={styles.cardTitle}>{product?.name} </div>
                         
                      {/* <div className="flex items-center mt-4">
                        <div className={styles.price}>
                          ₹
                          {parseFloat(
                            product?.special_price || product?.price || 0
                          ).toFixed(2)}
                        </div>
                        <div className={styles.exc}>Exc. of GST</div>
                      </div> */}
                    </a>
                    <Button 
                      className={styles.rfqButton}
                      onClick={(e) => {
                        e.preventDefault();

                        const data1 = {
                                name:product?.name,
                                brand:product?.brand_name,
                                description:`${web_url}/products/details/${product.url_key}-${product.product_id}`,
                                uom:""
                              }
                              const newVal =JSON.stringify(data1);
                              router.push(
                                {
                                  pathname: `/rfq`,
                                  query: {data:newVal},
                                },
                                "/rfq"
                              );
                        
                      }}
                    >
                      Send RFQ
                    </Button>
                  </div>
                );
              })}
            </Slider>
          ) : (
            <div className={styles.noProducts}>No products available</div>
          )}
        </div>
      </div>
    </div>
  );
};

export default CategoryProduct;