"use client";
import { useLocale, useTranslations } from "next-intl";
import { useDispatch } from "react-redux";
import { deleteCredentials } from "@/store/auth.slice";
import { clearCart } from "@/store/cart.slice";
import { AppDispatch } from "@/store/store";
import { clearAddresses } from "@/store/address.slice";
import { clearLocation } from "@/store/location.slice";
import { UseMutate } from "@/hooks/UseMutate";

export default function LogoutButton() {
  const locale = useLocale();
  const dispatch = useDispatch<AppDispatch>();
  const t = useTranslations("");
  const { mutate: handelLogout } = UseMutate({
    endpoint: "client/auth/logout",
    onSuccess: async () => {
      await Promise.all([
        dispatch(clearCart()),
        dispatch(clearAddresses()),
        dispatch(clearLocation()),
        dispatch(deleteCredentials()),
      ]);
      window.location.replace(`${locale == "ar" ? "/" : "/en"}`);
    },
  });

  return (
    <button
      onClick={() => handelLogout({})}
      className="cursor-pointer w-full rounded-2xl shadow-md shadow-black/10 bg-white p-4 flex items-center gap-4 hover:shadow-md transition-all duration-300 group border-2 border-error/10 hover:border-error/50"
    >
      <div className="w-12 h-12 rounded-lg flex items-center justify-center bg-error/10">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="24"
          height="24"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
          className="lucide lucide-log-out text-error"
        >
          <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
          <polyline points="16 17 21 12 16 7"></polyline>
          <line x1="21" x2="9" y1="12" y2="12"></line>
        </svg>
      </div>
      <span className="flex-1 text-end text-error"> {t("NAV.logout")}</span>
    </button>
  );
}
