"use client";
import { useEffect, useState, useCallback } from "react";
import Image from "next/image";
import Link from "next/link";
import { IoLocationOutline } from "react-icons/io5";
import { useAppDispatch, useAppSelector } from "@/app/store/hooks";
import {
  addToWishlistThunk,
  removeFromWishlistThunk,
  selectWishlistProductIds,
} from "@/app/store/slices/wishlistSlice";
import { RootState } from "@/app/store/store";
import { toast } from "react-toastify";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { checkAuthErrorGet } from "@/lib/checkAuthError";
import { useLocale } from "next-intl";
import { getImageUrl } from "@/hooks/useImageUrl";
import { getDateAndTimeWithLocale } from "@/lib/formTypes";
import { AttributeKeys, OtherAttribute } from "../../types/common-types";
import {
  getLocation,
  getSavedLocation,
  getUserLocation,
  saveLocation,
} from "@/lib/utils/location";

interface ProductCreator {
  id: string;
  name: string;
  email: string;
  profileImage?: string | null;
}

interface ProductCardProps {
  id: string;
  imageUrl: string;
  title: string;
  description: string;
  price: string;
  time: string;
  location: string;
  slug: string;
  distance?: number;
  createdAt?: string;
  creator?: ProductCreator | null;
  isWishlisted?: boolean;
  totalNumberOfViews?: number;
  isOtherAttribute?: boolean;
  otherAttribute?:
  | OtherAttribute<"mobile_number">
  | OtherAttribute<"vehicle_number_plate">;
  productType?: "product" | AttributeKeys;
}

export default function ProductCard({
  id,
  imageUrl,
  title,
  description,
  price,
  time,
  location,
  slug,
  distance,
  createdAt,
  creator,
  isWishlisted = false,
  totalNumberOfViews = 0,
  isOtherAttribute = false,
  otherAttribute,
  productType = "product",
}: ProductCardProps) {
  const t = useTranslations();
  const locale = useLocale();
  const { user } = useAppSelector((state: RootState) => state.auth);
  const router = useRouter();
  useEffect(() => {
    if (imageUrl) {
      const img = new window.Image();
      img.src = getImageUrl(imageUrl);
    }
  }, [id, title, imageUrl]);

  const finalImageUrl = getImageUrl(imageUrl);

  const [imageError, setImageError] = useState(false);
  const dispatch = useAppDispatch();
  const wishlistProductIds = useAppSelector(selectWishlistProductIds);

  // Ensure we always have an array, even if the selector returns undefined
  const safeWishlistIds = Array.isArray(wishlistProductIds)
    ? wishlistProductIds
    : [];
  const isInWishlist = safeWishlistIds.includes(id);

  const [isToggling, setIsToggling] = useState(false);

  useEffect(() => {
    if (isWishlisted && !isInWishlist && user?.token) {
      dispatch(
        addToWishlistThunk({
          productId: id,
          token: user.token,
        }),
      );
    }
  }, [isWishlisted, isInWishlist, id, user?.token, dispatch]);

  const handleWishlistToggle = useCallback(
    async (e: React.MouseEvent) => {
      e.preventDefault();
      e.stopPropagation();

      if (isToggling) return;
      setIsToggling(true);

      try {
        const isRemoving = isInWishlist || isWishlisted;
        const thunk = isRemoving ? removeFromWishlistThunk : addToWishlistThunk;

        const result = await dispatch(
          thunk({
            productId: id,
            token: user?.token || null,
          }),
        );

        if (result.meta.requestStatus === "fulfilled") {
          const successKey = isRemoving
            ? "wishlist_page.wishlist_remove_success"
            : "wishlist_page.wishlist_add_success";
          toast.success(t(successKey));
        } else if (result.meta.requestStatus === "rejected") {
          if (user?.token) {
            const payload = result.payload as any;
            if (payload?.isAuthError && payload?.status === 401) {
              if (checkAuthErrorGet(payload.originalError, dispatch, router))
                return;
            }
          }

          const errorKey = isRemoving
            ? "wishlist_page.wishlist_remove_error"
            : "wishlist_page.wishlist_add_error";
          toast.error(t(errorKey));
        }
      } catch (error: any) {
        if (user?.token && checkAuthErrorGet(error, dispatch, router)) return;
        toast.error(t("validation.error_msg"));
      } finally {
        setIsToggling(false);
      }
    },
    [
      dispatch,
      id,
      isInWishlist,
      isWishlisted,
      isToggling,
      user?.token,
      title,
      description,
      price,
      imageUrl,
      distance,
      createdAt,
      creator,
    ],
  );

  // THIS IS OPERATOR CARD
  // if (isOtherAttribute && productType === "mobile_number") {
  //   const mobileAttr = otherAttribute as OtherAttribute<"mobile_number">;
  //   return (
  //     <div className="bg-white rounded-[15px_15px_8px_8px] overflow-hidden border border-primary200 sm:border-neutrals100 hover:border-primary200 hover:shadow-Shadow3 transition-all relative pt-0 pb-12 sm:p-0 sm:block h-full dark:bg-card dark:border-darkborder max-md:rounded-[24px]">
  //       <div className="w-full relative">
  //         <img
  //           src={getImageUrl(imageUrl)}
  //           alt={title}
  //           className="w-full h-[150px] object-cover object-top max-sm:h-[180px]"
  //         />

  //         <button
  //           className="absolute top-2.5 right-2.5 sm:right-2.5 bg-white bg-opacity-50 rounded-lg flex items-center justify-center h-8 w-8 z-20 dark:bg-darkbg dark:bg-opacity-40"
  //           onClick={handleWishlistToggle}
  //           disabled={isToggling}
  //           aria-label={
  //             isInWishlist || isWishlisted
  //               ? t("product_page.remove_from_wishlist")
  //               : t("product_page.add_to_wishlist")
  //           }
  //         >
  //           <svg
  //             width="20"
  //             height="19"
  //             viewBox="0 0 20 19"
  //             fill="none"
  //             xmlns="http://www.w3.org/2000/svg"
  //           >
  //             <path
  //               d={
  //                 isInWishlist || isWishlisted
  //                   ? "M14.5 0C12.76 0 11.09 0.81 10 2.09C8.91 0.81 7.24 0 5.5 0C2.42 0 0 2.42 0 5.5C0 9.28 3.4 12.36 8.55 17.04L10 18.35L11.45 17.03C16.6 12.36 20 9.28 20 5.5C20 2.42 17.58 0 14.5 0Z"
  //                   : "M14.5 0C12.76 0 11.09 0.81 10 2.09C8.91 0.81 7.24 0 5.5 0C2.42 0 0 2.42 0 5.5C0 9.28 3.4 12.36 8.55 17.04L10 18.35L11.45 17.03C16.6 12.36 20 9.28 20 5.5C20 2.42 17.58 0 14.5 0ZM10.1 15.55L10 15.65L9.9 15.55C5.14 11.24 2 8.39 2 5.5C2 3.5 3.5 2 5.5 2C7.04 2 8.54 2.99 9.07 4.36H10.94C11.46 2.99 12.96 2 14.5 2C16.5 2 18 3.5 18 5.5C18 8.39 14.86 11.24 10.1 15.55Z"
  //               }
  //               fill="#04196C"
  //               className="dark:fill-primary400"
  //             />
  //           </svg>
  //         </button>
  //       </div>
  //       <div className="ps-2 sm:pt-2 sm:px-4 sm:pb-11 max-sm:px-2">
  //         <div className="hidden sm:flex items-center justify-between mb-2.5">
  //           <div className="flex items-center gap-1 text-sm text-primary800 dark:text-neutrals100">
  //             <div className="w-6 h-6 min-w-6 bg-neutrals50 rounded flex items-center justify-center">
  //               <Image
  //                 src="/noto_fire.svg"
  //                 alt="noto_fire"
  //                 width={18}
  //                 height={18}
  //                 priority
  //               />
  //             </div>
  //             <span>{totalNumberOfViews}</span>
  //           </div>
  //           <div className="text-neutrals900 text-sm flex items-center gap-1 dark:text-neutrals100">
  //             {creator?.profileImage && !imageError ? (
  //               <div className="rounded-full h-5 w-5 overflow-hidden">
  //                 <img
  //                   src={getImageUrl(creator.profileImage, true)}
  //                   alt={creator.name || t("product_page.user")}
  //                   width={20}
  //                   height={20}
  //                   className="w-full h-full object-cover"
  //                   onError={() => setImageError(true)}
  //                 />
  //               </div>
  //             ) : (
  //               <div className="rounded-full h-5 w-5 flex items-center justify-center text-xs font-medium text-white bg-primary400 dark:bg-primary400 uppercase">
  //                 {creator?.name?.charAt(0) || "U"}
  //               </div>
  //             )}
  //             <span>{creator?.name || "User"}</span>
  //           </div>
  //         </div>
  //         <h3 className="font-semibold text-sm text-neutrals800 dark:text-white max-sm:mt-2">
  //           <Link
  //             href={`/products/${slug}`}
  //             className="stretched-link line-clamp-2"
  //           >
  //             {title}
  //           </Link>
  //         </h3>
  //         <p className="text-xs text-neutrals500 mt-1 line-clamp-3 dark:text-neutrals400 test">
  //           {description}
  //         </p>
  //         <p className="text-primary500 font-bold mt-1 dark:text-primary400">
  //           {process.env.NEXT_PUBLIC_CURRENCY_TYPE} {price}
  //         </p>
  //         <div className="flex justify-between text-[12px] sm:text-xs text-neutrals800 mt-2.5 pb-2.5 dark:text-neutrals400">
  //           <span>{getDateAndTimeWithLocale(time, locale).date}</span>
  //           <span className="line-clamp-1 max-w-36">{location}</span>
  //         </div>
  //         <div className="absolute bottom-2.5 left-2.5 w-[calc(100%-20px)] sm:w-[calc(100%-32px)] sm:bottom-3 sm:left-4 flex items-center justify-between border-t border-neutrals100 pt-1.5 dark:border-darkborder">
  //           <div className="flex sm:hidden items-center gap-1 text-sm text-neutrals800">
  //             <div className="w-6 h-6 min-w-6 bg-neutrals50 rounded flex items-center justify-center">
  //               <Image
  //                 src="/noto_fire.svg"
  //                 alt="noto_fire"
  //                 width={18}
  //                 height={18}
  //                 priority
  //               />
  //             </div>
  //             <span className="dark:text-neutrals50">20</span>
  //           </div>
  //           <div className="flex items-center gap-1 text-sm text-neutrals800 dark:text-neutrals400">
  //             <div className="w-6 h-6 min-w-6 bg-neutrals50 rounded flex items-center justify-center dark:bg-darkbg">
  //               <IoLocationOutline />
  //             </div>
  //             {distance
  //               ? `${distance} ${t("product_page.km_away")}`
  //               : t("product_page.nearby")}
  //           </div>
  //         </div>
  //       </div>
  //     </div>
  //   );
  // }

  // THIS IS VEHICLE CARD
  if (isOtherAttribute && productType === "vehicle_number_plate") {
    const vehicleAttr =
      otherAttribute as OtherAttribute<"vehicle_number_plate">;
    return (
      <div className="bg-white rounded-[15px_15px_8px_8px] overflow-hidden border border-primary200 sm:border-neutrals100 hover:border-primary200 hover:shadow-Shadow3 transition-all relative pt-0 pb-12 p-2.5 sm:p-0 sm:block h-full dark:bg-card dark:border-darkborder">
        <div className="w-full relative p-1">
          <img
            src={getImageUrl(imageUrl)}
            onError={(e) => {
              e.currentTarget.onerror = null;
              e.currentTarget.src = "/default.jpg";
            }}
            alt={title}
            className="w-full h-[215px] object-contain object-center max-sm:h-[180px]"
          />
          <button
            className="absolute top-2.5 right-2.5 sm:right-2.5 bg-white bg-opacity-50 rounded-lg flex items-center justify-center h-8 w-8 z-20 dark:bg-darkbg dark:bg-opacity-40"
            onClick={handleWishlistToggle}
            disabled={isToggling}
            aria-label={
              isInWishlist || isWishlisted
                ? t("product_page.remove_from_wishlist")
                : t("product_page.add_to_wishlist")
            }
          >
            <svg
              width="20"
              height="19"
              viewBox="0 0 20 19"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                d={
                  isInWishlist || isWishlisted
                    ? "M14.5 0C12.76 0 11.09 0.81 10 2.09C8.91 0.81 7.24 0 5.5 0C2.42 0 0 2.42 0 5.5C0 9.28 3.4 12.36 8.55 17.04L10 18.35L11.45 17.03C16.6 12.36 20 9.28 20 5.5C20 2.42 17.58 0 14.5 0Z"
                    : "M14.5 0C12.76 0 11.09 0.81 10 2.09C8.91 0.81 7.24 0 5.5 0C2.42 0 0 2.42 0 5.5C0 9.28 3.4 12.36 8.55 17.04L10 18.35L11.45 17.03C16.6 12.36 20 9.28 20 5.5C20 2.42 17.58 0 14.5 0ZM10.1 15.55L10 15.65L9.9 15.55C5.14 11.24 2 8.39 2 5.5C2 3.5 3.5 2 5.5 2C7.04 2 8.54 2.99 9.07 4.36H10.94C11.46 2.99 12.96 2 14.5 2C16.5 2 18 3.5 18 5.5C18 8.39 14.86 11.24 10.1 15.55Z"
                }
                fill="#04196C"
                className="dark:fill-primary400"
              />
            </svg>
          </button>
        </div>
        <div className="ps-2 sm:pt-2 sm:px-4 sm:pb-11 max-sm:px-2">
          <div className="hidden sm:flex items-center justify-between mb-2.5">
            <div className="flex items-center gap-1 text-sm text-primary800 dark:text-neutrals100">
              <div className="w-6 h-6 min-w-6 bg-neutrals50 rounded flex items-center justify-center">
                <Image
                  src="/noto_fire.svg"
                  alt="noto_fire"
                  width={18}
                  height={18}
                  priority
                />
              </div>
              <span>{totalNumberOfViews}</span>
            </div>
            <div className="text-neutrals900 text-sm flex items-center gap-1 dark:text-neutrals100">
              {creator?.profileImage && !imageError ? (
                <div className="rounded-full h-5 w-5 overflow-hidden">
                  <img
                    src={getImageUrl(creator?.profileImage, true)}
                    alt={creator.name || t("product_page.user")}
                    width={20}
                    height={20}
                    className="w-full h-full object-cover"
                    onError={() => setImageError(true)}
                  />
                </div>
              ) : (
                <div className="rounded-full h-5 w-5 flex items-center justify-center text-xs font-medium text-white bg-primary400 dark:bg-primary400 uppercase">
                  {creator?.name?.charAt(0) || "U"}
                </div>
              )}
              <span>{creator?.name || "User"}</span>
            </div>
          </div>
          <h3 className="font-semibold text-sm text-neutrals800 dark:text-white max-sm:mt-2">
            <Link
              href={`/products/${slug}`}
              className="stretched-link line-clamp-2"
            >
              {title}
            </Link>
          </h3>
          <p className="text-xs text-neutrals500 mt-1 line-clamp-3 dark:text-neutrals400 test">
            {description}
          </p>
          <p className="text-primary500 font-bold mt-1 dark:text-primary400">
            {process.env.NEXT_PUBLIC_CURRENCY_TYPE} {price}
          </p>
          <div className="flex justify-between text-[12px] sm:text-xs text-neutrals800 mt-2.5 pb-2.5 dark:text-neutrals400">
            <span>{getDateAndTimeWithLocale(time, locale).date}</span>
            <span className="line-clamp-1 max-w-36">{location || t("home_page.location_not_specified")}</span>
          </div>
          <div className="absolute bottom-2.5 left-2.5 w-[calc(100%-20px)] sm:w-[calc(100%-32px)] sm:bottom-3 sm:left-4 flex items-center justify-between border-t border-neutrals100 pt-1.5 dark:border-darkborder">
            <div className="flex sm:hidden items-center gap-1 text-sm text-neutrals800">
              <div className="w-6 h-6 min-w-6 bg-neutrals50 rounded flex items-center justify-center">
                <Image
                  src="/noto_fire.svg"
                  alt="noto_fire"
                  width={18}
                  height={18}
                  priority
                />
              </div>
              <span className="dark:text-neutrals50">20</span>
            </div>
            <div className="flex items-center gap-1 text-sm text-neutrals800 dark:text-neutrals400">
              <div className="w-6 h-6 min-w-6 bg-neutrals50 rounded flex items-center justify-center dark:bg-darkbg">
                <IoLocationOutline />
              </div>
              {distance
                ? `${distance} ${t("product_page.km_away")}`
                : t("product_page.nearby")}

              {getSavedLocation() === null && (
                <span
                  className="cursor-pointer text-primary500 dark:text-primary100"
                  onClick={() => {
                    getUserLocation();
                    router.refresh();
                  }}
                >
                  {t("enable_your_location")}
                </span>
              )}
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-white rounded-lg overflow-hidden border border-primary200 sm:border-neutrals100 hover:border-primary200 hover:shadow-Shadow3 transition-all relative p-2.5 pb-12 sm:p-0 sm:block h-full dark:bg-card dark:border-darkborder max-md:rounded-[10px]">
      <div className="relative min-w-36 sm:min-w-0 overflow-hidden rounded-lg sm:rounded-none max-sm:max-w-full">
        <img
          src={finalImageUrl}
          alt={title}
          width={407}
          height={149}
          className="!w-full !h-[214px] object-cover max-lg:!h-[248px] max-[1600px]:!h-[187px] max-[1539px]:!h-[193px] max-[1535px]:!h-[224px] max-[1441px]:!h-[200px] max-[1325px]:!h-[199px] max-[1279px]:!h-[318px] max-[1200px]:!h-[260px] max-[991px]:!h-[240px] max-[945px]:!h-[222px] max-[850px]:!h-[200px] max-[800px]:!h-[185px] max-md:!h-[290px] max-[728px]:!h-[260px] max-[660px]:!h-[230px] max-[600px]:!h-[430px] max-sm:!h-[360px] max-[490px]:!h-[330px] max-[450px]:!h-[300px] max-[415px]:!h-[280px] max-[390px]:!h-[251px] max-[370px]:!h-[210px]"
          onError={(e) => {
            e.currentTarget.onerror = null;
            e.currentTarget.src = "/default.jpg";
          }}
        />
        <button
          className="absolute top-2.5 right-2.5 sm:right-2.5 bg-white bg-opacity-50 rounded-lg flex items-center justify-center h-8 w-8 z-20 dark:bg-darkbg dark:bg-opacity-40"
          onClick={handleWishlistToggle}
          disabled={isToggling}
          aria-label={
            isInWishlist || isWishlisted
              ? t("product_page.remove_from_wishlist")
              : t("product_page.add_to_wishlist")
          }
        >
          <svg
            width="20"
            height="19"
            viewBox="0 0 20 19"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              d={
                isInWishlist || isWishlisted
                  ? "M14.5 0C12.76 0 11.09 0.81 10 2.09C8.91 0.81 7.24 0 5.5 0C2.42 0 0 2.42 0 5.5C0 9.28 3.4 12.36 8.55 17.04L10 18.35L11.45 17.03C16.6 12.36 20 9.28 20 5.5C20 2.42 17.58 0 14.5 0Z"
                  : "M14.5 0C12.76 0 11.09 0.81 10 2.09C8.91 0.81 7.24 0 5.5 0C2.42 0 0 2.42 0 5.5C0 9.28 3.4 12.36 8.55 17.04L10 18.35L11.45 17.03C16.6 12.36 20 9.28 20 5.5C20 2.42 17.58 0 14.5 0ZM10.1 15.55L10 15.65L9.9 15.55C5.14 11.24 2 8.39 2 5.5C2 3.5 3.5 2 5.5 2C7.04 2 8.54 2.99 9.07 4.36H10.94C11.46 2.99 12.96 2 14.5 2C16.5 2 18 3.5 18 5.5C18 8.39 14.86 11.24 10.1 15.55Z"
              }
              fill="#04196C"
              className="dark:fill-primary400"
            />
          </svg>
        </button>
      </div>
      <div className="ps-2 sm:pt-2 sm:px-4 sm:pb-11 max-sm:px-2">
        <div className="hidden sm:flex items-center justify-between mb-2.5">
          <div className="flex items-center gap-1 text-sm text-primary800 dark:text-neutrals100">
            <div className="w-6 h-6 min-w-6 bg-neutrals50 rounded flex items-center justify-center">
              <Image
                src="/noto_fire.svg"
                alt="noto_fire"
                width={18}
                height={18}
                priority
              />
            </div>
            <span>{totalNumberOfViews}</span>
          </div>
          <div className="text-neutrals900 text-sm flex items-center gap-1 dark:text-neutrals100">
            {creator?.profileImage && !imageError ? (
              <div className="rounded-full h-5 w-5 overflow-hidden">
                <img
                  src={getImageUrl(creator?.profileImage, true)}
                  alt={creator.name || t("product_page.user")}
                  width={20}
                  height={20}
                  className="w-full h-full object-cover"
                  onError={() => setImageError(true)}
                />
              </div>
            ) : (
              <div className="rounded-full h-5 w-5 flex items-center justify-center text-xs font-medium text-white bg-primary400 dark:bg-primary400 uppercase">
                {creator?.name?.charAt(0) || "U"}
              </div>
            )}
            <span>{creator?.name || "User"}</span>
          </div>
        </div>
        <h3 className="font-semibold text-sm text-neutrals800 dark:text-white max-sm:mt-2">
          <Link
            href={`/products/${slug}`}
            className="stretched-link line-clamp-2"
          >
            {title}
          </Link>
        </h3>
        {typeof description === "string" && description.trim().length > 0 && (
          <p className="text-xs text-neutrals500 mt-1 line-clamp-3 dark:text-neutrals400 test">
            {description}
          </p>
        )}
        <p className="text-primary500 font-bold mt-1 dark:text-primary400">
          {process.env.NEXT_PUBLIC_CURRENCY_TYPE} {price}
        </p>
        <div className="flex justify-between text-[12px] sm:text-xs text-neutrals800 mt-2.5 pb-2.5 dark:text-neutrals400">
          <span>{getDateAndTimeWithLocale(time, locale).date}</span>
          <span className="line-clamp-1 max-w-36">{location || t("home_page.location_not_specified")}</span>
        </div>
        <div className="absolute bottom-2.5 left-2.5 w-[calc(100%-20px)] sm:w-[calc(100%-32px)] sm:bottom-3 sm:left-4 flex items-center justify-between border-t border-neutrals100 pt-1.5 dark:border-darkborder">
          <div className="flex sm:hidden items-center gap-1 text-sm text-neutrals800">
            <div className="w-6 h-6 min-w-6 bg-neutrals50 rounded flex items-center justify-center">
              <Image
                src="/noto_fire.svg"
                alt="noto_fire"
                width={18}
                height={18}
                priority
              />
            </div>
            <span className="dark:text-neutrals50">{totalNumberOfViews}</span>
          </div>
          <div className="flex items-center gap-1 text-sm text-neutrals800 dark:text-neutrals400">
            <div className="w-6 h-6 min-w-6 bg-neutrals50 rounded flex items-center justify-center dark:bg-darkbg">
              <IoLocationOutline />
            </div>
            {distance
              ? `${distance} ${t("product_page.km_away")}`
              : t("product_page.nearby")}

            {getSavedLocation() === null && (
              <span
                className="cursor-pointer text-primary500 dark:text-primary100"
                onClick={() => {
                  getUserLocation();
                  router.refresh();
                }}
              >
                {t("enable_your_location")}
              </span>
            )}
          </div>

          <div className="text-neutrals900 sm:hidden text-sm flex items-center gap-1 dark:text-neutrals100">
            {creator?.profileImage && !imageError ? (
              <div className="rounded-full h-5 w-5 overflow-hidden">
                <img
                  src={getImageUrl(creator.profileImage, true)}
                  alt={creator.name || t("product_page.user")}
                  width={20}
                  height={20}
                  className="w-full h-full object-cover"
                  onError={() => setImageError(true)}
                />
              </div>
            ) : (
              <div className="rounded-full h-5 w-5 bg-primary100 flex items-center justify-center text-xs font-medium text-white bg-primary400 dark:bg-primary400">
                {creator?.name?.charAt(0) || "U"}
              </div>
            )}
            <span className="line-clamp-1">
              {creator?.name || t("product_page.user")}
            </span>
          </div>
        </div>
      </div>
    </div>
  );
}
