'use client';

import { useState } from 'react';

import { Spinner } from '@medusajs/icons';
import { Trash } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';

import { handleDeleteCartItem } from '~/lib/services/medusaCart.service';

const CartItemDelete = ({
  id,
  children,
}: {
  id: string;
  children?: React.ReactNode;
}) => {
  const [isDeleting, setIsDeleting] = useState(false);
  const { t } = useTranslation();

  const handleDelete = async () => {
    setIsDeleting(true);

    const promise = async () => {
      await handleDeleteCartItem({ lineId: id });
    };

    toast.promise(promise, {
      success: t(`cart:items.delete.success`),
      loading: t(`cart:items.delete.loading`),
      error: t(`cart:items.delete.error`),
    });
  };

  return (
    <div className="text-small-regular flex items-center justify-between">
      <button
        className="text-ui-fg-subtle hover:text-ui-fg-base flex cursor-pointer gap-x-1"
        onClick={() => handleDelete()}
      >
        {isDeleting ? <Spinner className="animate-spin" /> : <Trash />}
        <span>{children}</span>
      </button>
    </div>
  );
};

export default CartItemDelete;
