import { useQuery } from 'react-query';

import { useAuth } from 'src/contexts/JWTContext';
import { useGetManagerTypes } from 'src/hooks/queryHooks/manager';
import { timeTrackingKeys } from 'src/pages/dashboard/timeTracking/queries';
import { getTimeTrackingPolicies } from 'src/services/timeTracking';
import { type TimeTrackingPolicies } from 'src/types/timeTracking';
import {
  hasAllPermissions,
  ROUTE_PERMISSIONS,
  UserPermissions,
} from 'src/utils/permissions';

import usePermissions from './usePermissions';

const { VIEW_TIME_TRACKING } = UserPermissions;

type UseTimeTrackingAccessReturn = {
  canAccessClock: boolean;
  canAccessTimeTrackingModule: boolean;
  timeTrackingAppEnabled: boolean;
  isLoading: boolean;
  isManager: boolean;
  policies: TimeTrackingPolicies | undefined;
};

export const useTimeTrackingAccess = (): UseTimeTrackingAccessReturn => {
  const { user, permissions } = useAuth();
  const { hasAll: timeTrackingAppEnabled } = usePermissions([
    VIEW_TIME_TRACKING,
  ]);
  const { isManager, isFetchingSubordinates } = useGetManagerTypes([]);

  const { data: policies, isLoading: isLoadingPolicies } = useQuery(
    timeTrackingKeys.policies(),
    () => getTimeTrackingPolicies(user?.id ?? 0),
    {
      select: res => res.data,
      enabled: timeTrackingAppEnabled,
    },
  );

  const moduleRequiredPermissions = isManager
    ? ROUTE_PERMISSIONS.TIME_TRACKING_BOSS
    : ROUTE_PERMISSIONS.TIME_TRACKING;

  return {
    canAccessClock:
      timeTrackingAppEnabled && (policies?.clockingInWebEnabled ?? false),
    canAccessTimeTrackingModule: hasAllPermissions(
      permissions,
      moduleRequiredPermissions,
    ),
    timeTrackingAppEnabled,
    isLoading: isFetchingSubordinates || isLoadingPolicies,
    isManager,
    policies,
  };
};
