'use client';

import { cart_api } from '@/features/cart/lib/api';
import { product_api } from '@/shared/config/api/product/api';
import { BASE_URL } from '@/shared/config/api/URLs';
import { useCartId } from '@/shared/hooks/cartId';
import formatPrice from '@/shared/lib/formatPrice';
import {
  Carousel,
  CarouselContent,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
} from '@/shared/ui/carousel';
import { Input } from '@/shared/ui/input';
import { Skeleton } from '@/shared/ui/skeleton';
import { ProductCard } from '@/widgets/categories/ui/product-card';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { AxiosError } from 'axios';
import { Heart, Minus, Plus, Shield, ShoppingCart, Truck } from 'lucide-react';
import { useTranslations } from 'next-intl';
import Image from 'next/image';
import { useParams } from 'next/navigation';
import { useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';

const ProductDetail = () => {
  const t = useTranslations();
  const { product } = useParams<{ product: string }>();
  const queryClient = useQueryClient();
  const { cart_id } = useCartId();

  const [quantity, setQuantity] = useState(1);
  const [selectedImage, setSelectedImage] = useState(0);
  const debounceRef = useRef<NodeJS.Timeout | null>(null);

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

  /* ---------------- PRODUCT DETAIL ---------------- */
  const { data, isLoading } = useQuery({
    queryKey: ['product_detail', product],
    queryFn: () => product_api.detail(product),
    select: (res) => res.data,
    enabled: !!product,
  });

  /* ---------------- RECOMMENDATION ---------------- */
  const { data: recomendation, isLoading: recLoad } = useQuery({
    queryKey: ['product_list'],
    queryFn: () => product_api.list({ page: 1, page_size: 12 }),
    select: (res) => res.data.results,
  });

  /* ---------------- DERIVED DATA ---------------- */
  const price = Number(data?.prices?.[0]?.price || 0);

  /* ---------------- SYNC CART QUANTITY ---------------- */
  useEffect(() => {
    if (!data || !cartItems) return;

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

    setQuantity(item ? item.quantity : 1);
  }, [data, cartItems]);

  /* ---------------- DEBOUNCE UPDATE ---------------- */
  useEffect(() => {
    if (!cart_id || !data || !cartItems || quantity <= 0) return;

    const cartItem = cartItems.data.cart_item.find(
      (i) => Number(i.product.id) === data.id,
    );

    if (!cartItem || cartItem.quantity === quantity) return;

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

    debounceRef.current = setTimeout(() => {
      updateCartItem({
        cart_item_id: cartItem.id.toString(),
        body: { quantity },
      });
    }, 500);

    return () => {
      if (debounceRef.current) clearTimeout(debounceRef.current);
    };
  }, [quantity]);

  /* ---------------- ADD TO CART ---------------- */
  const { mutate: addToCart } = useMutation({
    mutationFn: (body: { product: string; quantity: number; cart: string }) =>
      cart_api.cart_item(body),
    onSuccess: () => {
      queryClient.refetchQueries({ queryKey: ['cart_items'] });
      toast.success(t("Mahsulot savatga qo'shildi"), { richColors: true });
    },
    onError: (err: AxiosError) => {
      const msg =
        (err.response?.data as { detail: string })?.detail || err.message;
      toast.error(msg, { richColors: true });
    },
  });

  const { mutate: updateCartItem } = useMutation({
    mutationFn: (payload: {
      cart_item_id: string;
      body: { quantity: number };
    }) => cart_api.update_cart_item(payload),
    onSuccess: () => queryClient.refetchQueries({ queryKey: ['cart_items'] }),
  });

  /* ---------------- FAVOURITE ---------------- */
  const favouriteMutation = useMutation({
    mutationFn: (id: string) => product_api.favourite(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['product_detail'] });
      queryClient.invalidateQueries({ queryKey: ['product_list'] });
    },
    onError: () => {
      toast.error(t('Tizimga kirilmagan'), {
        richColors: true,
        position: 'top-center',
      });
    },
  });

  /* ---------------- HANDLERS ---------------- */
  const handleAddToCart = () => {
    if (!data || !cart_id) return;

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

    if (cartItem) {
      updateCartItem({
        cart_item_id: cartItem.id.toString(),
        body: { quantity },
      });
    } else {
      addToCart({
        product: String(data.id),
        cart: cart_id,
        quantity,
      });
    }
  };

  /* ---------------- LOADING ---------------- */
  if (isLoading) {
    return (
      <div className="custom-container py-6">
        <Skeleton className="h-[400px] w-full rounded-lg" />
      </div>
    );
  }

  /* ===================== RENDER ===================== */
  return (
    <div className="custom-container pb-8">
      <div className="grid grid-cols-1 md:grid-cols-2 gap-8 bg-white p-6 rounded-lg shadow">
        {/* IMAGES */}
        <div>
          <Image
            width={500}
            unoptimized
            height={500}
            src={
              data?.images?.length
                ? data.images[selectedImage]?.image?.includes(BASE_URL)
                  ? data.images[selectedImage]?.image
                  : BASE_URL + data.images[selectedImage]?.image
                : '/placeholder.svg'
            }
            alt={data?.name || 'logo'}
            className="w-full h-[400px] object-contain"
          />
          <Carousel className="mt-4">
            <CarouselContent>
              {(data?.images?.length
                ? data.images
                : [{ id: 0, image: '/placeholder.svg' }]
              ).map((img, i) => (
                <CarouselItem key={i} className="basis-1/4">
                  <button
                    onClick={() => setSelectedImage(i)}
                    className={`border rounded-lg p-1 ${
                      i === selectedImage
                        ? 'border-blue-500'
                        : 'border-gray-200'
                    }`}
                  >
                    <Image
                      src={img.image!}
                      alt={data?.name || 'Mahsulot rasmi'}
                      width={120}
                      height={120}
                      className="object-contain"
                      unoptimized
                    />
                  </button>
                </CarouselItem>
              ))}
            </CarouselContent>
          </Carousel>
        </div>

        {/* INFO */}
        <div>
          <h1 className="text-3xl font-bold mb-2">{data?.name}</h1>

          <div className="text-4xl font-bold text-blue-600 mb-4">
            {formatPrice(price, true)}
          </div>

          <p className="text-gray-600 mb-6">{data?.short_name}</p>

          <div className="grid grid-cols-2 gap-4 mb-6">
            <div>
              <span className="text-gray-500">Kategoriya:</span>
              <p className="font-semibold">{data?.groups[0].name}</p>
            </div>
          </div>

          <div className="flex items-center gap-4 mb-6">
            <button
              onClick={() => setQuantity((q) => Math.max(1, q - 1))}
              className="p-2 border rounded"
            >
              <Minus />
            </button>

            <Input
              value={quantity}
              onChange={(e) => {
                const v = Number(e.target.value);
                if (v > 0) setQuantity(v);
              }}
              className="w-16 text-center"
            />

            <button
              onClick={() => setQuantity((q) => q + 1)}
              className="p-2 border rounded"
            >
              <Plus />
            </button>
          </div>

          <div className="mb-6 font-semibold">
            {t('Jami')}: {formatPrice(price * quantity, true)}
          </div>

          {/* ACTIONS */}
          <div className="flex gap-3 mb-6">
            <button
              onClick={handleAddToCart}
              className="flex-1 bg-green-600 hover:bg-green-700 text-white py-3 rounded-lg flex justify-center items-center gap-2"
            >
              <ShoppingCart />
              {t('Savatga')}
            </button>

            <button
              onClick={() => favouriteMutation.mutate(String(data?.id))}
              className={`p-3 rounded-lg border ${
                data?.liked ? 'border-red-500 bg-red-50' : 'border-gray-300'
              }`}
            >
              <Heart
                className={data?.liked ? 'fill-red-500 text-red-500' : ''}
              />
            </button>
          </div>

          {/* FEATURES */}
          <div className="grid grid-cols-2 gap-4 mt-6 border-t pt-4">
            <div className="text-center">
              <Truck className="mx-auto mb-1" />
              {t('Bepul yetkazib berish')}
            </div>
            <div className="text-center">
              <Shield className="mx-auto mb-1" />
              {t('Kafolat')}
            </div>
          </div>
        </div>
      </div>

      {/* RELATED */}
      <div className="mt-10 bg-white p-6 rounded-lg shadow">
        <h2 className="text-2xl font-bold mb-4">{t("O'xshash mahsulotlar")}</h2>

        <Carousel>
          <CarouselContent>
            {recLoad &&
              Array.from({ length: 6 }).map((_, i) => (
                <CarouselItem key={i} className="basis-1/5">
                  <Skeleton className="h-60 w-full" />
                </CarouselItem>
              ))}

            {recomendation
              ?.filter((p) => p.state === 'A')
              .map((p) => (
                <CarouselItem key={p.id} className="basis-1/5">
                  <ProductCard product={p} />
                </CarouselItem>
              ))}
          </CarouselContent>

          <CarouselPrevious />
          <CarouselNext />
        </Carousel>
      </div>
    </div>
  );
};

export default ProductDetail;
