/**
 * Major Life Crisis Events
 * Severe negative events that significantly impact the player's life
 *
 * NOTE: unexpectedBill exists in adulthood/lifeEvents.ts
 *
 * Events:
 * - houseFireDamage: Home fire with major damage
 * - legalTrouble: Facing legal problems requiring decisions
 * - victimOfCrime: Being robbed and feeling unsafe
 * - majorAccident: Serious accident requiring long recovery
 * - naturalDisaster: Natural disaster affecting the area
 * - carCrash: Car accident with a deer while driving (questionEvent)
 * - accountHacked: Accounts hacked with embarrassing posts
 * - funeral: Attending funeral for deceased relationship (questionEvent)
 * - murderAttempt: Extreme crime when relationship affinity is -100
 */

import {
  createMessageEvent,
  createQuestionEvent,
  createAnswerOption,
  checkProbability,
  modifyStat,
  type EventResult,
} from '../base';
import type { Player } from '../../models/Player';

/**
 * Home fire with major damage and belongings lost (ages 18-100)
 */
export function houseFireDamage(player: Player, _type: 'message' | 'question' = 'message'): EventResult {
  const fname = 'houseFireDamage';
  const ageYears = player.character.ageYears;

  const check =
    !player.events.has(fname) &&
    ageYears >= 18 &&
    ageYears <= 100 &&
    checkProbability(5000);

  const message = 'A fire damaged your home. Some of your belongings are gone forever.';

  if (check) {
    player.events.add(fname);
    if (player.character.money >= 5000) {
      player.character.money -= 5000;
    } else {
      player.character.money = 0;
      player.character.stress = (player.character.stress ?? 0) + 20;
    }
    player.character.happiness -= 45;
    player.character.stress = (player.character.stress ?? 0) + 50;
  }

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

/**
 * Facing legal problems with different handling options (ages 16-100)
 */
export function legalTrouble(
  player: Player,
  type: 'message' | 'question' | 'answer' = 'message',
  response?: { option: string }
): EventResult {
  const fname = 'legalTrouble';
  const ageYears = player.character.ageYears;

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

  const message = "You're facing legal problems. How do you handle it?";
  const answerOptions = [
    createAnswerOption('Hire expensive lawyer', '0', 0, 0, 5000),
    createAnswerOption('Public defender', '1'),
    createAnswerOption('Represent yourself', '2', 50),
  ];

  if (type !== 'answer') {
    return createQuestionEvent(fname, message, player, check, {
      answerOptions: answerOptions.map((opt) => opt.option),
    });
  } else if (type === 'answer' && response) {
    player.askedQuestions.add(fname);

    if (response.option === 'Hire expensive lawyer') {
      player.character.stress = (player.character.stress ?? 0) + 30;
      player.messageQueue.push(
        'You hired an expensive lawyer to handle your legal troubles. The cost is high, but at least you have expert representation.'
      );
    } else if (response.option === 'Public defender') {
      player.character.stress = (player.character.stress ?? 0) + 40;
      player.messageQueue.push(
        "You're using a public defender. They're overworked and you're stressed about the outcome."
      );
    } else if (response.option === 'Represent yourself') {
      player.character.stress = (player.character.stress ?? 0) + 50;
      player.messageQueue.push(
        'You decided to represent yourself in court. The stress of learning legal procedures on the fly is overwhelming.'
      );
    }
  }

  return null;
}

/**
 * Being robbed and feeling violated and unsafe (ages 14-100)
 */
export function victimOfCrime(player: Player, _type: 'message' | 'question' = 'message'): EventResult {
  const fname = 'victimOfCrime';
  const ageYears = player.character.ageYears;

  const check =
    !player.events.has(fname) &&
    ageYears >= 14 &&
    ageYears <= 100 &&
    checkProbability(5000);

  const message = 'You were robbed. You feel violated and unsafe.';

  if (check) {
    player.events.add(fname);
    if (player.character.money >= 800) {
      player.character.money -= 800;
    } else {
      player.character.money = 0;
      player.character.stress = (player.character.stress ?? 0) + 20;
    }
    player.character.happiness -= 35;
    player.character.stress = (player.character.stress ?? 0) + 60;
  }

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

/**
 * Serious accident requiring months of recovery (ages 16-100)
 */
export function majorAccident(player: Player, _type: 'message' | 'question' = 'message'): EventResult {
  const fname = 'majorAccident';
  const ageYears = player.character.ageYears;

  const check =
    !player.events.has(fname) &&
    ageYears >= 16 &&
    ageYears <= 100 &&
    checkProbability(5000);

  const message = 'You were in a serious accident. Recovery will take months.';

  if (check) {
    player.events.add(fname);
    player.character.health = modifyStat(player.character.health, -50);
    player.character.energy = modifyStat(player.character.energy, -40);
    player.character.happiness = modifyStat(player.character.happiness, -40);
  }

  return createMessageEvent(fname, message, player, check, { moneyCost: 3000 });
}

/**
 * Natural disaster hitting the area causing chaos (ages 1-100)
 */
export function naturalDisaster(player: Player, _type: 'message' | 'question' = 'message'): EventResult {
  const fname = 'naturalDisaster';
  const ageYears = player.character.ageYears;

  const check =
    !player.events.has(fname) &&
    ageYears >= 1 &&
    ageYears <= 100 &&
    checkProbability(5000);

  const message = 'A natural disaster hit your area. Everything is chaotic and scary.';

  if (check) {
    player.events.add(fname);
    player.character.stress = (player.character.stress ?? 0) + 45;
    player.character.happiness -= 30;
    if (player.character.money >= 1000) {
      player.character.money -= 1000;
    } else {
      player.character.money = 0;
      player.character.stress = (player.character.stress ?? 0) + 20;
    }
  }

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

/**
 * Car accident with a deer while driving (questionEvent)
 * Requires player can drive (age 16+)
 */
export function carCrash(
  player: Player,
  type: 'message' | 'question' | 'answer' = 'message',
  response?: { option: string }
): EventResult {
  const fname = 'carCrash';
  const ageYears = player.character.ageYears;

  // Check if player can drive (age 16+ and has a car or license)
  const canDrive = ageYears >= 16;

  const check =
    !player.askedQuestions.has(fname) &&
    canDrive &&
    checkProbability(100000);

  const message = "You're driving at night and a deer jumps in front of your car.";
  const answerOptions = [
    createAnswerOption('Swerve left', '0', 0, 5),
    createAnswerOption('Hit the brakes', '1', 0, 0, 50),
    createAnswerOption('Speed up', '2', 5),
  ];

  if (type !== 'answer') {
    return createQuestionEvent(fname, message, player, check, {
      answerOptions: answerOptions.map((opt) => opt.option),
    });
  } else if (type === 'answer' && response) {
    player.askedQuestions.add(fname);

    if (response.option === 'Swerve left') {
      player.messageQueue.push(
        "It's a quiet night and no other cars are on the road. You swerve around the deer without a scratch!"
      );
    } else if (response.option === 'Hit the brakes') {
      player.character.happiness = modifyStat(player.character.happiness, -5);
      player.messageQueue.push(
        'You slam the brakes but still hit the deer. You (and the deer) are safe, but the windshield will need some costly repairs!'
      );
    } else if (response.option === 'Speed up') {
      player.character.happiness = modifyStat(player.character.happiness, -10);
      player.character.health = modifyStat(player.character.health, -30);
      player.character.energy = modifyStat(player.character.energy, -40);
      player.character.money -= 500;
      player.messageQueue.push(
        '...Why would you speed up? You hit the deer at full speed and spent the night in the hospital.'
      );
    }
  }

  return null;
}

/**
 * Accounts hacked with embarrassing posts (ages 14-100)
 */
export function accountHacked(
  player: Player,
  _type: 'message' | 'question' = 'message'
): EventResult {
  const fname = 'accountHacked';
  const ageYears = player.character.ageYears;

  const check =
    !player.events.has(fname) &&
    ageYears >= 14 &&
    ageYears <= 100 &&
    checkProbability(1800);

  const message = 'Your accounts were hacked and embarrassing posts were made. Everyone saw.';

  if (check) {
    player.events.add(fname);
    player.character.happiness = modifyStat(player.character.happiness, -25);
    player.character.social = modifyStat(player.character.social, -25);
    player.character.stress = (player.character.stress ?? 0) + 30;
  }

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

/**
 * Attending funeral for deceased relationship (questionEvent)
 * Triggers when a relationship has passed away
 */
export function funeral(
  player: Player,
  type: 'message' | 'question' | 'answer' = 'message',
  response?: { option: string; personId?: string }
): EventResult {
  // Use full Person objects from player.r which have status property
  const fullRelationships = player.r ?? [];

  // Find deceased relationships that haven't had funerals yet
  for (const person of fullRelationships) {
    const fname = `funeral---${person.firstname}${person.lastname}`;

    if (type !== 'answer') {
      // Check if person is deceased and funeral hasn't been attended
      const isDeceased = person.status !== 'alive';
      const check = isDeceased && !player.events.has(fname);

      if (check) {
        const message = `${person.firstname} ${person.lastname} has passed away. Would you like to attend their funeral?`;
        return createQuestionEvent(fname, message, player, true, {
          answerOptions: ['Yes', 'No'],
        });
      }
    } else if (type === 'answer' && response) {
      // Handle response - check if this response is for this person's funeral
      if (response.personId === `${person.firstname}${person.lastname}`) {
        player.events.add(fname);

        if (response.option === 'Yes') {
          player.character.happiness = modifyStat(player.character.happiness, -15);
          player.character.social = modifyStat(player.character.social, -15);
          player.character.energy = modifyStat(player.character.energy, -20);
          player.messageQueue.push(
            `You attended the funeral of ${person.firstname} ${person.lastname}. It was a somber day.`
          );
        } else {
          player.messageQueue.push('You did not attend the funeral.');
        }
        return null;
      }
    }
  }

  return null;
}

/**
 * Murder attempt - extreme crime when someone hates player with -100 affinity
 * Very rare but severe consequence of extremely poor relationships
 */
export function murderAttempt(
  player: Player,
  type: 'message' | 'question' | 'answer' = 'message',
  response?: { option: string }
): EventResult {
  const fname = 'murderAttempt';
  const relationships = player.relationships ?? [];

  // Find someone who truly hates the player (affinity -100)
  const enemies = relationships.filter((p) => (p.affinity ?? 0) <= -100);

  if (enemies.length === 0) {
    return null;
  }

  const check =
    !player.askedQuestions.has(fname) &&
    enemies.length > 0 &&
    checkProbability(100000);

  if (type !== 'answer' && check) {
    const enemy = enemies[Math.floor(Math.random() * enemies.length)];
    const message = `${enemy.firstname} hates you so much they break into your house and stab you in your sleep.`;

    return createQuestionEvent(fname, message, player, true, {
      answerOptions: ['Fight back', 'Call for help', 'Play dead'],
    });
  } else if (type === 'answer' && response) {
    player.askedQuestions.add(fname);

    if (response.option === 'Fight back') {
      // Risky but could work
      if (Math.random() < 0.5) {
        player.messageQueue.push(
          'You managed to fight off your attacker! The police have been called and you are recovering in the hospital.'
        );
        player.character.health = modifyStat(player.character.health, -40);
        player.character.energy = modifyStat(player.character.energy, -35);
        player.character.happiness = modifyStat(player.character.happiness, -30);
      } else {
        player.messageQueue.push(
          'You fought back but were overpowered. You barely survived and spent weeks in the hospital.'
        );
        player.character.health = modifyStat(player.character.health, -70);
        player.character.energy = modifyStat(player.character.energy, -40);
        player.character.happiness = modifyStat(player.character.happiness, -50);
        player.character.money -= 10000;
      }
    } else if (response.option === 'Call for help') {
      player.messageQueue.push(
        'You managed to scream for help. Neighbors called the police and you were saved, though not without injury.'
      );
      player.character.health = modifyStat(player.character.health, -30);
      player.character.energy = modifyStat(player.character.energy, -40);
      player.character.happiness = modifyStat(player.character.happiness, -25);
      player.character.stress = (player.character.stress ?? 0) + 50;
    } else if (response.option === 'Play dead') {
      player.messageQueue.push(
        'You played dead and your attacker fled thinking the deed was done. Smart, but traumatizing.'
      );
      player.character.health = modifyStat(player.character.health, -20);
      player.character.happiness = modifyStat(player.character.happiness, -40);
      player.character.stress = (player.character.stress ?? 0) + 60;
    }
  }

  return null;
}
