'use client';
import { cart_api } from '@/features/cart/lib/api';
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 { Button } from '@/shared/ui/button';
import { Input } from '@/shared/ui/input';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { AxiosError } from 'axios';
import {
  ArrowLeft,
  CreditCard,
  Minus,
  Plus,
  ShoppingBag,
  Trash,
  Truck,
} from 'lucide-react';
import { useTranslations } from 'next-intl';
import Image from 'next/image';
import { useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';

const CartPage = () => {
  const { cart_id } = useCartId();
  const queryClient = useQueryClient();
  const router = useRouter();
  const t = useTranslations();

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

  const [quantities, setQuantities] = useState<Record<string, string>>({});
  const debounceRef = useRef<Record<string, NodeJS.Timeout | null>>({});

  useEffect(() => {
    if (!cartItems) return;
    const initialQuantities: Record<string, string> = {};
    cartItems.forEach((item) => {
      initialQuantities[item.id] = String(item.quantity);
      debounceRef.current[item.id] = null;
    });
    setQuantities(initialQuantities);
  }, [cartItems]);

  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.invalidateQueries({ queryKey: ['cart_items', cart_id] }),
    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.invalidateQueries({ queryKey: ['cart_items', cart_id] }),
    onError: (err: AxiosError) =>
      toast.error(err.message, { richColors: true, position: 'top-center' }),
  });

  const handleCheckout = () => router.push('/cart/order');

  if (isLoading)
    return (
      <div className="min-h-screen flex items-center justify-center">
        Loading...
      </div>
    );

  if (!cartItems || cartItems.length === 0)
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <ShoppingBag className="w-24 h-24 text-gray-300 mx-auto mb-4" />
          <h2 className="text-2xl font-bold text-gray-800 mb-2">
            {t("Savatingiz bo'sh")}
          </h2>
          <p className="text-gray-600 mb-6">
            {t("Mahsulotlar qo'shish uchun katalogga o'ting")}
          </p>
          <button
            onClick={() => router.push('/')}
            className="bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 transition flex items-center gap-2 mx-auto"
          >
            <ArrowLeft className="w-5 h-5" /> {t('Xarid qilishni boshlash')}
          </button>
        </div>
      </div>
    );

  const subtotal = cartItems.reduce(
    (sum, item) => sum + item.product_price * Number(item.quantity),
    0,
  );

  const handleQuantityChange = (itemId: string, value: number) => {
    setQuantities((prev) => ({
      ...prev,
      [itemId]: String(value),
    }));

    if (debounceRef.current[itemId]) clearTimeout(debounceRef.current[itemId]!);

    debounceRef.current[itemId] = setTimeout(() => {
      if (value <= 0) {
        deleteCartItem({ cart_item_id: itemId });
      } else {
        updateCartItem({ body: { quantity: value }, cart_item_id: itemId });
      }
    }, 500);
  };

  return (
    <div className="custom-container mb-6">
      <div className="mb-6">
        <h1 className="text-3xl font-bold text-gray-800 mb-2">{t('Savat')}</h1>
        <p className="text-gray-600">
          {cartItems.length} {t('ta mahsulot')}
        </p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2">
          <div className="bg-white rounded-lg shadow-md overflow-hidden">
            {cartItems.map((item, index) => (
              <div
                key={item.id}
                className={`p-6 flex relative gap-4 ${
                  index !== cartItems.length - 1 ? 'border-b' : ''
                }`}
              >
                <Button
                  variant="destructive"
                  size="icon"
                  onClick={() => deleteCartItem({ cart_item_id: item.id })}
                  className="absolute right-2 w-7 h-7 top-2 cursor-pointer"
                >
                  <Trash className="size-4" />
                </Button>

                <div className="w-24 h-40 bg-gray-100 rounded-lg flex-shrink-0 overflow-hidden">
                  <Image
                    src={BASE_URL + item.product_image}
                    alt={item.product_name}
                    width={500}
                    height={500}
                    className="object-cover"
                    style={{ width: '100%', height: 'auto' }}
                  />
                </div>

                <div className="flex-1">
                  <h3 className="font-semibold text-lg mb-1">
                    {item.product_name}
                  </h3>
                  <div className="flex items-center gap-2 mb-3 max-lg:flex-col max-lg:items-start max-lg:gap-1">
                    <span className="text-blue-600 font-bold text-xl">
                      {formatPrice(item.product_price, true)}
                    </span>
                  </div>

                  <div className="flex items-center border border-gray-300 rounded-lg w-max">
                    <button
                      onClick={() =>
                        handleQuantityChange(
                          item.id,
                          Number(quantities[item.id]) - 1,
                        )
                      }
                      className="p-2 cursor-pointer transition rounded-lg"
                    >
                      <Minus className="w-4 h-4" />
                    </button>

                    <Input
                      value={quantities[item.id]}
                      onChange={(e) => {
                        const val = e.target.value.replace(/\D/g, ''); // faqat raqam
                        setQuantities((prev) => ({
                          ...prev,
                          [item.id]: val,
                        }));

                        // Debounce bilan update
                        const valNum = Number(val);
                        if (!isNaN(valNum))
                          handleQuantityChange(item.id, valNum);
                      }}
                      type="text"
                      className="w-16 text-center"
                    />

                    <button
                      onClick={() =>
                        handleQuantityChange(
                          item.id,
                          Number(quantities[item.id]) + 1,
                        )
                      }
                      className="p-2 cursor-pointer transition rounded-lg"
                    >
                      <Plus className="w-4 h-4" />
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="lg:col-span-1">
          <div className="bg-white rounded-lg shadow-md p-6 sticky top-4">
            <h3 className="text-xl font-bold mb-4">{t('Buyurtma haqida')}</h3>

            <div className="space-y-3 mb-4">
              <div className="flex justify-between text-gray-600">
                <span>{t('Mahsulotlar narxi')}:</span>
                <span>{formatPrice(subtotal, true)}</span>
              </div>

              <div className="flex justify-between text-gray-600">
                <span className="flex items-center gap-1">
                  <Truck className="w-4 h-4" /> {t('Yetkazib berish')}:
                </span>
                <span>
                  <span className="text-green-600 font-semibold">
                    {t('Bepul')}
                  </span>
                </span>
              </div>
            </div>

            <div className="border-t pt-4 mb-6">
              <div className="flex justify-between items-center">
                <span className="text-lg font-semibold">{t('Jami')}:</span>
                <span className="text-2xl font-bold text-blue-600">
                  {formatPrice(subtotal, true)}
                </span>
              </div>
            </div>

            <button
              onClick={handleCheckout}
              className="w-full bg-blue-600 text-white py-4 rounded-lg font-semibold hover:bg-blue-700 transition flex items-center justify-center gap-2 mb-4"
            >
              <CreditCard className="w-5 h-5" />{' '}
              {t('Buyurtmani rasmiylashtirish')}
            </button>

            <button
              onClick={() => router.push('/')}
              className="w-full border-2 border-gray-300 cursor-pointer text-gray-700 py-3 rounded-lg font-semibold hover:bg-gray-50 transition flex items-center justify-center gap-2"
            >
              <ArrowLeft className="w-5 h-5" /> {t('Xaridni davom ettirish')}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default CartPage;
