"use client";
import shoppingCartService from "@/lib/services/shoppingcart";
import { getStoreData } from "@/lib/utils/storagedata";
import { useCartStore } from "@/zustand/cartStore";
import * as AlertDialog from "@radix-ui/react-alert-dialog";

export default function Page() {
  const { setCartItems } = useCartStore();

  const clearAll = async () => {
    const token = (await getStoreData<string>("token")) || "";

    const response = await shoppingCartService.clearShoppingCart(
      token,
    );
    if (response.success) {
      setCartItems([]);
    }
  };

  return (
    <AlertDialog.Root>
      <AlertDialog.Trigger asChild>
        <button className="text-primary bg-transparent transition-colors text-sm md:text-base font-bold">
          Clear Cart
        </button>
      </AlertDialog.Trigger>

      <AlertDialog.Portal>
        <AlertDialog.Overlay className="fixed z-40 inset-0 bg-black/40 data-[state=open]:animate-overlayShow" />
        <AlertDialog.Content className="z-50 fixed left-1/2 top-1/2 max-h-[85vh] w-[90vw] max-w-[500px] -translate-x-1/2 -translate-y-1/2 rounded-md bg-white p-[25px] shadow-lg focus:outline-none data-[state=open]:animate-contentShow">
          <AlertDialog.Title className="m-0 text-[17px] font-medium text-gray-900">
            Are you absolutely sure?
          </AlertDialog.Title>
          <AlertDialog.Description className="mb-5 mt-[15px] text-[15px] leading-normal text-gray-600">
            You want to clear all item!
          </AlertDialog.Description>
          <div className="flex justify-end gap-[25px]">
            <AlertDialog.Cancel asChild>
              <button className="inline-flex h-[35px] items-center justify-center rounded bg-gray-200 px-[15px] font-medium text-gray-700 hover:bg-gray-300 focus-visible:outline focus-visible:outline-2 focus-visible:outline-gray-500">
                Cancel
              </button>
            </AlertDialog.Cancel>
            <AlertDialog.Action asChild>
              <button
                onClick={clearAll}
                className="inline-flex h-[35px] items-center justify-center rounded bg-red-500 px-[15px] font-medium text-white hover:bg-red-600 focus-visible:outline focus-visible:outline-2 focus-visible:outline-red-700"
              >
                Yes, delete
              </button>
            </AlertDialog.Action>
          </div>
        </AlertDialog.Content>
      </AlertDialog.Portal>
    </AlertDialog.Root>
  );
}
