"use client";

import { useCart } from "@/app/[name]/(Main)/cart/hook/useCart";
import MinusIcon from "@/components/icons/MinusIcon";
import PlusIcon from "@/components/icons/PlusIcon";
import { toast, toastLoginRequired } from "@/components/Toast";
import { getToken } from "@/lib/api/func";
import { ef } from "@/lib/helpers/utfNumbers";
import { glassSurface, glassSurfaceCard, glassSurfaceFlat } from "@/lib/styles/glassSurface";
import { motion } from "framer-motion";
import { ArrowLeft, Clock, Cup, Heart, TruckTick } from "iconsax-react";
import { useParams, useRouter } from "next/navigation";
import { useEffect, useMemo, useRef, useState } from "react";
import { useGetProfile } from "../../(Profile)/profile/hooks/userProfileData";
import { useGetAbout } from "../about/hooks/useAboutData";
import { useGetFood, useToggleFavorite } from "./hooks/useFoodData";
import FoodReviewsSection from "./components/FoodReviewsSection";

type Props = object;

function FoodPage({}: Props) {
  const { id, name } = useParams();
  const router = useRouter();
  const { isSuccess } = useGetProfile();
  const { data: food, isLoading } = useGetFood(id as string);
  const { data: about } = useGetAbout();
  const { items, addToCart, removeFromCart } = useCart();
  const [isFavorite, setIsFavorite] = useState<boolean>(false);
  const { mutate: toggleFavorite } = useToggleFavorite();
  const imageRef = useRef<HTMLImageElement>(null);
  const foodId = food?.data?.id || (id as string);
  const quantity = useMemo(() => {
    const item = items?.[foodId];
    if (item && typeof item === "object" && "quantity" in item) {
      return item.quantity || 0;
    }
    return 0;
  }, [items, foodId]);

  const handleAddToCart = () => {
    if (!foodId || food?.data?.isAvailable === false) return;
    addToCart(foodId);
  };

  const handleRemoveFromCart = () => {
    if (foodId) {
      removeFromCart(foodId);
    }
  };

  const handleToggleFavorite = async () => {
    if (!foodId) return;

    const token = await getToken();
    if (!token || !isSuccess) {
      toastLoginRequired(() => router.push(`/${name}/auth`), "error");
      return;
    }

    // به‌روزرسانی خوش‌بینانه: تغییر state قبل از ارسال درخواست
    const previousFavorite = isFavorite;
    setIsFavorite(!isFavorite);

    toggleFavorite(foodId, {
      onSuccess: () => {
        // تایید تغییر در صورت موفقیت
      },
      onError: () => {
        // بازگرداندن به حالت قبلی در صورت خطا
        setIsFavorite(previousFavorite);
        toast("خطا در تغییر وضعیت علاقه‌مندی", "error");
      },
    });
  };

  useEffect(() => {
    if (food?.data?.isFavorite) {
      setIsFavorite(true);
    } else {
      setIsFavorite(false);
    }
  }, [food?.data?.isFavorite]);

  useEffect(() => {
    const scrollEl = document.querySelector("main");
    const imageEl = imageRef.current;
    if (!scrollEl || !imageEl) return;

    const desktopQuery = window.matchMedia("(min-width: 1024px)");
    const MAX_SCALE = 1.6;
    const MIN_SCALE = 1.0;

    const applyParallax = () => {
      if (desktopQuery.matches) {
        imageEl.style.transform = "";
        return;
      }
      const scrollRange = imageEl.parentElement?.offsetHeight ?? 320;
      const progress = Math.min(1, Math.max(0, scrollEl.scrollTop / scrollRange));
      const scale = MIN_SCALE + (MAX_SCALE - MIN_SCALE) * progress;
      imageEl.style.transform = `scale(${scale})`;
    };

    scrollEl.addEventListener("scroll", applyParallax, { passive: true });
    desktopQuery.addEventListener("change", applyParallax);
    window.addEventListener("resize", applyParallax);
    applyParallax();

    return () => {
      scrollEl.removeEventListener("scroll", applyParallax);
      desktopQuery.removeEventListener("change", applyParallax);
      window.removeEventListener("resize", applyParallax);
      imageEl.style.transform = "";
    };
  }, [food?.data?.id]);

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <p className="text-disabled-text">در حال بارگذاری...</p>
      </div>
    );
  }

  if (!food?.data) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <p className="text-disabled-text">غذا یافت نشد</p>
      </div>
    );
  }

  const foodData = food.data;
  const isAvailable = foodData.isAvailable !== false;
  const foodName = foodData.title || foodData.name || foodData.foodName || "";
  const foodImage =
    typeof foodData.image === "string"
      ? foodData.image
      : Array.isArray(foodData.images) && foodData.images.length > 0
        ? typeof foodData.images[0] === "string"
          ? foodData.images[0]
          : typeof foodData.images[0] === "object" && foodData.images[0] !== null && "url" in foodData.images[0]
            ? (foodData.images[0] as { url: string }).url
            : "/assets/images/no-image.png"
        : "/assets/images/no-image.png";
  const categoryName = foodData.category?.title;
  const prepareTime = foodData.prepareTime || 0;
  const price = foodData.price || 0;
  const content = Array.isArray(foodData.content) ? foodData.content.join("، ") : foodData.content || foodData.desc || "";

  const handleBackToMenu = () => {
    const urlParams = new URLSearchParams(window.location.search);
    const categoryParam = urlParams.get("category") || foodData.category?.id;
    if (categoryParam) {
      router.push(`/${name}?category=${categoryParam}`);
    } else {
      router.push(`/${name}`);
    }
  };

  return (
    <div className="not-lg:max-w-lg not-lg:place-self-center not-lg:w-full w-full flex flex-col gap-4 pt-6 lg:pt-8 pb-24 lg:pb-28">
      <div className="not-lg:flex not-lg:flex-col lg:grid lg:grid-cols-2 lg:min-h-[420px] lg:max-h-[480px] lg:rounded-2xl lg:overflow-hidden shrink-0">
        <div
          className={glassSurface(
            "relative w-full lg:h-full min-h-0 rounded-2xl overflow-hidden lg:rounded-r-none lg:order-1 lg:bg-transparent! lg:border-0! lg:shadow-none! lg:[backdrop-filter:none] not-lg:sticky not-lg:top-6 not-lg:z-0 not-lg:h-[min(50vh,400px)] not-lg:min-h-[280px] not-lg:rounded-b-none",
          )}
        >
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img
          ref={imageRef}
          className="lg:object-cover not-lg:object-contain lg:h-full object-cover object-top bg-[#F2F2F9] w-full not-lg:absolute not-lg:inset-0 not-lg:h-full not-lg:origin-top not-lg:will-change-transform"
          src={foodImage}
          alt={foodName}
          onError={(event) => {
            event.currentTarget.src = "/assets/images/no-image.png";
          }}
        />
        <div className="absolute top-4 left-0 z-10 pe-5.5 ps-7 w-full inline-flex justify-between items-center">
          <div className={glassSurfaceFlat("whitespace-nowrap rounded-[34px] py-1.5 px-4 w-min text-xs text-disabled2 dark:text-disabled-text font-bold")}>{categoryName || "-"}</div>
          <button onClick={handleBackToMenu} className={glassSurfaceFlat("p-2 rounded-full")}>
            <ArrowLeft size={18} className="stroke-primary dark:stroke-foreground" />
          </button>
        </div>
      </div>

      <div
        className={glassSurfaceCard(
          "relative bg-white/60! px-6 pt-6 pb-7.5 lg:flex lg:flex-col lg:h-full lg:min-h-0 w-full overflow-hidden not-lg:z-10 not-lg:-mt-12 not-lg:rounded-t-3xl not-lg:shadow-[0_-10px_30px_rgba(0,0,0,0.08)] lg:rounded-l-none lg:overflow-y-auto rounded-3xl",
        )}
      >
        <div className="w-full inline-flex justify-between items-center shrink-0">
          <h5 className="text-base font-bold">{foodName}</h5>
          <button onClick={handleToggleFavorite} className="p-2 bg-[#EAECF0] dark:bg-neutral-600 rounded-lg">
            <Heart variant={isFavorite ? "Bold" : "Outline"} size={24} color="currentColor" className={isFavorite ? "fill-primary dark:fill-foreground" : ""} />
          </button>
        </div>

        <div className="mt-4 lg:mt-0 lg:flex-1 lg:flex lg:flex-col lg:justify-center lg:min-h-0 lg:overflow-y-auto">
          <div className="text-xs">
            <div className="flex items-center gap-1">
              <Clock size={14} className="stroke-disabled-text" />
              <span className="text-disabled-text">زمان پخت و آماده سازی: {prepareTime > 0 ? `${ef(String(prepareTime))} دقیقه` : "-"}</span>
            </div>
            <div className="flex items-center gap-2 mt-2">
              <Cup size={14} className="stroke-disabled-text" />
              <span className="text-disabled-text flex gap-1">
                {about?.data?.plan === "base" ? (
                  <>
                    <div>۰</div>
                    <span>امتیاز برای هر بار خرید</span>
                  </>
                ) : about?.data?.score?.purchaseScore && about?.data?.score?.purchaseAmount ? (
                  <>
                    <div>{ef(Math.round(foodData?.price * (Number(about.data.score.purchaseScore) / Number(about.data.score.purchaseAmount))).toLocaleString("en-US"))}</div>
                    <span>امتیاز برای هر بار خرید</span>
                  </>
                ) : (
                  <span>-</span>
                )}
              </span>
            </div>
            <div className="flex items-center gap-2 mt-2">
              <TruckTick size={14} className="stroke-disabled-text" />
              <span className="text-disabled-text">{foodData.pickupServe ? "ارسال با پیک" : "-"}</span>
            </div>
          </div>

          <div className="mt-7 text-xs">
            <p className="font-bold">محتویات:</p>
            <p className="mt-2 leading-6">{content || "-"}</p>
          </div>
        </div>

        <div className="mt-12 lg:mt-0 shrink-0 flex justify-between items-center">
          <span dir="ltr">{ef(price.toLocaleString("en-US"))} T</span>
          <motion.div
            whileTap={isAvailable ? { scale: 1.05 } : undefined}
            className="bg-background pattern-secondary-bg active:drop-shadow-xs max-w-[115px] rounded-md w-full h-8 inline-flex p-1 justify-between items-center gap-2 relative overflow-hidden"
          >
            {quantity <= 0 ? (
              <button onClick={handleAddToCart} disabled={!isAvailable} className="inline-flex w-full justify-center items-center gap-2 disabled:pointer-events-none">
                {isAvailable && <PlusIcon />}
                <div className="text-sm2 pt-0.5 font-normal text-foreground">{isAvailable ? "افزودن" : "عدم موجودی"}</div>
              </button>
            ) : (
              <>
                <button
                  onClick={handleAddToCart}
                  disabled={!isAvailable}
                  className={glassSurfaceFlat("hover:brightness-95 active:brightness-90 rounded-sm p-2 transition-all disabled:pointer-events-none")}
                >
                  <PlusIcon className="text-foreground" />
                </button>
                <motion.div key={quantity} initial={{ scale: 1 }} animate={{ scale: [1.2, 0.95, 1] }} transition={{ duration: 0.3 }} className="text-sm2 pt-0.5 font-semibold">
                  {quantity}
                </motion.div>
                <button onClick={handleRemoveFromCart} className={glassSurfaceFlat("hover:brightness-95 active:brightness-90 rounded-sm p-2 transition-all")}>
                  <MinusIcon className="text-foreground" />
                </button>
              </>
            )}
          </motion.div>
        </div>
      </div>
      </div>

      <div className={glassSurfaceCard("w-full px-6 pt-6 pb-7.5 rounded-3xl bg-white/60! shrink-0")}>
        <FoodReviewsSection foodId={foodId} />
      </div>
    </div>
  );
}

export default FoodPage;
