import { useMemo } from 'react';
import { useQuery } from 'react-query';
import { useParams } from 'react-router';

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

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import { getEvent } from 'src/services/events';
import { urlToFile } from 'src/utils/files';

import NewEvent from '../../New';
import { eventsKeys } from '../../queries';
import { getImageFileCard } from '../../utils';

export const EventEdit = () => {
  const { id } = useParams();
  const eventId = Number(id);
  const HuGoThemeProvider = useHuGoTheme();

  const { data: event, isLoading } = useQuery(
    eventsKeys.event(eventId),
    () => getEvent(eventId),
    {
      enabled: !!eventId,
      select: r => r.data,
    },
  );

  const { data: imageFile, isLoading: isLoadingImage } = useQuery(
    eventsKeys.eventImage(eventId),
    () => urlToFile(event!.coverPictureUrl),
    {
      enabled: !!event?.coverPictureUrl,
    },
  );

  const eventWithFileCard = useMemo(() => {
    return {
      ...event,
      imagePreview: getImageFileCard(event, imageFile),
    };
  }, [event, imageFile]);

  if (isLoading || isLoadingImage) {
    return (
      <HuGoThemeProvider>
        <HuCircularProgress centered />
      </HuGoThemeProvider>
    );
  }

  return <NewEvent event={eventWithFileCard} />;
};

export default EventEdit;
