"use client";
import Image from "next/image";
import { Swiper, SwiperSlide } from "swiper/react";

import "swiper/css";
import "swiper/css/grid";
import { Grid } from "swiper/modules";
import { Icons } from "../icons";
import { useEffect, useState } from "react";
import apis, { BUCKET_ROOT } from "@/utils/apis";
import { Dot, Heart } from "lucide-react";
import { useRouter } from "next/navigation";
import { useGlobalContext } from "@/context/Provider";
import { useSelector } from "react-redux";
import { RootState } from "@/store/store";
import "swiper/css/navigation";
import { Navigation } from "swiper/modules";

import * as Progress from '@radix-ui/react-progress';
import { getValidImage } from "@/lib/utils";

interface HomeRestrosProps {
  selectedCategoryId: string | null;
}

const CategoryCard = ({ image, title, data, onFavourite, auth }: any) => {
  const address = data?.address?.name.split(",");
  const toggleFavorite = async (id: string, status: boolean) => {
    onFavourite(id, status);
  };

  return (
    <div className="bg-white rounded-xl overflow-hidden shadow-sm hover:shadow-md transition-shadow cursor-pointer h-full">
      <div className="relative h-48 w-full">
        <Image src={image} alt={title} fill className="object-cover" />

        {auth && (data?.is_fav ? (
          <div
            className="absolute top-2 right-2 bg-white rounded-full p-1 shadow-sm"
            onClick={(e) => {
              e.stopPropagation();
              toggleFavorite(data._id, data?.is_fav);
            }}
          >
            <Icons.Heart />
          </div>
        ) : (
          <div
            className="absolute top-2 right-2 bg-white rounded-full p-1 shadow-sm"
            onClick={(e) => {
              e.stopPropagation();
              toggleFavorite(data._id, data?.is_fav);
            }}
          >
            <Heart size={15} />
          </div>
        ))}
      </div>

      <div className="p-3">
        <h3 className="font-medium text-base text-start">{title}</h3>

        {data?.restaurant_type === "home-cooked-meal" && (
          <div className="w-full flex justify-start">
            <div className="inline-flex items-center mt-1 rounded-full bg-brand-100 text-primary text-[11px] font-medium">
              🍱 Home Cooked Meal
            </div>
          </div>
        )}

        <div className="flex items-center mt-1 text-sm">
          {data?.rating_count > 0 && (
            <div className="flex w-[20px] h-[20px] items-center bg-primary text-white justify-center rounded-full mr-2">
              <Icons.Star />
            </div>
          )}
          {data?.rating_count > 0 && (
            <>
              {data?.rating}({data?.rating_count}) <Dot color="#000" />{" "}
            </>
          )}
          <div>
            {data?.average_preparing_time - 5}-{data?.average_preparing_time} mins
          </div>
        </div>

        <div className="text-xs text-[#847f7f] mt-1 text-start flex flex-row items-center">
          <span className="flex items-center">
            {data?.distance?.distance} km approx.
          </span>
          <Dot color="#847f7f" />
          <span className="ml-1">
            {address?.[0]?.length > 20 ? `${address[0].slice(0, 20)}...` : address?.[0]}
          </span>
        </div>
      </div>
    </div>
  );
};


const HomeRestros: React.FC<HomeRestrosProps> = ({ selectedCategoryId }) => {
  const { Toast, userInfo } = useGlobalContext();
  const selectedAddress = useSelector(
    (state: RootState) => state.user.profile.selectedAddress
  );
  const [resList, setResList] = useState<any>([]);
  const [location, setLocation] = useState<{ lat: number; long: number } | null>(null);
  const [loading, setLoading] = useState(true);
  const router = useRouter();

  const getRes = async (customLocation?: { lat: number; long: number }) => {
    try {
      const getAndFetch = async (lat: number, long: number) => {
        const params = new URLSearchParams({
          page: "1",
          limit: "100",
        });
        const payLoad = {
          lat,
          long,
          ...(selectedCategoryId ? { category: selectedCategoryId } : {}),
        };
        const apiRes = await apis.restaurant.getAll(params.toString(), payLoad);
        setResList(apiRes?.data);
        setLoading(false);
      };

      if (selectedAddress && selectedAddress.lat && selectedAddress.long) {
        getAndFetch(parseFloat(selectedAddress.lat), parseFloat(selectedAddress.long));
      } else if (customLocation) {
        getAndFetch(customLocation.lat, customLocation.long);
      } else if (location) {
        getAndFetch(location.lat, location.long);
      } else {
        navigator.geolocation.getCurrentPosition(
          (position) => {
            const { latitude, longitude } = position.coords;
            setLocation({ lat: latitude, long: longitude });
            getAndFetch(latitude, longitude);
          },
          (error) => {
            console.error("Location error:", error);
          }
        );
      }
    } catch (error) {
      console.error("GetRes error:", error);
    }
  };

  useEffect(() => {
    getRes();
  }, [selectedAddress, selectedCategoryId]);

  const handleSelect = (data: any) => {
    router.push(`/restaurant?id=${data}`);
  };

  const handleFavourite = async (id: string, status: boolean) => {
    try {
      const payLoad = {
        restaurant_id: id,
        status: status ? "dislike" : "favourite",
      };
      const apiRes = await apis.Favourite.toggle(payLoad);

      if (apiRes) {
        if (selectedAddress && selectedAddress.lat && selectedAddress.long) {
          getRes({ lat: parseFloat(selectedAddress.lat), long: parseFloat(selectedAddress.long) });
        } else if (location) {
          getRes(location);
        } else {
          navigator.geolocation.getCurrentPosition(
            (position) => {
              const { latitude, longitude } = position.coords;
              setLocation({ lat: latitude, long: longitude });
              getRes({ lat: latitude, long: longitude });
            },
            (error) => {
              console.error("Location error:", error);
            }
          );
        }
        Toast.success(status ? "Vendor/Store removed from favourites" : "Vendor/Store added to favourites");
      }
    } catch (error) {
      console.error("Favourite error:", error);
    }
  };

  return (
    <div className="max-w-7xl mt-4 flex flex-row mx-auto py-8 px-4">
      <div className="mb-8 w-[40%] h-[600px] flex items-center flex-col justify-center gap-2 px-3">
        <div className="w-full text-left">
          <h2 className="text-h4 font-medium">
            <span className="text-primary">OUR RESTAURANTS</span>
          </h2>
        </div>
        <p className="w-full text-left text-gray-800 text-h1 font-bold">
          Food That Always Makes You Fall In{" "}
          <span className="text-primary">Love</span>
        </p>
      </div>

      <div className="w-[70%] h-[600px]">
        {loading ? (
          <div className="flex justify-center items-center h-full">
            <Progress.Root value={100} max={100} className="w-16 h-16 bg-transparent relative rounded-full">
              <Progress.Indicator
                style={{
                  width: '100%',
                  height: '100%',
                  transformOrigin: 'center',
                  animation: 'spin 1.5s linear infinite',
                  borderRadius: '50%',
                  border: '4px solid transparent',
                  borderTop: '4px solid hsl(var(--primary))',
                }}
              />
            </Progress.Root>
          </div>
        ) : (
          <div className="home-restros-swiper">
            <Swiper
              slidesPerView={resList?.length < 3 ? 1 : resList?.length < 5 ? 2 : 3}
              grid={{ rows: 2, fill: "row" }}
              spaceBetween={20}
              pagination={{ clickable: true }}
              navigation={true}
              modules={[Grid, Navigation]}
              className="mySwiper"
              style={{ width: "100%", height: "auto" }}
            >
              {resList?.length > 0 &&
                resList.map((item: any) => (
                  <SwiperSlide key={item._id} onClick={() => handleSelect(item._id)}>
                    <div className="h-full w-full px-2">
                      <CategoryCard
                        image={getValidImage(item.image ? item.image : item.uploadRestaurantPhotos[0])}
                        title={item.restaurant_name}
                        data={item}
                        onFavourite={handleFavourite}
                        auth={userInfo}
                      />
                    </div>
                  </SwiperSlide>

                ))}
            </Swiper>
          </div>
        )}
      </div>
    </div>
  );
};

export default HomeRestros;