"use client";
import { useEffect } from "react";
import ShowAlertMixin from "@/shared/ShowAlertMixin";
import { useDispatch } from "react-redux";
import { deleteCredentials } from "@/store/auth.slice";
import { useLocale, useTranslations } from "next-intl";
import { clearCart } from "@/store/cart.slice";
import { clearAddresses } from "@/store/address.slice";
import { clearLocation } from "@/store/location.slice";
import MediaWithFallback from "@/shared/MediaWithFallback";
import Unauthorized from "@/public/assets/images/401.png";

interface UseAuthorizationErrorProps {
  showError?: boolean;
}

export default function UseAuthorizationErrorServer({
  showError = true,
}: UseAuthorizationErrorProps) {
  const locale = useLocale();
  const dispatch = useDispatch();
  const t = useTranslations();

  useEffect(() => {
    if (showError) {
      ShowAlertMixin({
        icon: "error",
        title: t("session_expired"),
      });

      // Clear all user data and redirect to login
      dispatch(deleteCredentials());
      dispatch(clearCart());
      dispatch(clearAddresses());
      dispatch(clearLocation());

      // Redirect to login page after a short delay
      const timeout = setTimeout(() => {
        window.location.replace(`${locale === "ar" ? "" : "/en"}/auth/login`);
      }, 1000);

      return () => clearTimeout(timeout);
    }
  }, [showError, t, dispatch, locale]);

  return (
    <div className="h-fit grid items-center py-8">
      <div className="flex justify-center flex-col items-center">
        <MediaWithFallback
          width="500"
          height="500"
          src={Unauthorized}
          alt="not found icon"
          loading="lazy"
        />

        <h2 className="text-center font-bold lg:text-2xl text-lg my-4  ">
          {t("page 401")}
        </h2>
        <h2 className="text-center lg:w-[30%] w-3/4 mx-auto font-medium leading-8 text-lg my-4 text-sub">
          {t("page 401 description")}
        </h2>
        {/* <ErrorButton title={t("NAV.login")} link="/auth/login" /> */}
      </div>
    </div>
  );
}
