/**
 * Childhood Activity Events
 * Learning activities for young children (ages 2-12)
 *
 * Events:
 * - learnedBike: Learning to ride a bike
 * - learnedSwim: Learning to swim
 * - childhoodActivity: General childhood activity selection
 * - learnInstrument: Learning a musical instrument
 * - playDate: Play date with another child
 */

import {
  createMessageEvent,
  createQuestionEvent,
  createAnswerOption,
  checkProbability,
  type EventResult,
  type AnswerOption,
} from '../base.js';
import type { Player } from '../../models/Player.js';
import type { Schedule } from '../../models/Person.js';
import { addFriend } from '../../services/character/character_manager.js';
import {
  getExtracurricularByTitle,
  applyForExtracurricular,
  getRandomExtracurricular,
} from '../../services/education/index.js';

/**
 * Learning to ride a bike (ages 2-4 years / 720-1460 days)
 */
export function learnedBike(player: Player, _type: 'message' | 'question' = 'message'): EventResult {
  const fname = 'learnedBike';
  const ageDays = player.character.ageDays;

  const check =
    ageDays >= 720 &&
    ageDays < 1460 &&
    !player.events.has(fname) &&
    player.character.location?.includes('home') &&
    checkProbability(1000);

  const message = 'Your parents have decided to start teaching you to ride a bike.';

  if (check) {
    player.events.add(fname);
    // Add a schedule for bike practice sessions (weekends at 10am for 4 weeks)
    const bikeSchedule: Schedule = {
      id: `bike-lessons-${player.character.id}`,
      title: 'Bike practice',
      location: 'park',
      duration: 4, // 4 sessions total
      executions: 0,
      days: {
        daysOfWeek: ['6', '7'], // Weekends only
        hour: 10,
      },
    };
    player.character.schedules = player.character.schedules ?? [];
    player.character.schedules.push(bikeSchedule);
  }

  return createMessageEvent(fname, message, player, check);
}

/**
 * Learning to swim (ages 4-6 years / 1460-2190 days)
 */
export function learnedSwim(player: Player, _type: 'message' | 'question' = 'message'): EventResult {
  const fname = 'learnedSwim';
  const ageDays = player.character.ageDays;

  const check =
    ageDays >= 1460 &&
    ageDays < 2190 &&
    !player.events.has(fname) &&
    player.character.location?.includes('home') &&
    checkProbability(1000);

  const message = 'Your parents have signed you up for swimming lessons!';

  if (check) {
    player.events.add(fname);
    // Add a schedule for swimming lessons (Saturdays at 9am for 8 weeks)
    const swimSchedule: Schedule = {
      id: `swim-lessons-${player.character.id}`,
      title: 'Swimming lessons',
      location: 'pool',
      duration: 8, // 8 sessions total
      executions: 0,
      days: {
        daysOfWeek: ['6'], // Saturdays only
        hour: 9,
      },
    };
    player.character.schedules = player.character.schedules ?? [];
    player.character.schedules.push(swimSchedule);
  }

  return createMessageEvent(fname, message, player, check);
}

/**
 * General childhood activity selection (ages 8-12)
 */
export function childhoodActivity(
  player: Player,
  type: 'message' | 'question' | 'answer' = 'message',
  response?: { option: string }
): EventResult {
  const fname = 'childhoodActivity';
  const ageYears = player.character.ageYears;

  const check =
    !player.askedQuestions.has(fname) &&
    ageYears >= 8 &&
    ageYears < 13 &&
    checkProbability(1000);

  const message = 'Your parents want you to take on a new activity, what would you like to learn?';
  const answerOptions = ['Learn Instrument', 'Dance Class', 'Sports Team', 'None'];

  if (type !== 'answer') {
    return createQuestionEvent(fname, message, player, check, { answerOptions });
  } else if (type === 'answer' && response) {
    player.askedQuestions.add(fname);
    if (response.option === 'Dance Class') {
      const dance = getExtracurricularByTitle('Dance Class');
      if (dance) {
        applyForExtracurricular(player, dance.id);
        player.messageQueue.push('You signed up for dance classes!');
      }
    } else if (response.option === 'Sports Team') {
      // Pick a random sport
      const sports = ['Baseball', 'Basketball', 'Soccer', 'Football'];
      const randomSport = sports[Math.floor(Math.random() * sports.length)];
      const sport = getExtracurricularByTitle(randomSport);
      if (sport) {
        applyForExtracurricular(player, sport.id);
        player.messageQueue.push(`You joined the ${randomSport} team!`);
      }
    }
    // Learn Instrument will be handled by the learnInstrument event
  }

  return null;
}

/**
 * Learning a musical instrument (ages 10-17)
 */
export function learnInstrument(
  player: Player,
  type: 'message' | 'question' | 'answer' = 'message',
  response?: { option: string }
): EventResult {
  const fname = 'learnInstrument';
  const ageYears = player.character.ageYears;

  const check =
    !player.askedQuestions.has(fname) &&
    player.askedQuestions.has('childhoodActivity') &&
    (player.character.activities?.length ?? 0) === 0 &&
    ageYears >= 10 &&
    ageYears < 18 &&
    checkProbability(1000);

  const message = 'What instrument would you like to learn?';
  const answerOptions = ['Piano', 'Guitar', 'Violin', 'Drums', 'None'];

  if (type !== 'answer') {
    return createQuestionEvent(fname, message, player, check, { answerOptions });
  } else if (type === 'answer' && response) {
    player.askedQuestions.add(fname);
    if (response.option !== 'None') {
      const instrument = getExtracurricularByTitle(response.option);
      if (instrument) {
        applyForExtracurricular(player, instrument.id);
        player.messageQueue.push(`You started learning ${response.option}!`);
      }
    }
  }

  return null;
}

/**
 * Play date with another child (ages 4-7)
 */
export function playDate(
  player: Player,
  type: 'message' | 'question' | 'answer' = 'message',
  response?: { option: string }
): EventResult {
  const fname = 'playDate';
  const ageYears = player.character.ageYears;

  const check =
    !player.askedQuestions.has(fname) &&
    ageYears >= 4 &&
    ageYears < 8 &&
    checkProbability(100);

  const message = 'Your parents have arranged a play date for you with another kid, how does it go?';
  const answerOptions: (string | AnswerOption)[] = [
    'It goes well',
    createAnswerOption("You can't wait to hang out again!", '', 0, 3),
    'You and them do not get along.',
  ];

  if (type !== 'answer') {
    return createQuestionEvent(fname, message, player, check, {
      answerOptions: answerOptions.map((opt) =>
        typeof opt === 'string' ? opt : opt.option
      ),
      characters: [player.character],
      image: 'https://images.unsplash.com/photo-1578328819058-b69f3a3b0f6b?w=800',
    });
  } else if (type === 'answer' && response) {
    player.askedQuestions.add(fname);

    if (response.option === 'It goes well') {
      addFriend(player, player.character.sex === 'Male' ? 'Female' : 'Male', 'similar');
      player.messageQueue.push('You have made a new friend!');
    } else if (response.option === "You can't wait to hang out again!") {
      addFriend(player, player.character.sex === 'Male' ? 'Female' : 'Male', 'similar');
      player.character.social = (player.character.social ?? 0) + 10;
      player.messageQueue.push('You love making friends!');
    } else {
      player.character.social = (player.character.social ?? 0) - 10;
      player.messageQueue.push('Your playdate did not go well');
    }
  }

  return null;
}
