import { type ReactNode, useState } from 'react';

import { IconChevronRight } from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import UserAvatar from '@material-hu/components/composed-components/UserAvatar';
import AvatarGroup from '@material-hu/components/design-system/AvatarGroup';
import Drawer from '@material-hu/components/design-system/Drawer';

import { type User } from 'src/types/user';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getFullName, getInitials } from 'src/utils/userUtils';

import { ellipsisTypographyStyle } from './constants';
import { type ApproverStepItem, type PotentialApprover } from './types';
import { getResponsiblesForCurrentApprovalStep } from './utils';

type ApproverSummaryUser = User | PotentialApprover;

const userInitials = (user: ApproverSummaryUser) => {
  const fullName = user.fullName || getFullName(user);
  return getInitials(fullName);
};

export type ApproversProps = {
  /** Approval steps (summary row and empty state are derived via getResponsiblesForCurrentApprovalStep). */
  steps: ApproverStepItem[];
  /** Title of the drawer when opening the full list */
  drawerTitle: string;
  /** Content to render inside the drawer (e.g. accordion of steps, custom list) */
  children: ReactNode;
  /** Whether the current user is an admin */
  isAdmin?: boolean;
};

const Approvers = ({
  steps,
  drawerTitle,
  children,
  isAdmin = false,
}: ApproversProps) => {
  const { t } = useLokaliseTranslation('approval_requests');
  const [seeApprovers, setSeeApprovers] = useState(false);

  const openSeeApprovers = () => {
    setSeeApprovers(true);
  };
  const closeSeeApprovers = () => {
    setSeeApprovers(false);
  };

  const currentResponsibles = getResponsiblesForCurrentApprovalStep(steps);
  const currentApprovers = currentResponsibles.approvers;
  const approvalStepCount = steps.length;

  const label = t('response_responsible', {
    count: currentResponsibles.count,
  });
  const stepHasNoPotentialApprovers = currentResponsibles.count === 0;
  const stepHasOnlyOneApprover = currentApprovers.length === 1;
  const stepHasMultipleApprovers = currentApprovers.length > 1;
  const showApproversPerStep =
    !stepHasOnlyOneApprover || approvalStepCount !== 1;
  const noApproversText = isAdmin
    ? t('response_responsible_no_assignee.can_approve')
    : t('response_responsible_no_assignee.admin_will_review');

  return (
    <>
      <Stack
        onClick={showApproversPerStep ? openSeeApprovers : undefined}
        sx={{
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
          cursor: showApproversPerStep ? 'pointer' : 'default',
        }}
      >
        <Stack sx={{ gap: 0.5, flex: 1, minWidth: 0 }}>
          <Typography
            variant="globalXXS"
            sx={{
              color: theme => theme.palette.new.text.neutral.lighter,
            }}
          >
            {label}
          </Typography>
          <Stack>
            <Stack sx={{ gap: 0.5 }}>
              {stepHasNoPotentialApprovers && (
                <Typography
                  variant="globalS"
                  sx={{
                    fontWeight: 'fontWeightSemiBold',
                    color: theme => theme.palette.new.text.neutral.default,
                  }}
                >
                  {noApproversText}
                </Typography>
              )}
              {stepHasOnlyOneApprover && (
                <Stack
                  onClick={e => {
                    e.stopPropagation();
                  }}
                  sx={{ width: 'fit-content' }}
                >
                  <UserAvatar
                    profileProps={{
                      redirectToPath: `/profile/${currentApprovers[0].id}`,
                    }}
                    user={currentApprovers[0]}
                    sx={{
                      width: 'fit-content',
                      '& .MuiListItem-root': {
                        py: 0.5,
                        px: 0,
                        width: 'fit-content',
                      },
                      '& .MuiStack-root': { gap: 2 },
                      '& .MuiTypography-root': {
                        ...ellipsisTypographyStyle,
                        maxWidth: 500,
                      },
                    }}
                  />
                </Stack>
              )}
              {stepHasMultipleApprovers && (
                <Stack sx={{ gap: 0.5 }}>
                  <AvatarGroup
                    avatars={currentApprovers.map(user => ({
                      src: user.profilePicture ?? undefined,
                      text: user.profilePicture
                        ? undefined
                        : userInitials(user),
                      color: 'primary',
                    }))}
                  />
                </Stack>
              )}
            </Stack>
          </Stack>
        </Stack>
        {showApproversPerStep && <IconChevronRight size={24} />}
      </Stack>
      <Drawer
        open={seeApprovers}
        onClose={closeSeeApprovers}
        title={drawerTitle}
        hasBackButton
      >
        <Stack sx={{ gap: 2 }}>{children}</Stack>
      </Drawer>
    </>
  );
};

export default Approvers;
