'use client';

import { useState } from 'react';

import { useRouter } from 'next/navigation';

import { deleteLineItem } from '@lib/data/cart';
import { Spinner, Trash } from '@medusajs/icons';
import { clx } from '@medusajs/ui';

const DeleteButton = ({
  id,
  children,
  className,
  Icon,
}: {
  id: string;
  children?: React.ReactNode;
  className?: string;
  Icon?: React.ReactNode;
}) => {
  const [isDeleting, setIsDeleting] = useState(false);
  const router = useRouter();

  const handleDelete = async (id: string) => {
    setIsDeleting(true);

    try {
      await deleteLineItem(id);

      router.refresh();
    } catch (err) {
      // TODO: display a toast notification with the error
      setIsDeleting(false);
    }
  };

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

export default DeleteButton;
