import React from 'react';

import { addDays, format } from 'date-fns';

import { getCreatorBirthdaysByRange } from '@/services/creators';
import { getEventsByDate } from '@/services/events';
import type { HomepageCollectionTextFields } from '@/services/homeCollections';

import { formatEventShortDate } from '@/components/creators/creatorEventFormatting';
import { toBudapestDate } from '@/utils/eventHelpers';

import { BirthdayRangeDay, TimelyProgramItem } from '@/types/Birthday';
import { Event } from '@/types/Events';

import HomepageBirthdayCreatorsClient from './HomepageBirthdayCreatorsClient';
import { getBudapestDateParts, toIsoDate } from './birthdayDateUtils';

interface HomepageBirthdayCreatorsProps {
  locale: string;
  textFields?: HomepageCollectionTextFields | null;
}

const DAY_WINDOW = 30;

const toEventDateIso = (event: Event) => format(toBudapestDate(event.kezdete), 'yyyy-MM-dd');

const mapEventToTimelyProgram = (event: Event, locale: string): TimelyProgramItem => {
  return {
    id: `event-${event.id}`,
    dateIso: toEventDateIso(event),
    dateLabel: formatEventShortDate(event, locale),
    event,
  };
};

const HomepageBirthdayCreators: React.FC<HomepageBirthdayCreatorsProps> = async ({
  locale,
  textFields,
}) => {
  const todayParts = getBudapestDateParts();
  const todayIso = toIsoDate(todayParts);
  const todayDate = new Date(todayParts.year, todayParts.month - 1, todayParts.day, 12, 0, 0, 0);

  let preloadedBirthdays: BirthdayRangeDay[] = [];
  let preloadedPrograms: TimelyProgramItem[] = [];

  try {
    const fromDate = format(addDays(todayDate, -DAY_WINDOW), 'yyyyMMdd');
    const toDate = format(addDays(todayDate, DAY_WINDOW), 'yyyyMMdd');
    preloadedBirthdays = await getCreatorBirthdaysByRange({ fromDate, toDate }, { locale });
    const events = await getEventsByDate({
      fromDate,
      toDate,
    });

    preloadedPrograms = events.map((event) => mapEventToTimelyProgram(event, locale));
  } catch (error) {
    console.error('Error loading timely program feed:', error);
  }

  return (
    <HomepageBirthdayCreatorsClient
      initialDateIso={todayIso}
      preloadedBirthdays={preloadedBirthdays}
      preloadedPrograms={preloadedPrograms}
      textFields={textFields}
    />
  );
};

export default HomepageBirthdayCreators;
