'use client';

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

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

  const cartFoods = React.useMemo(() => {
    if (!foods.length) return [];
    return Object.entries(items)
      .filter(([, detail]) => detail?.quantity && detail.quantity > 0)
      .map(([id]) =>
        foods.find((foodItem) => String(foodItem.id) === String(id))
      )
      .filter((food): food is Food => Boolean(food));
  }, [foods, items]);

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

  if (cartFoods.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'>
      {cartFoods.map((food) => (
        <MenuItemRenderer key={food.id}>
          <MenuItem food={food} />
        </MenuItemRenderer>
      ))}
    </div>
  );
};

export default CartItemsList;

