'use client';

import LogosProduct from '@/assets/product.png';
import { cart_api } from '@/features/cart/lib/api';
import { product_api } from '@/shared/config/api/product/api';
import {
  FavouriteProductRes,
  ProductListResult,
} from '@/shared/config/api/product/type';
import { BASE_URL } from '@/shared/config/api/URLs';
import { useRouter } from '@/shared/config/i18n/navigation';
import { useCartId } from '@/shared/hooks/cartId';
import formatPrice from '@/shared/lib/formatPrice';
import { Alert, AlertDescription, AlertTitle } from '@/shared/ui/alert';
import { Button } from '@/shared/ui/button';
import { Card, CardContent } from '@/shared/ui/card';
import { Input } from '@/shared/ui/input';
import { FlyingAnimationPortal } from '@/widgets/animation/FlyingAnimationPortal';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { AxiosError } from 'axios';
import { Heart, Minus, Plus, ShoppingCart } from 'lucide-react';
import { useTranslations } from 'next-intl';
import Image from 'next/image';
import { MouseEvent, useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';
import { useProductStore } from '../lib/hook';

export function ProductCard({
  product,
  error,
}: {
  product: ProductListResult | FavouriteProductRes;
  error?: boolean;
}) {
  const { setProduct } = useProductStore();
  const [quantity, setQuantity] = useState<number | ''>(0);
  const router = useRouter();
  const queryClient = useQueryClient();
  const t = useTranslations();
  const { cart_id } = useCartId();
  const [animated, setAnimated] = useState<boolean>(false);
  const debounceRef = useRef<NodeJS.Timeout | null>(null);
  const imageRef = useRef<HTMLDivElement>(null);

  const { mutate } = useMutation({
    mutationFn: (body: { product: string; quantity: number; cart: string }) =>
      cart_api.cart_item(body),
    onSuccess: () => {
      queryClient.refetchQueries({ queryKey: ['cart_items'] });
      setAnimated(true);
    },
    onError: (err: AxiosError) => {
      const detail = (err.response?.data as { detail: string }).detail;
      toast.error(detail || err.message, {
        richColors: true,
        position: 'top-center',
      });
    },
  });

  const { mutate: updateCartItem } = useMutation({
    mutationFn: ({
      body,
      cart_item_id,
    }: {
      body: { quantity: number };
      cart_item_id: string;
    }) => cart_api.update_cart_item({ body, cart_item_id }),
    onSuccess: () => {
      queryClient.refetchQueries({ queryKey: ['cart_items'] });
      setAnimated(true);
    },
    onError: (err: AxiosError) => {
      toast.error(err.message, { richColors: true, position: 'top-center' });
    },
  });

  const { mutate: deleteCartItem } = useMutation({
    mutationFn: ({ cart_item_id }: { cart_item_id: string }) =>
      cart_api.delete_cart_item(cart_item_id),
    onSuccess: () => {
      queryClient.refetchQueries({ queryKey: ['cart_items'] });
      setAnimated(true);
    },
    onError: (err: AxiosError) => {
      toast.error(err.message, { richColors: true, position: 'top-center' });
    },
  });

  const { data: cartItems } = useQuery({
    queryKey: ['cart_items', cart_id],
    queryFn: () => cart_api.get_cart_items(cart_id!),
    enabled: !!cart_id,
  });

  useEffect(() => {
    const item = cartItems?.data?.cart_item?.find(
      (item) => Number(item.product.id) === product.id,
    );

    setQuantity(item ? item.quantity : 0);
  }, [cartItems, product.id]);

  const favouriteMutation = useMutation({
    mutationFn: (productId: string) => product_api.favourite(productId),

    onSuccess: () => {
      queryClient.refetchQueries({ queryKey: ['product_list'] });
      queryClient.refetchQueries({ queryKey: ['list'] });
      queryClient.refetchQueries({ queryKey: ['favourite_product'] });
      queryClient.refetchQueries({ queryKey: ['search'] });
      queryClient.refetchQueries({ queryKey: ['product_detail', product] });
    },

    onError: () => {
      toast.error(t('Tizimga kirilmagan'), {
        richColors: true,
        position: 'top-center',
      });
    },
  });

  const increase = (e: MouseEvent<HTMLButtonElement>) => {
    e.stopPropagation();
    const newQty = (quantity === '' ? 0 : quantity) + 1;
    setQuantity(newQty);

    if (newQty > 1) {
      const cartItemId = cartItems?.data?.cart_item.find(
        (item) => Number(item.product.id) === product.id,
      )?.id;
      if (cartItemId) {
        updateCartItem({
          body: { quantity: newQty },
          cart_item_id: cartItemId.toString(),
        });
      }
    }
  };

  const decrease = (e: MouseEvent<HTMLButtonElement>) => {
    e.stopPropagation();

    if (!cartItems) return;

    const currentQty = quantity === '' ? 0 : quantity;
    const newQty = currentQty - 1;

    const cartItemId = cartItems.data.cart_item.find(
      (item) => Number(item.product.id) === product.id,
    )?.id;

    if (!cartItemId) return;

    if (newQty <= 0) {
      setQuantity(0);
      deleteCartItem({ cart_item_id: cartItemId.toString() });
      return;
    }

    setQuantity(newQty);
    updateCartItem({
      body: { quantity: newQty },
      cart_item_id: cartItemId.toString(),
    });
  };

  if (error) {
    return (
      <Card className="p-4 rounded-xl">
        <Alert variant="destructive">
          <AlertTitle>Xatolik</AlertTitle>
          <AlertDescription>{t('Mahsulotni yuklab bo‘lmadi')}</AlertDescription>
        </Alert>
      </Card>
    );
  }

  return (
    <>
      <Card
        onClick={(e) => {
          e.stopPropagation();
          router.push(`/product/${product.id}`);
          setProduct(product);
        }}
        className="group relative p-0 h-full flex flex-col overflow-hidden border border-slate-200 bg-white shadow-sm hover:shadow-lg transition-all rounded-xl sm:rounded-2xl hover:border-green-400"
      >
        <CardContent className="p-0 flex flex-col h-full">
          <div className="relative overflow-hidden">
            {/* {product. > 0 && (
            <div className="absolute top-2 left-2 z-10 bg-orange-500 text-white px-2 py-0.5 rounded-full text-xs sm:text-sm font-bold">
              -{product.discount}%
            </div>
          )} */}

            <Button
              onClick={(e) => {
                e.stopPropagation();
                favouriteMutation.mutate(String(product.id));
              }}
              aria-label="liked"
              className="absolute top-2 right-2 z-10 bg-white hover:bg-gray-200 cursor-pointer rounded-full p-1.5 sm:p-2 shadow hover:scale-110"
            >
              <Heart
                className={`w-4 h-4 sm:w-5 sm:h-5 ${
                  product.liked
                    ? 'fill-red-500 text-red-500'
                    : 'text-slate-400 hover:text-red-400'
                }`}
              />
            </Button>

            <div ref={imageRef} className="relative h-40 sm:h-48 md:h-56">
              <Image
                fill
                src={
                  product.images.length > 0
                    ? product?.images[0].image?.includes(BASE_URL)
                      ? product.images[0].image
                      : BASE_URL + product.images[0].image
                    : LogosProduct
                }
                alt={product.name}
                unoptimized
                className="object-cover"
              />
            </div>
          </div>

          <div className="p-3 sm:p-4 space-y-1 flex-1">
            {/* <div className="flex items-center gap-2">
            <Star className="w-3.5 h-3.5 sm:w-4 sm:h-4 fill-orange-400 text-orange-400" />
            <span className="text-xs sm:text-sm font-semibold text-orange-600">
              {product.rating}
            </span>
          </div> */}

            <h3 className="text-sm sm:text-base font-semibold text-slate-800 line-clamp-1">
              {product.name}
            </h3>

            <div>
              {product.prices.length > 0 && (
                <span className="text-lg sm:text-xl font-bold text-green-600">
                  {formatPrice(
                    Math.max(...product.prices.map((p) => Number(p.price))),
                    true,
                  )}
                </span>
              )}

              {/* {product. && (
              <div className="text-xs sm:text-sm text-slate-400 line-through">
                {formatPrice(product.oldPrice, true)}
              </div>
            )} */}
            </div>
          </div>
          <div className="p-3 sm:p-4 pt-0">
            {quantity === 0 ? (
              <Button
                onClick={(e) => {
                  e.stopPropagation();
                  mutate({
                    product: String(product.id),
                    quantity: 1,
                    cart: cart_id!,
                  });
                }}
                className="w-full h-9 sm:h-11 text-sm bg-green-600 hover:bg-green-600/80"
              >
                <ShoppingCart className="w-4 h-4 mr-1" />
                {t('Savatga')}
              </Button>
            ) : (
              <div
                onClick={(e) => e.stopPropagation()}
                className="flex items-center justify-between border border-green-500 rounded-lg h-9 sm:h-11"
              >
                <Button size="icon" variant="ghost" onClick={decrease}>
                  <Minus className="w-4 h-4" />
                </Button>

                <Input
                  value={quantity}
                  className="border-none text-center focus-visible:border-none focus-visible:ring-0"
                  onChange={(e) => {
                    const v = e.target.value;

                    // ❌ faqat raqam
                    if (!/^\d*$/.test(v)) return;

                    // ⛔ oldingi debounce'ni tozalaymiz
                    if (debounceRef.current) {
                      clearTimeout(debounceRef.current);
                    }

                    // bo‘sh input — faqat UI
                    if (v === '') {
                      setQuantity('');
                      return;
                    }

                    const num = Number(v);
                    setQuantity(num);

                    if (!cartItems) return;

                    const cartItemId = cartItems.data.cart_item.find(
                      (item) => Number(item.product.id) === product.id,
                    )?.id;

                    if (!cartItemId) return;

                    // ❗ 0 bo‘lsa — DELETE (darhol)
                    if (num === 0) {
                      deleteCartItem({ cart_item_id: cartItemId.toString() });
                      return;
                    }

                    // 🕒 debounce bilan UPDATE
                    debounceRef.current = setTimeout(() => {
                      updateCartItem({
                        body: { quantity: num },
                        cart_item_id: cartItemId.toString(),
                      });
                    }, 500);
                  }}
                />

                <Button size="icon" variant="ghost" onClick={increase}>
                  <Plus className="w-4 h-4" />
                </Button>
              </div>
            )}
          </div>
        </CardContent>
      </Card>
      <FlyingAnimationPortal
        product={product}
        animated={animated}
        imageRef={imageRef}
        setAnimated={setAnimated}
      />
    </>
  );
}
