import { Layout, Txt, makeScene2D } from "@motion-canvas/2d";
import {
  Direction,
  all,
  beginSlide,
  createRef,
  makeRef,
  slideTransition,
  waitFor,
} from "@motion-canvas/core";
import { theme } from "../theme";
import { PEOPLE, Person } from "../components/person";
import { CardI, birthdayCardsFor } from "./birthday_letters";

export default makeScene2D(function* (view) {
  const date = createRef<Txt>();
  const people: Person[] = [];
  const peopleLayout: Layout[] = [];
  const peopleText: Txt[] = [];

  view.add(
    <Layout direction="column" gap={15} layout>
      <Txt
        fontSize={30}
        fontFamily={theme.font}
        fill={theme.text.hex}
        ref={date}
      />

      <Layout direction="row" gap={15}>
        {PEOPLE.map((person, i) => (
          <Layout
            ref={makeRef(peopleLayout, i)}
            alignItems="center"
            direction="column"
            gap={100}
          >
            <Person ref={makeRef(people, i)} person={person} />
            <Txt
              textAlign="center"
              ref={makeRef(peopleText, i)}
              fontSize={0}
              fontFamily={theme.font}
              fill={theme.text.hex}
            />
          </Layout>
        ))}
      </Layout>
    </Layout>,
  );
  yield* all(slideTransition(Direction.Right));

  const cards = birthdayCardsFor(PEOPLE);

  for (let i = 1; i <= 365 + 1; i++) {
    const day = new Date(Date.now() + i * 24 * 60 * 60 * 1000);

    yield* waitFor(0.01);
    yield date().text(day.toDateString());

    const peoplesBirthday = cards
      .map((x, i) => [x, i] as [CardI, number])
      .filter(([{ deliverInDays }]) => deliverInDays === i)
      .map(([_, i]) => i);

    yield* all(
      ...peoplesBirthday.map((p) => {
        const text = peopleText[p];
        return all(text.text("🗓️🎂", 0), text.fontSize(50, 0.5));
      }),
    );

    yield* all(
      ...peoplesBirthday.map((p) => {
        const layout = peopleLayout[p];
        return layout.gap(0, 0.5);
      }),
    );

    yield* all(
      ...peoplesBirthday.map((p) => {
        const person = people[p];
        const text = peopleText[p];
        return all(
          text.opacity(0, 0.5),
          text.fontSize(0, 0.5),
          person.emit(":(", 0.8, false),
        );
      }),
    );
  }

  yield* beginSlide("See their reactions");
  yield* all(
    date().fontSize(0, 0.5),
    date().opacity(0, 0.65),
    ...people.map((person) => person.opacity(0, 0.5)),
  );
});
