import { type FC } from 'react';

import { groupBy } from 'lodash-es';
import Stack from '@material-hu/mui/Stack';

import useEvents from 'src/hooks/queryHooks/events';
import { EventTabs, EventTimeRange, InvitationStatus } from 'src/types/events';
import { useLokaliseTranslation } from 'src/utils/i18n';

import EmptyState from '../../components/EmptyState';
import EventsSkeleton from '../../components/skeleton/EventsSkeleton';

import EventsByDate from './EventsByDate';

export const MyEvents: FC = () => {
  const { t } = useLokaliseTranslation('events');

  const {
    data: groups = {},
    isLoading,
    isSuccess,
  } = useEvents({
    pagination: { limit: 500, page: 0 },
    timeRange: EventTimeRange.UPCOMING,
    onlyInvited: true,
    invitationStatus: [InvitationStatus.ACCEPTED, InvitationStatus.MAY_ASSIST],
    useQueryOptions: {
      select: r =>
        groupBy(r.data.items, e => new Date(e.startDateTime).toDateString()),
    },
  });

  const groupKeys = Object.keys(groups);

  if (isLoading) return <EventsSkeleton eventGroups={2} />;

  return (
    <Stack>
      {isSuccess && groupKeys.length === 0 && (
        <EmptyState
          titleProps={{
            title: t('NO_NEXT_EVENTS'),
            description: t('EVENTS_WILL_BE_LISTED_HERE'),
          }}
        />
      )}
      <EventsByDate
        eventsByDate={groups}
        source={EventTabs.MY_EVENTS_TAB}
      />
    </Stack>
  );
};

export default MyEvents;
