"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";

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;
}

export default function ServiceCard({
  id,
  imageUrl,
  title,
  description,
  price,
  time,
  location,
  slug,
  distance,
  createdAt,
  creator,
  isWishlisted = false,
}: 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,
    ]
  );

  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 flex sm:block h-full dark:bg-card dark:border-darkborder">
      <div className="relative min-w-36 sm:min-w-0 overflow-hidden rounded-lg sm:rounded-none max-sm:max-w-16">
        <img
          src={finalImageUrl}
          alt={title}
          width={407}
          height={149}
          className="!w-full !h-full md:!h-[149px] max-md:!h-[149px] object-cover"
          onError={(e) => {
            if (!e.currentTarget.src.endsWith("/products/product-01.png")) {
              e.currentTarget.src = "/products/product-01.png";
            }
          }}
        />
        <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">
        <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>
            3
          </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">
            <Link
              href={`/service/${slug}`}
              className="stretched-link line-clamp-2"
            >
              {title}
            </Link>
          </h3>
          {description.trim().length > 0 && <p className="text-xs text-neutrals500 mt-1 line-clamp-3 dark:text-neutrals400">
            {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>{time}</span>
          <span>{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>
            3
          </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 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>
  );
}
