import { useMemo } from 'react';
import { useFormContext } from 'react-hook-form';

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

import useSegmentationGroups from 'src/hooks/queryHooks/useSegmentationGroups';
import { ColaboratorsList } from 'src/pages/dashboard/Learning/common/components/ColaboratorsList';
import { InformationRow } from 'src/pages/dashboard/Learning/common/components/InformationRow';
import { RevisionAccordion } from 'src/pages/dashboard/Learning/common/components/RevisionAccordion';
import { PathSteps } from 'src/pages/dashboard/Learning/Paths/constants';
import { type NewPathFormValues } from 'src/pages/dashboard/Learning/Paths/types';
import { type SegmentationType } from 'src/types/user';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { formatSegmentationInSections } from 'src/components/FormInputs/FormSegmentation/utils';

const RevisionSegmentation = () => {
  const { t } = useLokaliseTranslation('learning');
  const { getValues } = useFormContext<NewPathFormValues>();
  const segmentations = getValues('segmentation');

  const { userSegmentation, groupSegmentation } = segmentations || {};

  const allCollaborators = segmentations === null;

  const hasUserSegmentation = Boolean(
    userSegmentation && userSegmentation.length > 0,
  );
  const hasGroupSegmentation = Boolean(
    groupSegmentation && groupSegmentation.length > 0,
  );

  const { data: segmentationGroups = [] } =
    useSegmentationGroups<SegmentationType[]>();

  const formattedSegmentation = useMemo(
    () =>
      formatSegmentationInSections(segmentationGroups, groupSegmentation || []),
    [segmentationGroups, groupSegmentation],
  );

  return (
    <RevisionAccordion step={PathSteps.SEGMENTATION}>
      <InformationRow
        title={t(`common.segmentation_type.type`)}
        description={
          <Stack sx={{ gap: 1, maxWidth: '70%' }}>
            {allCollaborators && (
              <Typography
                variant="globalS"
                sx={{ textAlign: 'right' }}
              >
                {t(`common.colaborators.all_collaborators`)}
              </Typography>
            )}
            {hasUserSegmentation && (
              <ColaboratorsList users={userSegmentation} />
            )}
            {hasGroupSegmentation && (
              <ColaboratorsList segmentations={formattedSegmentation} />
            )}
          </Stack>
        }
      />
    </RevisionAccordion>
  );
};

export default RevisionSegmentation;
