import React, { FC, useEffect } from 'react';

import { USER_ROLE_UPDATE } from '../../../../constants/appLoading';
import { useUpdateLoadingStatus } from '../../../../hooks/useAppLoading';
import { useUserInfo } from '../../../../hooks/useStorage';
import { useUpdateUserRole } from '../../../../hooks/useUser';
import { UserRoleAllResponse } from '../../../../services/api/APIS/UserManagement/types';
import SelectModal from '../../../Modal/SelectModal';

type props = {
  userRoles: UserRoleAllResponse[];
  isVisible: boolean;
  setIsVisible: (value: boolean) => void;
};

const UserRoleModal: FC<props> = ({ userRoles, isVisible, setIsVisible }) => {
  const [userInfo, setUserInfo] = useUserInfo();
  const updateLoadingStatus = useUpdateLoadingStatus();

  const { isLoading, mutate: updateRole } = useUpdateUserRole(
    userInfo.token,
    userInfo,
    setUserInfo,
  );

  useEffect(() => {
    updateLoadingStatus(isLoading, USER_ROLE_UPDATE);
  }, [isLoading]);

  return (
    <SelectModal
      items={userRoles}
      title="Vyberte roli"
      fullHeight={userRoles && userRoles?.length > 20}
      itemGetter={role => role.displayName}
      isVisible={isVisible}
      setIsVisible={setIsVisible}
      selected={userRoles.find(role => role.id === userInfo.roleId)}
      setSelected={role => {
        updateRole(role.id);
      }}
    />
  );
};

export default UserRoleModal;
