import Collapse from '@material-hu/mui/Collapse';
import * as colors from '@material-hu/mui/colors';
import MuiList from '@material-hu/mui/List';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import { PeopleExperience } from '@material-hu/components/composed-components/peopleExperience';

import useManagerParticipation from '../hooks/useManagerParticipation';
import { type ParticipationListParams, SegmentType } from '../types';
import { useLokaliseTranslation } from 'src/utils/i18n';

const {
  ListWithDivider,
  ParticipationItemSkeleton,
  ParticipationExpandableItem,
  ParticipationItem,
} = PeopleExperience;

type UsersParticipationListProps = ParticipationListParams & {
  expanded?: boolean;
};

const ParticipationList = ({
  depth = 0,
  surveyId,
  parentId,
  limit,
  expanded = true,
  page,
  order,
  dimension,
  q,
}: UsersParticipationListProps) => {
  const { t } = useLokaliseTranslation('people_experience');

  const { data, isLoading, isSuccess, isPreviousData } =
    useManagerParticipation({
      depth,
      surveyId,
      parentId,
      limit,
      page,
      dimension,
      ...(depth === 0 && { order, q }),
      queryOptions: {
        enabled: expanded,
        keepPreviousData: true,
      },
    });

  const noDataMessage = t('NOT_ENOUGH_PARTICIPANTS');

  const items =
    data?.items.map(
      ({
        id,
        hasChildren,
        title,
        totalReviews,
        completedReviews,
        participationPercentage,
        subtitle,
        childrenAmount,
      }) => {
        const partial = completedReviews;
        const total = totalReviews;

        const participationItemSlotProps = {
          misc: {
            label: t('participants_ratio', { partial, total }),
            noDataMessage,
            isEmpty: total === 0,
            sx: {
              width: '200px',
            },
          },
        };

        if (hasChildren) {
          return (
            <ParticipationExpandableItem
              primary={title}
              secondary={subtitle}
              key={id}
              value={participationPercentage}
              slotProps={participationItemSlotProps}
            >
              {isItemExpanded => (
                <ParticipationList
                  depth={depth + 1}
                  surveyId={surveyId}
                  parentId={
                    dimension === SegmentType.SEGMENTATION_GROUPS
                      ? parentId
                      : id
                  }
                  page={1}
                  order={order}
                  dimension={dimension}
                  limit={childrenAmount}
                  expanded={isItemExpanded}
                />
              )}
            </ParticipationExpandableItem>
          );
        }

        return (
          <ParticipationItem
            key={id}
            primary={title}
            secondary={subtitle}
            value={participationPercentage}
            slotProps={participationItemSlotProps}
          />
        );
      },
    ) ?? [];

  return (
    <>
      {isLoading && <ParticipationItemSkeleton />}
      <Collapse
        in={expanded && isSuccess && !!data?.count}
        timeout="auto"
        unmountOnExit
      >
        {depth < 2 && (
          <ListWithDivider
            sx={{
              ...(depth === 1 && {
                bgcolor: theme => theme.palette.new.background.layout.default,
                m: 2,
              }),
              opacity: isPreviousData ? 0.5 : 1,
            }}
            items={items}
          />
        )}
        {depth >= 2 && <MuiList sx={{ pl: 2 }}>{items}</MuiList>}
      </Collapse>
      {isSuccess && !data?.count && (
        <Collapse in={expanded}>
          <Stack sx={{ alignItems: 'center', gap: 1, p: 2 }}>
            <Typography variant="h6">{t('NOT_ENOUGH_DATA_TITLE')}</Typography>
            <Typography variant="body1">
              {t('NOT_ENOUGH_DATA_DESCRIPTION')}
            </Typography>
          </Stack>
        </Collapse>
      )}
    </>
  );
};

export default ParticipationList;
