"use client";

import { useState, useEffect, useRef, useCallback, MouseEvent } from "react";
import { useRouter } from "next/navigation";
import {
  Heart,
  ShoppingCart,
  Plus,
  Minus,
  AlertTriangle,
  Zap,
} from "lucide-react";
import { toast } from "sonner";
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
  type CarouselApi,
} from "@/components/ui/carousel";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { useToggleFavorite, useIsFavorite } from "@/lib/hooks";
import {
  useAddToCart,
  useUpdateCartItemQuantity,
  useRemoveFromCart,
  useCart,
} from "@/features/cart/hooks/useCart";
import { useTranslations } from "next-intl";

type ProductCardProps = {
  id: number;
  name: string;
  price: number | null;
  oldPrice: number | null;
  struct_price_text: string;
  discount?: number | null;
  discount_text?: string | null;
  images: string[];
  labels?: { text: string; bg_color: string }[];
  price_color?: string;
  height?: number;
  width?: number;
  button?: boolean;
  stock?: number;
};

export default function ProductCard({
  id,
  name,
  price,
  oldPrice,
  struct_price_text,
  images,
  labels = [],
  price_color = "#0A0A0A",
  // height = 500,
  // width = 350,
  button = false,
  stock,
}: ProductCardProps) {
  const router = useRouter();
  const t = useTranslations();
  const { isFavorite, isLoading: isFavoriteLoading } = useIsFavorite(id);
  const { mutate: toggleFavorite, isPending: isFavoriteToggling } =
    useToggleFavorite();
  const addToCartMutation = useAddToCart();
  const updateCartMutation = useUpdateCartItemQuantity();
  const removeFromCartMutation = useRemoveFromCart();
  const { data: cartData, refetch: refetchCart } = useCart();

  const [api, setApi] = useState<CarouselApi>();
  const [current, setCurrent] = useState(0);
  const [localQuantity, setLocalQuantity] = useState(1);
  const [isSyncing, setIsSyncing] = useState(false);
  const [showStockModal, setShowStockModal] = useState(false);
  const [isHovered, setIsHovered] = useState(false);
  const [isInteracting, setIsInteracting] = useState(false);

  const debounceTimerRef = useRef<NodeJS.Timeout | undefined>(undefined);
  const isRequestInFlightRef = useRef<boolean>(false);
  const pendingQuantityRef = useRef<number | null>(null);

  const hasMultipleImages = images.length > 1;
  const cartItem = cartData?.data?.find((item: any) => item.product?.id === id);
  const isInCart = !!cartItem;
  const isOutOfStock = stock === 0;
  const availableStock = stock || 0;

  useEffect(() => {
    if (!api) return;
    setCurrent(api.selectedScrollSnap());
    const onSelect = () => setCurrent(api.selectedScrollSnap());
    api.on("select", onSelect);
    return () => {
      api.off("select", onSelect);
    };
  }, [api]);

  useEffect(() => {
    setLocalQuantity(cartItem?.product_quantity || 1);
  }, [cartItem]);

  const syncToServer = useCallback(
    async (quantity: number) => {
      if (isRequestInFlightRef.current) {
        pendingQuantityRef.current = quantity;
        return;
      }

      isRequestInFlightRef.current = true;
      setIsSyncing(true);

      try {
        if (quantity === 0) {
          await removeFromCartMutation.mutateAsync(id);
        } else {
          await updateCartMutation.mutateAsync({ productId: id, quantity });
        }
        await refetchCart();

        if (pendingQuantityRef.current !== null) {
          const nextQuantity = pendingQuantityRef.current;
          pendingQuantityRef.current = null;
          setTimeout(() => syncToServer(nextQuantity), 100);
        }
      } catch (error) {
        console.error("Sync failed:", error);
        setLocalQuantity(cartItem?.product_quantity || 1);
        toast.error("Failed to update quantity", {
          description: "Please try again",
        });
      } finally {
        isRequestInFlightRef.current = false;
        setIsSyncing(false);
      }
    },
    [id, updateCartMutation, cartItem, refetchCart],
  );

  useEffect(() => {
    if (!isInCart || localQuantity === (cartItem?.product_quantity || 1))
      return;

    if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current);

    debounceTimerRef.current = setTimeout(() => {
      syncToServer(localQuantity);
    }, 800);

    return () => {
      if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current);
    };
  }, [localQuantity, isInCart, cartItem, syncToServer]);

  const handleFavorite = useCallback(
    (e: MouseEvent<HTMLButtonElement>) => {
      e.preventDefault();
      e.stopPropagation();

      toggleFavorite(
        { productId: id, isFavorite },
        {
          onSuccess: (data) =>
            toast.success(
              data.wasAdded
                ? t("added_to_favorites")
                : t("removed_from_favorites"),
            ),
          onError: () => toast.error("Error. Try again"),
        },
      );
    },
    [id, isFavorite, toggleFavorite],
  );

  const handleAddToCart = useCallback(
    async (e: MouseEvent<HTMLButtonElement>) => {
      e.preventDefault();
      e.stopPropagation();

      if (localQuantity > availableStock) {
        setShowStockModal(true);
        return;
      }

      setIsSyncing(true);

      try {
        await addToCartMutation.mutateAsync({
          productId: id,
          quantity: localQuantity,
        });
        toast.success(t("added_to_cart"), {
          description: `${name} ${t("added_to_cart_description")}`,
        });
      } catch (error) {
        console.error("Add to cart error:", error);
        toast.error(t("add_to_cart_failed"));
      } finally {
        setIsSyncing(false);
      }
    },
    [id, name, localQuantity, availableStock, addToCartMutation],
  );

  const handleQuantityChange = useCallback(
    (e: MouseEvent<HTMLButtonElement>, delta: number) => {
      e.preventDefault();
      e.stopPropagation();

      const newQuantity = localQuantity + delta;

      if (newQuantity < 0) return;

      if (newQuantity > availableStock) {
        setShowStockModal(true);
        return;
      }

      setLocalQuantity(newQuantity);
    },
    [localQuantity, availableStock, setShowStockModal],
  );

  const handleCardClick = useCallback(
    (e: MouseEvent<HTMLDivElement>) => {
      const target = e.target as HTMLElement;

      if (
        target.closest("button") ||
        target.closest('[data-carousel-control="true"]') ||
        target.closest('[role="dialog"]')
      ) {
        e.preventDefault();
        e.stopPropagation();
        return;
      }

      e.preventDefault();
      router.push(`/product/${id}`);
    },
    [router, id],
  );

  const handleNavClick = (e: MouseEvent, action: () => void) => {
    e.preventDefault();
    e.stopPropagation();
    action();
  };

  return (
    <>
      <div
        onClick={handleCardClick}
        onMouseEnter={() => setIsHovered(true)}
        onMouseLeave={() => setIsHovered(false)}
        className="flex justify-center cursor-pointer group"
      >
        <Card
          className="relative gap-2 bg-white border border-gray-100 shadow-sm hover:shadow-xl transition-all duration-300 p-0 w-full overflow-hidden rounded-lg"
          // style={{ height, maxWidth: width }}
        >
          {/* Image Section */}
          <div className="relative w-full aspect-square bg-gradient-to-br from-gray-50 to-gray-100 overflow-hidden">
            <Carousel
              opts={{ align: "start", loop: true, watchDrag: true }}
              setApi={setApi}
              className="w-full h-full"
              onPointerDown={() => setIsInteracting(true)}
              onPointerUp={() => setIsInteracting(false)}
              onPointerCancel={() => setIsInteracting(false)}
            >
              <CarouselContent className="h-full ml-0">
                {images.map((image, idx) => (
                  <CarouselItem key={idx} className="h-full pl-0">
                    <div className="w-full h-full flex items-center justify-center p-1 md:p-2">
                      <img
                        src={image}
                        alt={`${name} - ${idx + 1}`}
                        className={`max-w-full max-h-full object-contain rounded-t-sm transition-transform duration-500 ${
                          isHovered ? "scale-105" : "scale-100"
                        }`}
                        draggable="false"
                      />
                    </div>
                  </CarouselItem>
                ))}
              </CarouselContent>

              {hasMultipleImages && (
                <>
                  <CarouselPrevious
                    data-carousel-control="true"
                    className="absolute cursor-pointer left-3 opacity-0 group-hover:opacity-100 transition-all duration-300 z-20 h-9 w-9 bg-white/95 hover:bg-white border-0 shadow-lg"
                    onClick={(e) => handleNavClick(e, () => api?.scrollPrev())}
                  />
                  <CarouselNext
                    data-carousel-control="true"
                    className="absolute cursor-pointer right-3 opacity-0 group-hover:opacity-100 transition-all duration-300 z-20 h-9 w-9 bg-white/95 hover:bg-white border-0 shadow-lg"
                    onClick={(e) => handleNavClick(e, () => api?.scrollNext())}
                  />
                </>
              )}
            </Carousel>

            {/* Image Dots */}
            {hasMultipleImages && (
              <div
                className={`absolute bottom-3 left-1/2 -translate-x-1/2 z-10 flex gap-1.5 transition-opacity duration-300 ${
                  isHovered || isInteracting ? "opacity-100" : "opacity-0"
                }`}
              >
                {images.map((_, idx) => (
                  <button
                    key={idx}
                    data-carousel-control="true"
                    onClick={(e) => handleNavClick(e, () => api?.scrollTo(idx))}
                    className={`h-1.5 rounded-full transition-all duration-300 ${
                      idx === current
                        ? "w-8 bg-gray-900"
                        : "w-1.5 bg-gray-400 hover:bg-gray-600"
                    }`}
                  />
                ))}
              </div>
            )}

            {/* Labels */}
            {labels.length > 0 && (
              <div className="absolute top-3 left-3 flex flex-col gap-2 z-10">
                {labels.map((label, idx) => (
                  <Badge
                    key={idx}
                    className="text-white text-xs font-bold px-3 py-1 shadow-md backdrop-blur-sm"
                    style={{
                      backgroundColor: label.bg_color,
                      borderRadius: "12px",
                    }}
                  >
                    {label.text}
                  </Badge>
                ))}
              </div>
            )}

            {/* Out of Stock Overlay */}
            {isOutOfStock && (
              <div className="absolute inset-0 bg-white/80 backdrop-blur-sm flex items-center justify-center z-20">
                <div className="text-center">
                  <Badge
                    variant="secondary"
                    className="text-sm font-bold px-4 py-2 bg-gray-900 text-white"
                  >
                    {t("outOfStock")}
                  </Badge>
                </div>
              </div>
            )}
          </div>

          {/* Content Section */}
          <CardContent className="p-3 space-y-3">
            {/* Product Name */}
            <h3 className="text-gray-900 text-base font-semibold leading-tight line-clamp-2 min-h-[40px]">
              {name}
            </h3>

            {/* Price */}
            <div className="flex-col flex md:flex-row  items-baseline gap-1">
              <p
                className="text-xl font-bold tracking-tight"
                style={{ color: price_color }}
              >
                {struct_price_text.replace(/\.00\b/, "")}
              </p>
              {oldPrice && (
                <span className="text-sm text-gray-400 line-through ">
                  {oldPrice} TMT
                </span>
              )}  
            </div>
            <div className="flex gap-2 items-center">
              {/* Favorite Button  */}
              <Button
                onClick={handleFavorite}
                disabled={isFavoriteToggling || isFavoriteLoading}
                className=" w-7 h-7 md:w-9 cursor-pointer md:h-9 rounded-[10px] bg-white/95 backdrop-blur-sm  hover:bg-white hover:scale-110 transition-all duration-200 shadow-md disabled:opacity-50"
              >
                {isFavoriteLoading ? (
                  <div className="w-5 h-5 border-2 border-gray-200 border-t-gray-700 rounded-full animate-spin" />
                ) : (
                  <Heart
                    className={`w-5 h-5 transition-all duration-200 ${
                      isFavorite
                        ? "text-rose-500 fill-rose-500 scale-110"
                        : "text-gray-600 hover:text-rose-500"
                    }`}
                  />
                )}
              </Button>
              {/* Action Buttons */}
              {button && !isOutOfStock && (
                <div className="w-full">
                  {!isInCart ? (
                    <Button
                      onClick={handleAddToCart}
                      disabled={isSyncing}
                      className="w-full h-7 md:h-9  cursor-pointer rounded-[10px] bg-gradient-to-r from-gray-900 to-gray-800 hover:from-gray-800 hover:to-gray-700 text-white font-semibold shadow-md hover:shadow-lg transition-all duration-300 gap-2"
                    >
                      {isSyncing ? (
                        <div className="flex items-center gap-2">
                          <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                          <span>{t("adding")}</span>
                        </div>
                      ) : (
                        <>
                          <ShoppingCart className="h-5 w-5" />
                          {/* <span className="hidden md:flex">
                            {t("add_to_cart")}
                          </span> */}
                        </>
                      )}
                    </Button>
                  ) : (
                    <div className="flex items-center gap-2">
                      <Button
                        variant="outline"
                        size="icon"
                        onClick={(e) => handleQuantityChange(e, -1)}
                        disabled={isSyncing}
                        className="rounded-[10px] cursor-pointer h-7 md:h-9 w-7 md:w-9 border-2 border-gray-200 hover:border-gray-900 hover:bg-gray-50 transition-all duration-200 disabled:opacity-30"
                      >
                        <Minus className="h-5 w-5 text-gray-700" />
                      </Button>

                      <div className="flex-1 text-center font-bold text-sm md:text-lg border-2 border-gray-200 rounded-[10px] h-7 md:h-9 flex items-center justify-center bg-white relative">
                        {isSyncing && (
                          <div className="absolute inset-0 bg-white/80 rounded-xl flex items-center justify-center">
                            <div className="w-4 h-4 border-2 border-gray-300 border-t-gray-700 rounded-full animate-spin" />
                          </div>
                        )}
                        <span className={isSyncing ? "opacity-30" : ""}>
                          {localQuantity}
                        </span>
                      </div>

                      <Button
                        variant="outline"
                        size="icon"
                        onClick={(e) => handleQuantityChange(e, 1)}
                        disabled={isSyncing}
                        className={`rounded-[10px] cursor-pointer h-7 md:h-9 w-7 md:w-9 border-2 transition-all duration-200 disabled:opacity-30 ${
                          localQuantity >= availableStock
                            ? "opacity-60 border-gray-200"
                            : "border-gray-900 bg-gray-900 hover:bg-gray-800"
                        }`}
                      >
                        <Plus
                          className={`h-5 w-5 ${localQuantity >= availableStock ? "text-gray-900" : "text-white"}`}
                        />
                      </Button>
                    </div>
                  )}
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Stock Warning Modal */}
      <Dialog open={showStockModal} onOpenChange={setShowStockModal}>
        <DialogContent
          className="sm:max-w-md rounded-lg border-0 shadow-2xl"
          onClick={(e) => e.stopPropagation()}
        >
          <DialogHeader>
            <div className="flex items-center justify-center mb-6">
              <div className="rounded-full bg-amber-100 p-3">
                <AlertTriangle className="h-8 w-8 text-amber-600" />
              </div>
            </div>
            <DialogTitle className="text-center text-2xl font-bold text-gray-900">
              {t("stock_limit_title")}
            </DialogTitle>
            <DialogDescription className="text-center text-base pt-4 text-gray-600 leading-relaxed">
              {t("stock_limit_message", {
                product: name,
                stock: availableStock,
              })}
            </DialogDescription>
          </DialogHeader>
          <div className="flex justify-center mt-6">
            <Button
              onClick={(e) => {
                e.stopPropagation();
                setShowStockModal(false);
              }}
              className="w-full h-12 rounded-lg bg-gray-900 hover:bg-gray-800 text-white font-semibold shadow-md hover:shadow-lg transition-all duration-300"
            >
              {t("understood")}
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
}
