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

import Stack from '@material-hu/mui/Stack';

import HuTitle from '@material-hu/components/design-system/Title';

import { type ReviewDetailFormQuestions } from 'src/pages/dashboard/performance/types';

import GetReviewInputComponent from '../GetReviewInputComponent';

type CompetencyGroupItemsListProps = {
  items: ReviewDetailFormQuestions[];
  answered: boolean;
  canViewGoalDetails: boolean;
  getHeaderActions?: (question: ReviewDetailFormQuestions) => ReactNode;
};

const stripTrailingAsterisks = (value: string) =>
  value.replace(/\s*\*+\s*$/u, '').trim();

const CompetencyGroupItemsList = ({
  items,
  answered,
  canViewGoalDetails,
  getHeaderActions,
}: CompetencyGroupItemsListProps) => {
  const questionTitle = stripTrailingAsterisks(items[0]?.title ?? '');
  const isAnyItemRequired = items.some(item => item.required);
  const questionTitleWithMark =
    questionTitle && isAnyItemRequired ? `${questionTitle} *` : questionTitle;

  return (
    <Stack sx={{ flexDirection: 'column', gap: 3 }}>
      {questionTitle && (
        <HuTitle
          variant="S"
          title={questionTitleWithMark}
        />
      )}
      {items.map((item, index) => (
        <GetReviewInputComponent
          canViewGoalDetails={canViewGoalDetails}
          key={item.id}
          answered={answered}
          index={index}
          {...item}
          description={item.description || undefined}
          choices={item.choices || undefined}
          headerActions={getHeaderActions?.(item)}
        />
      ))}
    </Stack>
  );
};

export default memo(CompetencyGroupItemsList);
