import { StoreCart, StoreCartLineItem } from '@medusajs/types';

import {
  Table,
  TableBody,
  TableHead,
  TableHeader,
  TableRow,
} from '@kit/ui/table';
import { Trans } from '@kit/ui/trans';

import CartItem from './cart-item';
import MobileCartItems from './mobile-cart-items';

export default function CartItems({
  cart,
  items,
  productColumnLabelKey,
}: {
  cart: StoreCart;
  items: StoreCartLineItem[];
  productColumnLabelKey: string;
}) {
  if (!items || items.length === 0) {
    return null;
  }

  return (
    <>
      <Table className="hidden border-separate rounded-lg border sm:block">
        <TableHeader className="text-ui-fg-subtle txt-medium-plus">
          <TableRow>
            <TableHead className="px-4 sm:px-6">
              <Trans i18nKey={productColumnLabelKey} />
            </TableHead>
            <TableHead className="px-4 sm:px-6">
              <Trans i18nKey="cart:table.quantity" />
            </TableHead>
            <TableHead className="min-w-[100px] px-4 sm:px-6">
              <Trans i18nKey="cart:table.price" />
            </TableHead>
            <TableHead className="min-w-[100px] px-4 text-right sm:px-6">
              <Trans i18nKey="cart:table.total" />
            </TableHead>
            <TableHead className="px-4 sm:px-6"></TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {items
            .sort((a, b) =>
              (a.created_at ?? '') > (b.created_at ?? '') ? -1 : 1,
            )
            .map((item) => (
              <CartItem
                key={item.id}
                item={item}
                currencyCode={cart.currency_code}
              />
            ))}
        </TableBody>
      </Table>

      <div className="sm:hidden">
        {items
          .sort((a, b) =>
            (a.created_at ?? '') > (b.created_at ?? '') ? -1 : 1,
          )
          .map((item) => (
            <MobileCartItems
              key={item.id}
              item={item}
              currencyCode={cart.currency_code}
              productColumnLabelKey={productColumnLabelKey}
            />
          ))}
      </div>
    </>
  );
}
