import { useEffect, useState } from "react";
import { useRouter } from "next/router";
import useSWR from "swr";
// services
import { WorkspaceService } from "services/workspace.service";
// hooks
import { useUser } from "hooks/store";

const workspaceService = new WorkspaceService();

const useUserAuth = (routeAuth: "sign-in" | "onboarding" | "admin" | null = "admin") => {
  // states
  const [isRouteAccess, setIsRouteAccess] = useState(true);
  // router
  const router = useRouter();
  const { next_url } = router.query;
  const { fetchCurrentUser } = useUser();
  // form info
  const {
    data: user,
    isLoading,
    error,
    mutate,
  } = useSWR("CURRENT_USER_DETAILS", () => fetchCurrentUser(), {
    refreshInterval: 0,
    shouldRetryOnError: false,
  });

  useEffect(() => {
    const handleWorkSpaceRedirection = async () => {
      workspaceService.userWorkspaces().then(async (userWorkspaces) => {
        if (!user) return;

        const firstWorkspace = Object.values(userWorkspaces ?? {})?.[0];
        const lastActiveWorkspace = userWorkspaces[user?.last_workspace_id];

        if (lastActiveWorkspace) {
          router.push(`/${lastActiveWorkspace.slug}`);
          return;
        } else if (firstWorkspace) {
          router.push(`/${firstWorkspace.slug}`);
          return;
        } else {
          router.push(`/profile`);
          return;
        }
      });
    };

    const handleUserRouteAuthentication = async () => {
      if (user && user.is_active) {
        if (routeAuth === "sign-in") {
          if (user.is_onboarded) handleWorkSpaceRedirection();
          else {
            router.push("/onboarding");
            return;
          }
        } else if (routeAuth === "onboarding") {
          if (user.is_onboarded) handleWorkSpaceRedirection();
          else {
            setIsRouteAccess(() => false);
            return;
          }
        } else {
          if (!user.is_onboarded) {
            router.push("/onboarding");
            return;
          } else {
            setIsRouteAccess(() => false);
            return;
          }
        }
      } else {
        // user is not active and we can redirect to no access page
        // router.push("/no-access");
        // remove token
        return;
      }
    };

    if (routeAuth === null) {
      setIsRouteAccess(() => false);
      return;
    } else {
      if (!isLoading) {
        setIsRouteAccess(() => true);
        if (user) {
          if (next_url) router.push(next_url.toString());
          else handleUserRouteAuthentication();
        } else {
          if (routeAuth === "sign-in") {
            setIsRouteAccess(() => false);
            return;
          } else {
            router.push("/");
            return;
          }
        }
      }
    }
  }, [user, isLoading, routeAuth, router, next_url]);

  return {
    isLoading: isRouteAccess,
    user: error ? undefined : user,
    mutateUser: mutate,
    // assignedIssuesLength: user?.assigned_issues ?? 0,
    // workspaceInvitesLength: user?.workspace_invites ?? 0,
  };
};

export default useUserAuth;
