"use client";

import { FC, useContext, useEffect, useState } from "react";
import { Button, Card, Col, Row, Tag, Typography } from "antd";
import { ShoppingCartOutlined } from "@ant-design/icons";
import Link from "next/link";
import { useRouter } from "next/router";
import shopConetxt from "../../../context/shopConetxt";
import { getFlattenCategory, createBreadcrumb } from "../../globalUtils/utils";
import { get } from "lodash";
import { baseUrl } from "../../../constants/urls";
import { getDiscountPercentHome } from "../../../constants/commonFunction";
import styles from "./greases.module.scss";
import Slider from "react-slick";

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

const { Title, Text } = Typography;

interface BalBearingProps {
  title?: string;
  type?: string;
  bearingData?: any[];
  category?: any[];
  categoryTree?: any[];
}

const Greases: FC<BalBearingProps> = ({
  title = "",
  type = "",
  bearingData = [],
  category = [],
  categoryTree = [],
}) => {
  const { setCategoryTreeNested, setCategoryBreadcrumb, categoryTreeNested } =
    useContext(shopConetxt);

  const [categoryData, setCaregoryData] = useState<any[]>([]);
  const [categoryTreeData, setCaregoryTreeData] = useState<any[]>([]);
  const [hoveredCard, setHoveredCard] = useState<number | null>(null);
  const router = useRouter();

  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");
    }
  };

  const handleAddToCart = (product: any, e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    // Add your add to cart logic here
    console.log("Add to cart:", product);
  };

  const handleBuyNow = (product: any, e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    // Add your buy now logic here
    console.log("Buy now:", product);
  };

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

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

  const sliderSettings = {
    dots: false,
    infinite: false,
    speed: 500,
    slidesToShow: 4,
    slidesToScroll: 1,
    autoplay: true,
    autoplaySpeed: 3000,
    arrows: true,
    responsive: [
      {
        breakpoint: 1024,
        settings: {
          slidesToShow: 3,
          slidesToScroll: 1,
        }
      },
      {
        breakpoint: 768,
        settings: {
          slidesToShow: 2,
          slidesToScroll: 1,
        }
      },
      {
        breakpoint: 480,
        settings: {
          slidesToShow: 1,
          slidesToScroll: 1,
        }
      }
    ]
  };

  return (
    <div style={{ background: "#F4EAFE", padding: "40px 20px" }}>
      <div className="container">
        <div className={styles.sectionSubTitle}>{title}</div>

        <Row gutter={[24, 24]} align="stretch" wrap>
          {/* Left Section - 30% */}
          <Col
            xs={24}
            md={6}
            className={styles.firstContainer}
          >
            <button
              type="button"
              className={styles.buttonContainer}
              onClick={viewAllProduct}
              aria-label={`View all products for ${title}`}
            >
              <Title level={3} style={{ color: "#fff", textAlign: "center" }}>
                {title}
              </Title>
            </button>
          </Col>

          {/* Right Section - 70% */}
          <Col xs={24} md={18}>
            <div style={{ padding: "0 10px" }}>
              <Slider {...sliderSettings}>
                {bearingData.slice(0, 12).map((product, idx) => (
                  <div key={idx} style={{ padding: "0 100px"}}>
                    <Link
                      href={`/products/details/${product.url_key}-${product.product_id}`}
                      passHref
                      legacyBehavior
                    >
                      <a 
                        target="_blank" 
                        style={{ textDecoration: "none" }}
                        onMouseEnter={() => setHoveredCard(idx)}
                        onMouseLeave={() => setHoveredCard(null)}
                      >
                        <Card
                          hoverable
                          onClick={() => redirectUrl(product)}
                          style={{
                            borderRadius: 16,
                            overflow: "hidden",
                            height: "100%",
                            position: "relative",
                            transition: "all 0.3s ease",
                            transform: hoveredCard === idx ? "translateY(-5px)" : "none",
                            boxShadow: hoveredCard === idx ? "0 8px 24px rgba(0,0,0,0.15)" : "0 4px 12px rgba(0,0,0,0.1)",
                          }}
                          cover={
                            <div 
                              style={{ 
                                background: "#fff", 
                                padding: hoveredCard === idx ? "8px" : "16px",
                                transition: "all 0.3s ease",
                                position: "relative",
                              }}
                            >
                              <img
                                src={
                                  product?.base_image === null
                                    ? `${baseUrl}/${product?.default_image}`
                                    : product?.s3_base_url + product?.base_image
                                }
                                alt={product?.name || "Product"}
                                style={{
                                  width: "100%",
                                  height: hoveredCard === idx ? 160 : 180,
                                  objectFit: "contain",
                                  transition: "all 0.3s ease",
                                }}
                              />
                              
                              {/* Cart Icon - Only visible on hover */}
                              {/* {hoveredCard === idx && (
                                <div
                                  style={{
                                    position: "absolute",
                                    top: "50%",
                                    left: "50%",
                                    transform: "translate(-50%, -50%)",
                                    zIndex: 2,
                                  }}
                                >
                                  <Button
                                    type="primary"
                                    shape="circle"
                                    icon={<ShoppingCartOutlined />}
                                    size="large"
                                    style={{
                                      background: "#8B008B",
                                      borderColor: "#8B008B",
                                      boxShadow: "0 4px 12px rgba(139, 0, 139, 0.3)",
                                      width: "50px",
                                      height: "50px",
                                      display: "flex",
                                      alignItems: "center",
                                      justifyContent: "center",
                                    }}
                                    onClick={(e) => handleAddToCart(product, e)}
                                  />
                                </div>
                              )} */}
                            </div>
                          }
                          bodyStyle={{ 
                            padding: "16px",
                            position: "relative",
                            minHeight: "140px"
                          }}
                        >
                          {parseInt(product.special_price) > 0 &&
                            product?.special_price && (
                              <Tag
                                style={{
                                  background: "#F3465F",
                                  color: "#fff",
                                  position: "absolute",
                                  top: 12,
                                  right: 12,
                                  fontWeight: 600,
                                  zIndex: 1,
                                }}
                              >
                                {getDiscountPercentHome(product)}% OFF
                              </Tag>
                            )}

                          <Text type="secondary" style={{ fontSize: 12, display: "block", marginBottom: "4px" }}>
                            {product?.category || "Auto Safety Bearings"}
                          </Text>
                          
                          <Title 
                            level={5} 
                            style={{ 
                              margin: "4px 0 8px 0",
                              fontSize: "14px",
                              lineHeight: "1.4",
                              height: "40px",
                              overflow: "hidden",
                              display: "-webkit-box",
                              WebkitLineClamp: 2,
                              WebkitBoxOrient: "vertical",
                            }}
                          >
                            {product?.name}
                          </Title>
                          
                          <div style={{ marginBottom: hoveredCard === idx ? "52px" : "0px", transition: "margin-bottom 0.3s ease" }}>
                            <Text strong style={{ fontSize: 18, color: "#8B008B", display: "block" }}>
                              ₹{parseFloat(product?.special_price).toFixed(2)}
                            </Text>
                            {parseInt(product.special_price) > 0 && product?.price && (
                              <Text 
                                delete 
                                type="secondary" 
                                style={{ fontSize: 14, color: "#999" }}
                              >
                                ₹{parseFloat(product?.price).toFixed(2)}
                              </Text>
                            )}
                            <Text
                              type="secondary"
                              style={{ fontSize: 12, display: "block", color: "#666" }}
                            >
                              Exc. of GST
                            </Text>
                          </div>

                          {/* Buy Now and Add to Cart Buttons - Only visible on hover */}
                          {hoveredCard === idx && (
                            <div 
                              style={{ 
                                position: "absolute",
                                bottom: 16,
                                left: 16,
                                right: 16,
                                display: "flex", 
                                gap: "8px",
                                animation: "fadeInUp 0.3s ease",
                              }}
                            >
                              <Button
                                type="primary"
                                block
                                style={{
                                  background: "#8B008B",
                                  borderColor: "#8B008B",
                                  height: "36px",
                                  fontWeight: 600,
                                  borderRadius: "6px",
                                  flex: 2,
                                }}
                                onClick={(e) => handleBuyNow(product, e)}
                              >
                                BUY NOW
                              </Button>
                              
                              <Button
                                type="default"
                                icon={<ShoppingCartOutlined />}
                                style={{
                                  height: "36px",
                                  width: "36px",
                                  borderRadius: "6px",
                                  borderColor: "#8B008B",
                                  color: "#8B008B",
                                  display: "flex",
                                  alignItems: "center",
                                  justifyContent: "center",
                                  flex: 0,
                                  minWidth: "36px",
                                }}
                                onClick={(e) => handleAddToCart(product, e)}
                              />
                            </div>
                          )}
                        </Card>
                      </a>
                    </Link>
                  </div>
                ))}
              </Slider>
            </div>
          </Col>
        </Row>
      </div>
    </div>
  );
};

export default Greases;