import { FC } from 'react';
import { FormProvider, UseFormReturn } from 'react-hook-form';
import { useQuery } from 'react-query';

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

import HuAlert from '@material-hu/components/design-system/Alert';
import HuCircularProgress from '@material-hu/components/design-system/ProgressIndicators/Spinner';

import { getSegmentationGroups } from 'src/services/segmentations';
import { Event } from 'src/types/events';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { eventsKeys } from '../queries';

import { SegmentationsContent } from './SegmentationsContent';

type Props = {
  event: Event;
  form: UseFormReturn<any>;
};

export type SegmentationDataMapped = {
  id: number;
  name: string;
  items: {
    id: number;
    name: string;
    groupId: number;
  }[];
};

const SegmentationsData: FC<Props> = ({ event, form }) => {
  const { t } = useLokaliseTranslation('audience');

  const { data: segmentations, isLoading } = useQuery(
    eventsKeys.segmentations(event.id),
    () => getSegmentationGroups(),
    {
      select: response =>
        response.data.map(group => ({
          id: group.id,
          name: group.name,
          items: group.items.map(item => ({
            id: item.id,
            name: item.name,
            groupId: item.groupId,
          })),
        })),
    },
  );

  return (
    <FormProvider {...form}>
      <Stack sx={{ gap: 2 }}>
        {isLoading && <HuCircularProgress centered />}
        {!isLoading && segmentations && segmentations.length > 0 && (
          <SegmentationsContent segmentations={segmentations!} />
        )}
        {!isLoading && !segmentations?.length && (
          <HuAlert
            severity="info"
            title={t('segmentations.no_segmentation_groups')}
          />
        )}
      </Stack>
    </FormProvider>
  );
};

export default SegmentationsData;
