import { type InfiniteData } from 'react-query';

import { type AxiosResponse } from 'axios';
import { format, parseISO } from 'date-fns';
import i18next from 'i18next';

import {
  type CelebrationListResponse,
  CelebrationType,
  type CelebrationUser,
} from 'src/types/upcomingCelebrations';
import { type MeUser } from 'src/types/user';

import { getCurrentLocale } from './locale';

export const getResults = (
  data: InfiniteData<AxiosResponse<CelebrationListResponse>> | undefined,
  filter: CelebrationType,
): CelebrationUser[] =>
  data?.pages?.flatMap(page =>
    page?.data?.items.reduce((res: CelebrationUser[], current) => {
      if (current.isUserAnniversary && current.isUserBirthday) {
        const anniversary = {
          ...current,
          isUserAnniversary: true,
          isUserBirthday: false,
        };
        const birthday = {
          ...current,
          isUserAnniversary: false,
          isUserBirthday: true,
        };

        if (filter === CelebrationType.ALL) {
          return [...res, anniversary, birthday];
        }

        if (filter === CelebrationType.BIRTHDAY) {
          return [...res, birthday];
        }

        return [...res, anniversary];
      }

      return [...res, current];
    }, []),
  ) || [];

export const getDateTitle = (date: string, user?: MeUser): string => {
  if (!user || !date) return '';

  try {
    const locale = getCurrentLocale(user);

    let dateTitle = '';
    const formatString = locale.code?.startsWith('en') ? 'MMM d' : 'd MMM';
    const dateFormatted = format(parseISO(date), formatString, { locale });
    try {
      dateTitle = i18next
        .t('celebrations:date_celebration', {
          date: dateFormatted,
        })
        .toUpperCase();
    } catch (err) {
      dateTitle = '';
    }

    return date === format(new Date(), 'yyyy-MM-dd')
      ? `${dateTitle} (${i18next.t('today')})`
      : dateTitle;
  } catch (err) {
    return '';
  }
};

const getRandomIndex = (array: string[]) =>
  Math.floor(Math.random() * array.length);

const birthdayMessages = [
  'birthday_msg1',
  'birthday_msg2',
  'birthday_msg3',
  'birthday_msg4',
  'birthday_msg5',
];

const anniversaryMessages = ['anniversary_msg1', 'anniversary_msg2'];

export const getRandomMessage = (
  isAnniversary?: boolean,
  isBirthday?: boolean,
) => {
  if (isBirthday) return birthdayMessages[getRandomIndex(birthdayMessages)];
  if (isAnniversary)
    return anniversaryMessages[getRandomIndex(anniversaryMessages)];
  return '';
};
