import React from 'react';
import {AvatarGroup, AvatarGroupItem, ListRow} from '@components/_HuGo';
import {useModalHandler} from '@hooks/useModalHandler';
import {User} from '@interfaces/user';
import {getCompleteName} from '@shared/utils';

import ApproversDetail from './components/ApproversDetail';
import {ApproversModalStep} from './interfaces';

export interface ApproversProps {
  approvers: AvatarGroupItem[];
  approversCount: number;
  steps: ApproversModalStep[];
  isPending: boolean;
  approversByStep: User[][];
  isLoadingApprovers: boolean;
  shouldOpenModal?: boolean;
  emptyApproversText?: string;
}

export function Approvers({
  approvers,
  approversCount,
  steps,
  isPending,
  approversByStep,
  isLoadingApprovers,
  shouldOpenModal = false,
  emptyApproversText,
}: ApproversProps) {
  const {isVisible, onCloseModal, onOpenModal} = useModalHandler();
  const firstApprover = approvers[0];
  const renderDialog = approversCount > 1 || shouldOpenModal;

  return (
    <>
      {approversCount > 1 ? (
        <AvatarGroup
          groupCount={approversCount}
          list={approvers}
          onPress={onOpenModal}
        />
      ) : (
        <ListRow onPress={shouldOpenModal ? onOpenModal : undefined}>
          <ListRow.Avatar url={firstApprover.url} name={firstApprover.name} />
          <ListRow.Title title={getCompleteName(firstApprover.name as User)} />
        </ListRow>
      )}
      {renderDialog && (
        <ApproversDetail
          isPending={isPending}
          isVisible={isVisible}
          onCloseModal={onCloseModal}
          approversByStep={approversByStep}
          isLoadingApprovers={isLoadingApprovers}
          steps={steps}
          emptyApproversText={emptyApproversText}
        />
      )}
    </>
  );
}
