"use client";

import { Icons } from "../icons";
import { BUCKET_ROOT } from "@/utils/apis";
import { ArrowRight, Dot } from "lucide-react";
import { Swiper, SwiperSlide } from "swiper/react";

// Import Swiper styles
import "swiper/css";
import "swiper/css/pagination";
import { useRouter } from "next/navigation";
import { getValidImage, currency } from "@/lib/utils";
import { Skeleton } from "@/components/ui/skeleton";

const RestroCard = ({ title, data }: any) => {
  const router = useRouter();

  const storeId = data?._id || data?.store?._id;
  const storeType = data?.type || data?.store?.type;

  // Normalize items to display
  const itemsToDisplay = Array.isArray(data?.foods) && data.foods.length > 0
    ? data.foods
    : (Array.isArray(data?.items) ? data.items : (data?.items ? [data.items] : []));

  const stripHtml = (html: string) => {
    return html?.replace(/<[^>]*>?/gm, "") || "";
  };

  const handleHeaderClick = () => {
    if (storeType === "food") {
      router.push(`/restaurant?id=${storeId}`);
    } else {
      router.push(`/grocery/${storeId}?type=${storeType || 'grocery'}`);
    }
  };

  return (
    <div className="flex flex-col bg-white rounded-xl shadow-sm hover:shadow-md transition-shadow w-full p-4">
      <div
        className="w-full flex flex-row justify-between items-center cursor-pointer"
        onClick={handleHeaderClick}
      >
        <div className="flex flex-col">
          <span className="text-lg text-black font-semibold">{title}</span>
          <div className="flex items-center mt-1 text-sm">
            {data?.rating > 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} <Dot color="#847f7f" />
              </>
            )}
            <div className="text-gray-500">
              {data?.average_preparing_time
                ? `${data.average_preparing_time - 5}-${data.average_preparing_time
                } mins`
                : "N/A"}
            </div>
          </div>
        </div>
        <ArrowRight />
      </div>
      <div className="w-full">
        <Swiper
          slidesPerView={2}
          spaceBetween={30}
          pagination={{
            clickable: true,
          }}
          className="mySwiper"
        >
          {itemsToDisplay.length > 0 &&
            itemsToDisplay.map((item: any) => {
              const isFood = storeType === "food";
              const imageSrc = item?.imageUrl || (Array.isArray(item?.image) ? item.image[0] : item?.image);
              const imagePath = getValidImage(imageSrc);
              const itemRedirectUrl = isFood
                ? `/restaurant?id=${storeId}`
                : `/grocery/${storeId}?type=${storeType || 'grocery'}`;
              const description = isFood
                ? item?.description
                : stripHtml(item?.description);

              const hasDiscount =
                (item?.is_discount_active !== false) &&
                item?.discounted_price !== undefined &&
                item?.discounted_price !== null &&
                Number(item?.discounted_price) > 0 &&
                Number(item?.discounted_price) < Number(item?.price);

              return (
                <SwiperSlide
                  key={item?._id}
                  className="w-auto py-4 cursor-pointer"
                  onClick={() => router.push(itemRedirectUrl)}
                >
                  <div className="w-[350px] h-[160px] flex flex-row mt-4 border border-gray-300 rounded-lg overflow-hidden">
                    <div
                      className="w-[180px] h-[160px] relative flex flex-col justify-between border-r border-r-gray-200"
                      style={{
                        backgroundImage: `url(${imagePath})`,
                        backgroundSize: "cover",
                        backgroundPosition: "center",
                        backgroundRepeat: "no-repeat",
                      }}
                    />
                    <div className="w-[170px] h-[160px] flex flex-col items-center justify-around p-2 gap-1">
                      <p className="text-xl text-black font-medium w-full text-start truncate">
                        {item?.name}
                      </p>
                      <p className="w-full text-lg text-start font-semibold">
                        {hasDiscount ? (
                          <>
                            <span className="text-sm line-through text-gray-500 mr-2">
                              {currency}{item?.price}
                            </span>
                            <span className="text-primary">
                              {currency}{item?.discounted_price}
                            </span>
                          </>
                        ) : (
                          <span className="text-primary">
                            {currency}{item?.price}
                          </span>
                        )}
                      </p>
                      <span className="text-[#9c9595] text-sm w-full text-start line-clamp-2">
                        {description}
                      </span>
                    </div>
                  </div>
                </SwiperSlide>
              );
            })}
        </Swiper>
      </div>
    </div>
  );
};

const DishSkeleton = () => {
  return (
    <div className="flex flex-col bg-white rounded-xl shadow-sm w-full p-4">
      <div className="w-full flex flex-row justify-between items-center">
        <div className="flex flex-col gap-2">
          <Skeleton className="h-6 w-48" />
          <Skeleton className="h-4 w-32" />
        </div>
        <Skeleton className="h-6 w-6 rounded-full" />
      </div>
      <div className="w-full flex flex-row gap-6 mt-4">
        {[1, 2].map((i) => (
          <div key={i} className="w-[350px] h-[160px] flex flex-row border border-gray-100 rounded-lg overflow-hidden">
            <Skeleton className="w-[180px] h-full" />
            <div className="w-[170px] p-4 flex flex-col gap-3">
              <Skeleton className="h-5 w-full" />
              <Skeleton className="h-5 w-1/2" />
              <Skeleton className="h-4 w-full" />
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

const DishList = ({ data, loading }: any) => {
  return (
    <div className="w-full mt-4 flex flex-col mx-auto gap-6 px-4">
      {loading ? (
        [1, 2, 3].map((i) => <DishSkeleton key={i} />)
      ) : data?.length > 0 ? (
        data.map((item: any) => {
          const storeType = item?.type || item?.store?.type;
          const isFood = storeType === "food";
          const title = item.restaurant_name || (item.store?.restaurant_name) || (!isFood ? item.items?.[0]?.name : "");
          return (
            <RestroCard key={item._id || item.store?._id} title={title} data={item} />
          );
        })
      ) : (
        <div className="w-full h-full flex items-center justify-center text-lg font-medium text-gray-500">
          No Items Found!
        </div>
      )}
    </div>
  );
};


export default DishList;
