"use client";
import Image from "next/image";

import {
  fetchOffersRequest,
  fetchOffersSuccess,
  fetchOffersFailure,
} from "@/store/offer/actions";
import { useState, useEffect, useRef } from "react";
import Link from "next/link";
import { useDispatch } from "react-redux";
import { useTranslations, useLocale } from "next-intl";
import { usePathname } from "next/navigation";
import { useRouter } from "next/navigation";
import axios from "../../utils/axios-config";
import { saveOffer } from "@/store/offer/actions";
import { setOffer } from "@/store/offer/actions";
import OfferSkeleton from "../skeletons/skeleton-offers";



import CategoriesSkeleton from "../skeletons/skeleton-categories";
import "swiper/css";
import "swiper/css/navigation";
import "swiper/css/pagination";
import { Swiper, SwiperSlide } from "swiper/react";
import { IoIosArrowBack, IoIosArrowForward } from "react-icons/io";

import { Navigation, Autoplay, Pagination } from "swiper/modules";

type offer = {
  id: number;
  title: string;
  image: string;
  free_quantity: number;
  discount_value: number;
  buy_quantity: number;
  discount_type: string;
  type: number;
};

export interface DataType {
  offers: offer[];
  title?: string;
}

export default function TopOffers() {
  const locale = useLocale();
  const router = useRouter();
  const pathName = usePathname();
  const t = useTranslations();
  const dispatch = useDispatch();

  const [offers, setOffers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
const swiperRef = useRef<any>(null);
  useEffect(() => {
    // Fetch offers from API
    const fetchOffers = async () => {
      dispatch(fetchOffersRequest());
      const params: { [key: string]: string | number } = {};
      try {
        const response = await axios.get("/offers");
        const data = await response?.data;
        setOffers(data?.data || []);
        console.log("offers", data.data);
        dispatch(fetchOffersSuccess(data?.data));
      } catch (err) {
        setError("Failed to fetch offers.");
        if (err instanceof Error) {
          dispatch(fetchOffersFailure(err.message));
        } else {
          dispatch(fetchOffersFailure("An unknown error occurred."));
        }
        console.error(err);
      } finally {
        setLoading(false);
      }
    };

    fetchOffers();
  }, []);

  // const handleOfferClick = (offer: { id: any }) => {
  //   router.push(`/${locale}/offers/${offer.id}`); // Navigate to products page
  // };

  if (loading) {
    return (
      <section className="top-offers py-4 px-4">
        <div className="container px-4 mx-auto">
          <h2 className="text-white bg-primary px-2 w-fit rounded-sm bg-opacity-60 text-[14px]  sm:text-[16px]  font-bold ">
            {t("top-offers")}
          </h2>
          <OfferSkeleton />
        </div>
      </section>
    );
  }

  // if (error) {
  //   return <p className="text-center mt-10 text-red-500">{error}</p>;
  // }

  if (offers.length === 0) {
    return (
      // <div className="w-full flex flex-col items-center justify-center text-center p-4 my-5">
      //   <div className="w-64 h-auto">
      //     <Image
      //       src={"/images/no-items.png"}
      //       alt={t("no-offer-available")}
      //       width={365}
      //       height={275}
      //       className="object-contain"
      //     />
      //   </div>

      //   {/* Message */}
      //   <p className="text-lg font-semibold text-gray-600 mt-2">
      //     {t("no-offer-available")}
      //   </p>
      // </div>
      <></>
    );
  }

  

  return (
    // <section className="top-offers py-8 px-4">
      <div className="container pt-2 px-4 mx-auto lg:max-w-[1300px]">
        <div className="flex items-end gap-2 ">

        <h2 className="text-white bg-primary px-2 w-fit rounded-sm bg-opacity-50 text-[14px]  sm:text-[16px]  font-bold ">
          {t("top-offers")}
        </h2>
        {
          offers?.length < 20 ? null : (

            <Link href={'/offers/all-offers'} className="underline text-primary">{t('see-all')}</Link>
          )

        }
        </div>
        {/* <div className="grid md:justify-center lg:justify-center items-center gap-6 sm:grid-cols-1 md:grid-cols-1 lg:grid-cols-2">
          {offers.map((offer: any, index) => (
            <div
              className="relative card    w-full h-full p-4 rounded-lg flex items-center cursor-pointer"
              key={index}
            >
              <Link
                href={`/${locale}/offers/${offer?.id}`}
                locale={false}
                className="absolute z-50 cursor-pointer !text-transparent !bg-transparent w-full h-full left-0 top-0"
              />
              <div className="container   gap-3 items-center">
                <div className="relative  z-40 w-full h-full flex flex-col justify-center items-center mb-4 md:mb-0 lg:mb-0">
                  
                   <div className="flex flex-row items-center pt-5">
                    <p className="text-[#1B87AE] text-[18px] md:text-[24px] inline-block truncate text-center font-bold">
                      {offer.title}
                    </p>
                    {offer?.discount_value ? (
                      <span className="flex items-center font-medium mx-2 rounded-full bg-[#fff] text-[#36a79c] text-[1rem] text-center py-1 px-3  min-w-[61px] h-[27.2px] leading-[1.2]">
                        {offer.discount_value}{" "}
                        {offer.discount_type === 1 ? (
                          <Image
                            src={"/images/ryial.svg"}
                            alt="currancy icon"
                            width={25}
                            height={25}
                            className=""
                          />
                        ) : (
                          "%"
                        )}{" "}
                      </span>
                    ) : null}
                  </div>
                  <p className=" text-[#FBC43A]   text-[14px] md:text-[16px] text-center">
                    
                    {offer?.description}
                  </p>
                 
                </div>
                <Image
                  src={offer.image || "/images/offers/offer-placeholder.png"}
                fill
                 // height={100}
                  alt={offer.title}
                  unoptimized
                  className="object-cover"
                />
              </div>
            </div>
          ))}
        </div> */}
         {offers.length > 0 ? (
            <div className=" relative mx-auto  ">
              <div className="absolute top-[12.5%] left-[0]  w-full  h-full  flex ">
                <div className="swiper-buttons w-full h-[75%] flex items-center  justify-between gap-2 rtl:flex-row-reverse">
                  <button className="brands-swiper-button-prev-custom z-20 w-[30px] hover:w-[40px] text-primary bg-white hover:bg-primary hover:text-white h-[80px] rounded-r-sm transition-all duration-300 ease-in-out shadow-custom-slider  flex justify-center items-center">
                    <IoIosArrowBack className=" text-[30px]" />
                  </button>
                  <button className="brands-swiper-button-next-custom z-20 w-[30px] hover:w-[40px] text-primary bg-white hover:bg-primary hover:text-white h-[80px] rounded-l-sm transition-all duration-300 ease-in-out shadow-custom-slider  flex justify-center items-center">
                    <IoIosArrowForward className=" text-[30px]" />
                  </button>
                </div>
              </div>
             
              <div className="w-full  mx-auto ">
                <Swiper
                  slidesPerView={6}
                  //spaceBetween={40}
                  
                  breakpoints={{
                    0: {
                      slidesPerView: 1,
                    },
                    400: {
                      slidesPerView: 1,
                    },
                    500: {
                      slidesPerView: 2,
                    },
                    650: {
                      slidesPerView: 2,
                    },
                    1000: {
                      slidesPerView: 3,
                    },
                    1350: {
                      slidesPerView: 4,
                    },
                    1500: {
                      slidesPerView: 4,
                    },
                    1700: {
                      slidesPerView: 4,
                    },
                  }}
                  //  centeredSlides={true}
                  loop={true}
                  navigation={{
                    nextEl: ".brands-swiper-button-next-custom",
                    prevEl: ".brands-swiper-button-prev-custom",
                  }}
                  pagination={{
                    clickable: true,
                    type: "bullets",
                    dynamicBullets: true,
                  }}
                  
                  autoplay={{
                    delay: 2000,
                    disableOnInteraction: false,
                  }}
                  //autoplay={false}
                  modules={[Navigation,Pagination, Autoplay]}
                  className="swiper "
                  //onSwiper={(swiper) => (swiperRef.current = swiper)} 
                >
                  {offers?.map((item: any, index: any) => (
                    <SwiperSlide
                      className="mb-2 "
                      
                      key={index}
                      onMouseEnter={() => swiperRef.current?.autoplay.stop()}
                      onMouseLeave={() => swiperRef.current?.autoplay.start()} 
                    >
                      <div
                        className="aspect-[105/59]   relative flex justify-center flex-col items-center rounded-[10px]"
                        onClick={() => {
                         
                           router.push(`/${locale}/offers/${item?.id}`);
                          
                        }}
                      >
                        <Link
                          href={`/${locale}/offers/${item?.id}`}
                          locale={false}
                          className="absolute w-full h-full top-0 left-0 z-[99]"
                        ></Link>
                        {/* <div className="bg-[#defffc] mb-2 relative w-[120px] h-[120px]  rounded-[50%] flex items-center justify-center"> */}
                        <Image
                          src={item?.image}
                          alt={item?.title}
                          //  width={300}
                          //  height={160}
                          fill
                          //layout="fill"
                          className="object-contain p-[10px]"
                          priority
                        />
                        
                      </div>
                    </SwiperSlide>
                  ))}
                </Swiper>
              </div>
            </div>
          ) : (
            <CategoriesSkeleton />
          )}
      </div>
    // </section>
  );
}
