'use client';

import ProductBanner from '@/assets/product.png';
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,
  });

  // Haqiqiy raqamlar (hisob-kitob uchun)
  const [quantities, setQuantities] = useState<Record<string, number>>({});
  // Input ko'rinishi uchun string (nuqta bilan yozish imkonini beradi)
  const [inputValues, setInputValues] = useState<Record<string, string>>({});

  const debounceRef = useRef<Record<string, NodeJS.Timeout | null>>({});

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

  // Update mutation
  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: (_, variables) => {
      queryClient.invalidateQueries({ queryKey: ['cart_items', cart_id] });
      const item = cartItems?.find(
        (i) => String(i.id) === variables.cart_item_id,
      );
      if (item) {
        const measurementName = item.product.meansurement?.name || 'шт.';
        toast.success(
          `${t('Miqdor')} ${variables.body.quantity} ${measurementName} ${t('ga yangilandi')}`,
          { richColors: true, position: 'top-center' },
        );
      }
    },
    onError: (err: AxiosError) =>
      toast.error(err.message, { richColors: true, position: 'top-center' }),
  });

  // Delete mutation
  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] });
      toast.success(t("Savatdan o'chirildi"), {
        richColors: true,
        position: 'top-center',
      });
    },
    onError: (err: AxiosError) =>
      toast.error(err.message, { richColors: true, position: 'top-center' }),
  });

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

  const handleQuantityChange = (
    itemId: number,
    delta: number = 0,
    newValue?: number,
  ) => {
    setQuantities((prev) => {
      const item = cartItems?.find((i) => i.id === itemId);
      if (!item) return prev;

      const isGram = item.product.meansurement?.name?.toLowerCase() === 'gr';
      const STEP = isGram ? 100 : 1;
      const MIN_QTY = isGram ? 100 : 0.5;

      let updatedQty: number;
      if (newValue !== undefined) {
        updatedQty = newValue;
      } else {
        updatedQty = (prev[itemId] ?? MIN_QTY) + delta * STEP;
        if (updatedQty < MIN_QTY) updatedQty = MIN_QTY;
      }

      // inputValues ni ham yangilash
      setInputValues((prevInput) => ({
        ...prevInput,
        [itemId]: String(updatedQty),
      }));

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

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

      return { ...prev, [itemId]: updatedQty };
    });
  };

  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) => {
      if (!item.product.prices.length) return sum;

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

      const qty = quantities[item.id] ?? item.quantity;

      return sum + price * qty;
    }, 0) || 0;

  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) => {
              const measurementDisplay =
                item.product.meansurement?.name || 'шт.';
              const quantity = quantities[item.id] ?? item.quantity;
              // Input uchun string qiymat (nuqta bilan yozish imkonini beradi)
              const inputValue = inputValues[item.id] ?? String(item.quantity);

              return (
                <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: String(item.id) })
                    }
                    className="absolute right-2 w-7 h-7 top-2"
                  >
                    <Trash className="size-4" />
                  </Button>

                  <div className="w-24 h-40 bg-gray-100 rounded-lg overflow-hidden">
                    <Image
                      src={
                        item.product.images.length > 0
                          ? item.product.images[0].image.includes(BASE_URL)
                            ? item.product.images[0].image
                            : BASE_URL + item.product.images[0].image
                          : ProductBanner
                      }
                      alt={item.product.name}
                      width={300}
                      height={300}
                      unoptimized
                      className="object-cover w-full h-full"
                    />
                  </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">
                      <span className="text-blue-600 font-bold text-xl">
                        {item.product.prices.find(
                          (p) => p.price_type.code === '1',
                        )
                          ? formatPrice(
                              Number(
                                item.product.prices.find(
                                  (p) => p.price_type.code === '1',
                                )?.price,
                              ),
                              true,
                            )
                          : formatPrice(
                              Math.min(
                                ...item.product.prices.map((p) =>
                                  Number(p.price),
                                ),
                              ),
                              true,
                            )}
                      </span>
                      <span className="text-sm text-gray-500">
                        /{measurementDisplay}
                      </span>
                    </div>

                    <p className="text-sm text-gray-500 mb-2">
                      {t('Miqdor')}: {quantity} {measurementDisplay}
                    </p>

                    <div className="flex items-center border rounded-lg w-max">
                      <button
                        onClick={() => handleQuantityChange(item.id, -1)}
                        className="p-2 hover:bg-gray-50"
                      >
                        <Minus className="w-4 h-4" />
                      </button>

                      <div className="flex items-center gap-1 px-2">
                        <Input
                          value={inputValue}
                          onChange={(e) => {
                            const v = e.target.value;

                            // Faqat raqamlar va bitta nuqtaga ruxsat (vergul ham)
                            if (!/^\d*[.,]?\d*$/.test(v)) return;

                            // String sifatida saqlash (nuqta yo'qolmasin)
                            setInputValues((prev) => ({
                              ...prev,
                              [item.id]: v,
                            }));

                            // Bo'sh yoki faqat nuqta bo'lsa raqamga o'tkazmaymiz
                            if (v === '' || v === '.' || v === ',') return;

                            const parsed = parseFloat(v.replace(',', '.'));
                            if (isNaN(parsed)) return;

                            // quantities ni yangilash
                            setQuantities((prev) => ({
                              ...prev,
                              [item.id]: parsed,
                            }));

                            // Debounce bilan API ga yuborish
                            if (debounceRef.current[item.id])
                              clearTimeout(debounceRef.current[item.id]!);

                            debounceRef.current[item.id] = setTimeout(() => {
                              if (parsed <= 0) {
                                deleteCartItem({
                                  cart_item_id: String(item.id),
                                });
                              } else {
                                updateCartItem({
                                  body: { quantity: parsed },
                                  cart_item_id: String(item.id),
                                });
                              }
                            }, 500);
                          }}
                          onBlur={() => {
                            // Blur bo'lganda noto'g'ri qiymatlarni tuzatish
                            const isGram =
                              item.product.meansurement?.name?.toLowerCase() ===
                              'gr';
                            const MIN_QTY = isGram ? 100 : 0.5;
                            let value = quantities[item.id] ?? item.quantity;

                            if (!value || isNaN(value) || value < MIN_QTY)
                              value = MIN_QTY;

                            setInputValues((prev) => ({
                              ...prev,
                              [item.id]: String(value),
                            }));
                            handleQuantityChange(item.id, 0, value);
                          }}
                          type="text"
                          inputMode="decimal"
                          className="w-16 text-center border-none p-0"
                        />
                        <span className="text-xs text-gray-500">
                          {measurementDisplay}
                        </span>
                      </div>

                      <button
                        onClick={() => handleQuantityChange(item.id, 1)}
                        className="p-2 hover:bg-gray-50"
                      >
                        <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 className="text-green-600 font-semibold">
                  {t('Bepul')}
                </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 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;
