'use client';

import React from 'react';
import MenuItem from '@/components/listview/MenuItem';
import MenuItemRenderer from '@/components/listview/MenuItemRenderer';
import { useGetProducts } from '@/app/[name]/(Main)/hooks/useMenuData';
import type { Product } from '@/app/[name]/(Main)/types/Types';
import { useCart } from '../hook/useCart';
import { useTranslation } from 'react-i18next';
import { CartItemsSkeleton } from './CartSkeleton';

const CartItemsList = () => {
  const { data: productsResponse, isFetching } = useGetProducts();
  const products = React.useMemo(() => productsResponse?.data ?? [], [productsResponse?.data]);
  const { items } = useCart();
  const { t } = useTranslation('parallels', { keyPrefix: 'Cart' });

  const cartLines = React.useMemo(() => {
    if (!products.length) return [];
    return Object.entries(items)
      .filter(([, detail]) => detail?.quantity && detail.quantity > 0)
      .map(([variantId]) => {
        const product = products.find((p) =>
          p.variants?.some((v) => String(v.id) === String(variantId))
        );
        return product ? { product, variantId } : null;
      })
      .filter((line): line is { product: Product; variantId: string } => line != null);
  }, [products, items]);

  if (isFetching && !products.length) {
    return <CartItemsSkeleton />;
  }

  if (cartLines.length === 0) {
    return (
      <div className='flex flex-col items-center justify-center gap-2 py-12 text-sm2 text-muted-foreground'>
        <p>{t('EmptyStateTitle', { defaultValue: 'سبد خرید شما خالی است' })}</p>
        <p className='text-xs'>
          {t('EmptyStateDescription', {
            defaultValue: 'برای افزودن کالا، به منوی فروشگاه برگردید.',
          })}
        </p>
      </div>
    );
  }

  return (
    <div className='flex-1 space-y-4'>
      {cartLines.map(({ product, variantId }) => (
        <MenuItemRenderer key={variantId}>
          <MenuItem product={product} variantId={variantId} />
        </MenuItemRenderer>
      ))}
    </div>
  );
};

export default CartItemsList;

