'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 { userStore } from '@/widgets/welcome/lib/hook';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { AxiosError } from 'axios';
import { Heart, Minus, Plus } 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 | string>(0);
  const router = useRouter();
  const queryClient = useQueryClient();
  const t = useTranslations();
  const { cart_id } = useCartId();
  const [animated, setAnimated] = useState(false);
  const debounceRef = useRef<NodeJS.Timeout | null>(null);
  const imageRef = useRef<HTMLDivElement>(null);
  const { user } = userStore();

  /** ✅ Measurement */
  const measurementName = product.meansurement?.name ?? null;
  const isGram = measurementName === 'gr';

  const defaultQty = isGram ? 100 : 1;
  const step = isGram ? 100 : 1;
  const measurementDisplay = measurementName || 'шт.';

  /** 🛒 Add */
  const { mutate: addToCart } = useMutation({
    mutationFn: (body: { product: string; quantity: number; cart: string }) =>
      cart_api.cart_item(body),

    onSuccess: (_, variables) => {
      queryClient.refetchQueries({ queryKey: ['cart_items'] });
      setAnimated(true);

      toast.success(
        `${variables.quantity} ${measurementDisplay} ${t("savatga qo'shildi")}`,
        { richColors: true, position: 'top-center' },
      );
    },

    onError: (err: AxiosError) => {
      const detail = (err.response?.data as { detail?: string })?.detail;
      toast.error(detail || err.message, {
        richColors: true,
        position: 'top-center',
      });
    },
  });

  /** 🔄 Update */
  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);
    },
  });

  /** ❌ Delete */
  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);
    },
  });

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

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

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

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

  const numericQty =
    quantity === '' || quantity === '.' || quantity === ','
      ? 0
      : Number(String(quantity).replace(',', '.'));

  /** ➖ Decrease */
  const decrease = (e: MouseEvent<HTMLButtonElement>) => {
    e.stopPropagation();
    if (!cartItems) return;

    const newQty = numericQty - step;
    const id = getCartItemId();
    if (!id) return;

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

    setQuantity(newQty);

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

  /** ➕ Increase */
  const increase = (e: MouseEvent<HTMLButtonElement>) => {
    e.stopPropagation();

    const newQty = numericQty + step;
    const id = getCartItemId();
    if (!id) return;

    setQuantity(newQty);

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

  /** ❤️ Favourite */
  const favouriteMutation = useMutation({
    mutationFn: (productId: string) => product_api.favourite(productId),

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

    onError: (err: AxiosError) => {
      const detail = (err.response?.data as { detail?: string })?.detail;
      toast.error(detail || err.message, {
        richColors: true,
        position: 'top-center',
      });
    },
  });

  const price = product.prices.find((p) => p.price_type.code === '1')
    ? product.prices.find((p) => p.price_type.code === '1')?.price
    : Math.min(...product.prices.map((p) => Number(p.price)));

  /** ❌ Error */
  if (error) {
    return (
      <Card className="p-4 rounded-xl">
        <Alert variant="destructive">
          <AlertTitle>{t('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">
            <Button
              onClick={(e) => {
                e.stopPropagation();
                if (user === null) {
                  router.push('/auth');
                  return;
                } else {
                  favouriteMutation.mutate(String(product.id));
                }
              }}
              className="absolute top-2 right-2 z-10 bg-white hover:bg-gray-200 rounded-full p-2 shadow"
            >
              <Heart
                className={`w-4 h-4 ${
                  product.liked ? 'fill-red-500 text-red-500' : 'text-slate-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-2 flex-1">
            {product.prices.length > 0 && (
              <p className="text-lg font-bold">
                {formatPrice(Number(price), true)}
                <span className="text-sm text-slate-500 ml-1">
                  /{measurementDisplay}
                </span>
              </p>
            )}

            <h3 className="text-sm font-medium line-clamp-2">{product.name}</h3>
          </div>

          <div className="p-3 sm:p-4 pt-0">
            {typeof quantity === 'number' && quantity === 0 ? (
              <Button
                onClick={(e) => {
                  e.stopPropagation();

                  if (user) {
                    addToCart({
                      product: String(product.id),
                      quantity: defaultQty,
                      cart: cart_id!,
                    });
                  } else {
                    router.push('/auth');
                  }
                }}
                className="w-full bg-white border border-slate-300 text-slate-700"
              >
                {t('Savatga')}
              </Button>
            ) : (
              <div
                onClick={(e) => e.stopPropagation()}
                className="flex items-center justify-between border border-slate-300 rounded-lg h-10"
              >
                <Button size="icon" variant="ghost" onClick={decrease}>
                  <Minus className="w-4 h-4" />
                </Button>

                <div className="flex items-center gap-2">
                  <Input
                    value={quantity}
                    className="border-none text-center w-16"
                    onChange={(e) => {
                      const v = e.target.value;

                      /** ✅ Decimal + comma */
                      if (!/^\d*([.,]\d*)?$/.test(v)) return;

                      if (debounceRef.current)
                        clearTimeout(debounceRef.current);

                      setQuantity(v);

                      const id = getCartItemId();
                      if (!id) return;

                      const num = Number(v.replace(',', '.'));

                      debounceRef.current = setTimeout(() => {
                        if (num === 0) {
                          deleteCartItem({
                            cart_item_id: id.toString(),
                          });
                        } else if (!isNaN(num)) {
                          updateCartItem({
                            cart_item_id: id.toString(),
                            body: { quantity: num },
                          });
                        }
                      }, 500);
                    }}
                  />
                </div>

                <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}
      />
    </>
  );
}
