import StateCard from '@design-system/StateCard';
import { List } from '@mui/material';

import { ParticipationItemSkeleton } from '../../../Participation';
import { type ParticipationItem } from '../../../types';
import ParticipationListItem from '../ParticipationListItem';

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

const SKELETON_COUNT = 5;

const ParticipationList = ({
  items,
  isLoading = false,
  isPreviousData = false,
  noDataMessage,
  emptyState,
  formatRatioLabel,
  renderChildren,
  depth = 0,
}: ParticipationListProps) => {
  if (isLoading && !isPreviousData) {
    return (
      <List disablePadding>
        {Array.from({ length: SKELETON_COUNT }).map((_, i) => (
          <ParticipationItemSkeleton key={i} />
        ))}
      </List>
    );
  }

  if (!items || items.length === 0) {
    return (
      <StateCard
        title={emptyState.title}
        description={emptyState.description}
      />
    );
  }

  return (
    <List
      disablePadding
      sx={{ opacity: isPreviousData ? 0.5 : 1, transition: 'opacity 0.2s' }}
    >
      {items.map((item: ParticipationItem, index) => (
        <ParticipationListItem
          key={item.id}
          primary={item.title}
          secondary={item.subtitle}
          value={item.participationPercentage}
          ratioLabel={formatRatioLabel(
            item.completedReviews,
            item.totalReviews,
          )}
          noDataMessage={noDataMessage}
          isEmpty={item.totalReviews === 0}
          expandable={item.hasChildren && !!renderChildren}
          depth={depth}
          isLastItem={index === items.length - 1}
          avatarSrc={item.avatarSrc}
          avatarAlt={item.avatarAlt}
        >
          {item.hasChildren && renderChildren
            ? (isExpanded: boolean) => renderChildren(item, isExpanded)
            : undefined}
        </ParticipationListItem>
      ))}
    </List>
  );
};

export default ParticipationList;
