'use client';

import React from 'react';
import { useRouter } from 'next/navigation';
import { useTranslation } from 'react-i18next';
import { ArrowLeft, Trash } from 'iconsax-react';
import Image from 'next/image';
import { useCart } from './hook/useCart';
import CartSummary from './components/CartSummary';
import Prompt from '@/components/utils/Prompt';
import { useGetProducts } from '@/app/[name]/(Main)/hooks/useMenuData';
import MenuItem from '@/components/listview/MenuItem';
import MenuItemRenderer from '@/components/listview/MenuItemRenderer';

const CartIndex = () => {
  const { t } = useTranslation('parallels', { keyPrefix: 'Cart' });
  const router = useRouter();
  const { clearCart, items } = useCart();
  const [showClearConfirm, setShowClearConfirm] = React.useState(false);
  const { data: productsResponse, isFetching } = useGetProducts();
  const products = React.useMemo(() => productsResponse?.data ?? [], [productsResponse?.data]);
  const isLoading = isFetching && !products.length;

  const cartProducts = React.useMemo(() => {
    if (!products.length) return [];
    return Object.entries(items)
      .filter(([, detail]) => detail?.quantity && detail.quantity > 0)
      .map(([variantId, detail]) => {
        const product = products.find((p) =>
          p.variants?.some((v) => v.id === variantId)
        );
        const variantValue = (detail as { variantValue?: string } | undefined)?.variantValue;
        return product ? { product, variantId, variantValue } : null;
      })
      .filter((x): x is NonNullable<typeof x> => x != null);
  }, [products, items]);

  const isCartEmpty = cartProducts.length === 0;

  const handleClearCart = (e: React.MouseEvent) => {
    e?.preventDefault();
    e?.stopPropagation();
    clearCart();
    setShowClearConfirm(false);
  };

  const toggleClearConfirm = (e: React.MouseEvent) => {
    e?.preventDefault();
    e?.stopPropagation();
    setShowClearConfirm(false);
  };

  return (
    <div className='overflow-y-auto h-full noscrollbar flex flex-col bg-background -mx-6 -mt-4 -mb-6 px-6 pt-4 pb-6'>
      <div className='grid grid-cols-3 items-center'>
        {isCartEmpty ? (
          <span></span>
        ) : (
          <Trash
            className='cursor-pointer place-self-start'
            size='24'
            color='currentColor'
            onClick={() => setShowClearConfirm(true)}
          />
        )}
        <h1 className='text-sm2 place-self-center font-medium'>{t('Heading')}</h1>
        <ArrowLeft
          className='cursor-pointer place-self-end'
          size='24'
          color='currentColor'
          onClick={() => router.back()}
        />
      </div>

      <div className="mt-8 flex-1 h-full">
        {isLoading ? (
          <div className='flex flex-col items-center justify-center gap-2 py-12 text-sm2 text-muted-foreground'>
            <span className='h-4 w-4 animate-spin rounded-full border border-dashed border-foreground border-t-transparent'></span>
            <p>در حال دریافت سبد خرید...</p>
          </div>
        ) : isCartEmpty ? (
          <div className='flex flex-col items-center justify-center gap-4 h-full'>
            <Image
              src='/assets/images/cart.png'
              alt='cart'
              width={120}
              height={120}
              className='object-contain'
            />
            <div className='flex flex-col items-center gap-2 text-sm2 text-muted-foreground'>
              <p>{t('EmptyStateTitle', { defaultValue: 'سبد خرید شما خالی است' })}</p>
              <p className='text-xs'>
                {t('EmptyStateDescription', {
                  defaultValue: 'برای افزودن کالا، به منوی فروشگاه برگردید.',
                })}
              </p>
            </div>
          </div>
        ) : (
          <div className="flex flex-col gap-4 pb-24">
            {cartProducts.map(({ product, variantId, variantValue }) => (
              <MenuItemRenderer key={variantId}>
                <MenuItem product={product} variantId={variantId} variantValue={variantValue} />
              </MenuItemRenderer>
            ))}
            <CartSummary isPremium />
          </div>
        )}
      </div>

      <div className={showClearConfirm ? 'fixed inset-0 z-1001' : 'pointer-events-none fixed inset-0 z-1001'}>
        <Prompt
          title='پاک کردن سبد خرید'
          description='آیا از پاک کردن تمامی آیتم‌های سبد خرید اطمینان دارید؟'
          textConfirm='بله'
          textCancel='خیر'
          onConfirm={handleClearCart}
          onCancel={toggleClearConfirm}
          visible={showClearConfirm}
          onClick={toggleClearConfirm}
        />
      </div>
    </div>
  );
};

export default CartIndex;