import { IconCircleCheck, IconCircleX } from '@material-hu/icons/tabler';
import Divider from '@material-hu/mui/Divider';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import UserAvatar from '@material-hu/components/composed-components/UserAvatar';
import Accordion from '@material-hu/components/design-system/Accordion';
import List from '@material-hu/components/design-system/List';
import { type PillsProps } from '@material-hu/components/design-system/Pills';

import { useLokaliseTranslation } from 'src/utils/i18n';

import { type ApproverStepItem } from './types';

const STATE_PILL_TYPE: Record<
  ApproverStepItem['state'],
  PillsProps['type'] | undefined
> = {
  approved: 'success',
  pending: 'warning',
  rejected: 'error',
  waiting: undefined,
};

const DEFAULT_PILL_LABEL: Record<ApproverStepItem['state'], string> = {
  approved: 'approval_requests:request_status.approved',
  pending: 'approval_requests:request_status.pending',
  rejected: 'approval_requests:request_status.rejected',
  waiting: 'approval_requests:request_status.in_progress',
};

export type ApproversAccordionProps = {
  step: ApproverStepItem;
  /**
   * When set, a pending step shows the warning “Pending” pill only if this user is in
   * `potentialApprovers`; otherwise it shows the informational “In progress” pill.
   */
  viewerUserId?: string | number | null;
};

const ApproversAccordion = ({
  step,
  viewerUserId,
}: ApproversAccordionProps) => {
  const { t } = useLokaliseTranslation('approval_requests');
  const pillType = STATE_PILL_TYPE[step.state];
  const pillLabel = step.pillLabel ?? t(DEFAULT_PILL_LABEL[step.state]);
  const pill =
    pillType && pillLabel
      ? { label: pillLabel, type: pillType, hasIcon: false }
      : undefined;

  const hasViewerUserId = viewerUserId != null && viewerUserId !== '';
  const normalizedViewerUserId = hasViewerUserId ? String(viewerUserId) : null;
  const isViewerAmongPotentialApprovers =
    normalizedViewerUserId !== null &&
    (step.potentialApprovers?.some(
      approver => String(approver.id) === normalizedViewerUserId,
    ) ??
      false);
  const shouldShowInProgressPill =
    step.state === 'pending' &&
    hasViewerUserId &&
    !isViewerAmongPotentialApprovers;

  const inProgressPill: PillsProps = {
    label: t('approval_requests:request_status.in_progress'),
    type: 'info',
    hasIcon: false,
  };
  const resolvedPill = shouldShowInProgressPill ? inProgressPill : pill;

  const isStepPending = step.state === 'pending' || step.state === 'waiting';
  const isStepResolved = step.state === 'approved' || step.state === 'rejected';
  const accordionAvatarIcon = isStepPending
    ? { text: step.position.toString() }
    : { Icon: step.state === 'approved' ? IconCircleCheck : IconCircleX };

  const showPotentialApprovers =
    !isStepResolved &&
    !step.approver &&
    step.potentialApprovers &&
    step.potentialApprovers.length > 0;

  const hasNoApproversForStep =
    !isStepResolved &&
    !step.approver &&
    (!step.potentialApprovers || step.potentialApprovers.length === 0);

  return (
    <Accordion
      title={step.title}
      elevation={0}
      sx={{
        backgroundColor: theme => theme.palette.new.background.elements.grey,
        overflow: 'hidden',
        '& .MuiStack-root': {
          pt: 0,
          backgroundColor: theme => theme.palette.new.background.elements.grey,
        },
      }}
      defaultExpanded={step.defaultExpanded ?? true}
      pill={resolvedPill}
      avatar={{ ...accordionAvatarIcon, color: 'primary' }}
      customDetail={
        <>
          <Divider sx={{ mt: 1, mb: 2 }} />
          <Stack>
            <List
              sx={{
                alignItems: 'flex-start',
                backgroundColor: theme =>
                  theme.palette.new.background.elements.grey,
                display: 'flex',
                flexDirection: 'column',
              }}
            >
              {isStepResolved && step.approver && (
                <UserAvatar
                  user={step.approver}
                  profileProps={{
                    redirectToPath: `/profile/${step.approver.id}`,
                    showEmployeeInternalId: true,
                  }}
                />
              )}
              {showPotentialApprovers &&
                step.potentialApprovers?.map(user => (
                  <UserAvatar
                    key={user.id}
                    user={user}
                    profileProps={{
                      redirectToPath: `/profile/${user.id}`,
                      showEmployeeInternalId: true,
                    }}
                  />
                ))}
            </List>
            {hasNoApproversForStep && (
              <Typography
                variant="globalS"
                sx={{
                  fontWeight: 'fontWeightSemiBold',
                  color: theme => theme.palette.new.text.neutral.default,
                }}
              >
                {t('approval_requests:no_designated_approver')}
              </Typography>
            )}
          </Stack>
        </>
      }
    />
  );
};

export default ApproversAccordion;
