import { useCallback } from 'react';
import { useNavigate } from 'react-router-dom';

import Stack from '@material-hu/mui/Stack';

import HuCircularProgress from '@material-hu/components/design-system/ProgressIndicators/Spinner';

import { type CalibratedUser } from 'src/pages/dashboard/performance/types';

import NavigationSidebar from '../../components/Shared/NavigationSidebar';
import { performanceRoutes } from '../../routes';
import useCalibrationsSidebar from '../hooks/useCalibrationsSidebar';
import {
  getCalibrationItemId,
  getCalibrationItemIsCompleted,
  getCalibrationItemPrimaryLabel,
  getCalibrationItemUser,
} from '../utils';

type CalibrationNavigationSidebarProps = {
  cycleId: string | number;
  formReviewId: number;
};

const CalibrationNavigationSidebar = ({
  cycleId,
  formReviewId,
}: CalibrationNavigationSidebarProps) => {
  const navigate = useNavigate();
  const { items, isLoading } = useCalibrationsSidebar({ cycleId });

  const handleSelect = useCallback(
    (item: CalibratedUser) => {
      if (item.formReviewId === formReviewId) return;
      navigate(performanceRoutes.calibration(cycleId, item.formReviewId), {
        replace: true,
      });
    },
    [cycleId, formReviewId, navigate],
  );

  if (isLoading) {
    return (
      <Stack sx={{ alignItems: 'center', py: 3 }}>
        <HuCircularProgress />
      </Stack>
    );
  }

  return (
    <NavigationSidebar
      groups={[{ titleKey: 'general:collaborators', items }]}
      selectedId={formReviewId}
      getItemId={getCalibrationItemId}
      getUser={getCalibrationItemUser}
      getPrimaryLabel={getCalibrationItemPrimaryLabel}
      isCompleted={getCalibrationItemIsCompleted}
      onSelect={handleSelect}
    />
  );
};

export default CalibrationNavigationSidebar;
