"use client";

import React, { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { RootState } from "@/store/store";
import apis, { BUCKET_ROOT } from "@/utils/apis";
import { useGlobalContext } from "@/context/Provider";

import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";
import "swiper/css/pagination";
import { Pagination } from "swiper/modules";
import { useRouter } from "next/navigation";

const Banner = ({ type, restaurant_id }: { type?: string; restaurant_id?: string }) => {
  const router = useRouter();
  const { Toast } = useGlobalContext();

  const selectedAddress = useSelector(
    (state: RootState) => state.user.profile.selectedAddress
  );

  const [bannerList, setBannerList] = useState<any[]>([]);

  const getBanners = async () => {
    try {
      if (restaurant_id) {
        const res = await apis.Banner.getVendorBanner(restaurant_id);
        const list = res?.banners || res?.data || (Array.isArray(res) ? res : []);
        setBannerList(list);
        return;
      }

      let latitude = null;
      let longitude = null;

      if (selectedAddress?.lat && selectedAddress?.long) {
        latitude = parseFloat(selectedAddress.lat);
        longitude = parseFloat(selectedAddress.long);
      } else {
        const position = await new Promise<GeolocationPosition>(
          (resolve, reject) =>
            navigator.geolocation.getCurrentPosition(resolve, reject)
        );
        latitude = position.coords.latitude;
        longitude = position.coords.longitude;
      }

      const params = new URLSearchParams({
        lat: latitude.toString(),
        long: longitude.toString(),
        ...(type ? { type } : {}),
      });

      const res = await apis.Banner.getBanner(params.toString());
      setBannerList(res || []);
    } catch (error) {
      Toast.error(error);
    }
  };

  useEffect(() => {
    getBanners();
  }, [selectedAddress, restaurant_id]);

  if (bannerList.length === 0) {
    return null;
  }

  return (
    <div className="max-w-7xl mx-auto py-6 px-3 sm:py-5 sm:px-4">
      <Swiper
        slidesPerView={1}
        spaceBetween={12}
        pagination={{ clickable: true }}
        modules={[Pagination]}
        className="w-full h-[180px] sm:h-[250px] md:h-[300px] lg:h-[350px] rounded-lg"
      >
        {bannerList.map((banner) => (
          <SwiperSlide key={banner._id}>
            <div
              className="
                relative w-full 
                h-[180px] sm:h-[250px] md:h-[300px] lg:h-[350px] 
                rounded-lg overflow-hidden
              "
            >
              <img
                src={banner?.banner_url ? (banner.banner_url.startsWith("http") ? banner.banner_url : `${BUCKET_ROOT}${banner.banner_url.startsWith("/") ? banner.banner_url.slice(1) : banner.banner_url}`) : ""}
                alt={banner?.title}
                className="object-cover w-full h-full rounded-lg"
              />


              <div
                className="
                  absolute inset-0 flex items-center 
                  px-4 sm:px-8 md:ml-20
                "
              >
                <div
                  className="
                    p-2 sm:p-6 
                    bg-black/40 sm:bg-transparent 
                    rounded-md sm:rounded-l-lg 
                    max-w-[90%] sm:max-w-[60%]
                  "
                >
                  <h3 className="text-white text-lg sm:text-2xl font-bold break-words">
                    {banner?.title}
                  </h3>
                  <p className="text-white text-xs sm:text-sm mt-1 sm:mt-2 break-words line-clamp-3">
                    {banner?.description}
                  </p>
                </div>
              </div>
            </div>
          </SwiperSlide>
        ))}
      </Swiper>
    </div>
  );
};

export default Banner;
