import {useMemo} from 'react';
import {useTranslation} from 'react-i18next';
import {ScrollView} from 'react-native-gesture-handler';
import {Dialog, Skeleton} from '@components/_HuGo';
import {useSafeAreaBottomPadding} from '@hooks/useSafeAreaBottomPadding';
import {User} from '@interfaces/user';
import {getCurrentStepIndex} from '@modules/timeOff/utils';
import {useTheme} from '@shared/theme';

import {ApproversModalStep} from '../../interfaces';
import ApproversStep from '../ApproversStep';
import {styles} from './styles';

const PLURAL_COUNT = 2;

interface Props {
  isPending: boolean;
  isVisible: boolean;
  onCloseModal: () => void;
  steps: ApproversModalStep[];
  approversByStep: User[][];
  isLoadingApprovers: boolean;
  emptyApproversText?: string;
}

function ApproversDetail({
  isPending,
  isVisible,
  onCloseModal,
  steps,
  approversByStep,
  isLoadingApprovers,
  emptyApproversText,
}: Props) {
  const {spacing} = useTheme();
  const {t} = useTranslation();
  const paddingBottom = useSafeAreaBottomPadding({extra: spacing.x3});
  const currentStepIndex = useMemo(() => getCurrentStepIndex(steps), [steps]);

  const renderStep = (stepApprovers: User[], index: number) => {
    const currentStep = steps[index];
    return (
      <ApproversStep
        emptyApproversText={emptyApproversText}
        index={index}
        isCurrentStep={index === currentStepIndex}
        isPending={isPending}
        key={index}
        stepApprovers={stepApprovers}
        stepComment={currentStep.comment}
        stepState={currentStep.state}
      />
    );
  };

  return (
    <Dialog
      fullScreen
      isVisible={isVisible}
      onClose={onCloseModal}
      title={t('time_off.responsible_for_response', {count: PLURAL_COUNT})}
      wrapperType="scrollable">
      {isLoadingApprovers ? (
        <Skeleton style={styles.spinnerContainer}>
          {steps.map((_, index) => (
            <Skeleton.Item key={index} height={!index ? 300 : 80} />
          ))}
        </Skeleton>
      ) : (
        <ScrollView
          bounces={false}
          contentContainerStyle={[styles.container, {paddingBottom}]}
          showsVerticalScrollIndicator={false}>
          {approversByStep.map(renderStep)}
        </ScrollView>
      )}
    </Dialog>
  );
}

export default ApproversDetail;
