import {
  boats,
  removeFishingRod,
  giveFishingRod,
  getFishingRodEnchantments,
} from "./boats.js";
import * as server from "@minecraft/server";
import { system } from "@minecraft/server";

const world = server.world;

const cooldowns = {}; // Cooldowns object to store per-player and per-boat cooldowns
const activeBoat = {}; // Object to track the currently displayed boat cooldown per player
const playerBoatStatus = {}; // Track which boat a player is currently in
const remainingCooldowns = {}; // Track remaining cooldown times for each player and boat

// Function to display cooldown in the action bar
export function displayCooldown(player, remainingTime, boatId) {
  try {
    const playerId = player?.nameTag;
    const boatIdChecker =
      player?.getComponent("riding")?.entityRidingOn?.typeId;
    if (boatIdChecker) {
      if (remainingTime != 1) {
        player.onScreenDisplay.setActionBar(
          `Cooldown: ${remainingTime} seconds`
        );
      } else {
        player.onScreenDisplay.setActionBar(
          `Cooldown: ${remainingTime} second`
        );
      }
    }
  } catch {}
}

// Function to clear the action bar
export function clearActionBar(player) {
  player.onScreenDisplay.setActionBar("");
  player?.removeEffect("night_vision");
}

// Function to check if the player is currently in a boat and resume showing cooldown if needed
export function checkAndResumeCooldown(player) {
  const playerId = player?.nameTag;
  const currentBoatId = playerBoatStatus[playerId];

  // Ensure cooldowns object is initialized
  if (
    currentBoatId &&
    cooldowns[playerId] &&
    cooldowns[playerId][currentBoatId]
  ) {
    const remainingTime = remainingCooldowns[playerId]?.[currentBoatId];
    if (remainingTime) {
      displayCooldown(player, remainingTime, currentBoatId);
    }
  }
}

// Activate boat ability with cooldown and action bar display
export function activateBoatAbility(player, boatId, boatEntity) {
  if (!player || !boatId) {
    //world.sendMessage("§cNo valid player or boat found.");
    return;
  }

  const boat = boats[boatId];
  const playerUsed = player;
  const playerId = player?.nameTag;

  // Initialize the player's cooldowns and active boat tracking if not present
  if (!cooldowns[playerId]) {
    cooldowns[playerId] = {};
    remainingCooldowns[playerId] = {}; // Initialize remaining cooldowns for the player
  }

  // Check if the specific boat for this player is on cooldown
  if (cooldowns[playerId][boatId]) {
    if (!playerUsed.hasTag("fishingTime")) {
      world.sendMessage("§cPlease wait to use the ability again.");
    }
    return;
  }

  if (boat && boat.activate) {
    // Delay before activating the ability and starting cooldown
    const delay = boat.delay * 20; // Convert ticks to seconds

    boat.activate(player); // Activate the boat ability

    cooldowns[playerId][boatId] = true;

    system.runTimeout(() => {
      // Track the player's current boat
      playerBoatStatus[playerId] = boatId;

      // Get the boat's specific cooldown (default to 10 seconds if not specified)
      const boatCooldown = boat.cooldown || 10;
      let remainingTime = remainingCooldowns[playerId][boatId] || boatCooldown;

      // Set this boat as the currently active boat for displaying cooldown
      activeBoat[playerId] = boatId;

      // Display the initial cooldown in the player's action bar
      try {
        displayCooldown(player, remainingTime, boatId);
      } catch {}

      // Update the cooldown in the action bar every second
      const intervalId = system.runInterval(() => {
        remainingTime--;

        // Only update the action bar if the player is in the current boat
        if (remainingTime > 0) {
          if (playerBoatStatus[playerId] === boatId) {
            displayCooldown(player, remainingTime, boatId);
          }
        } else {
          // Cooldown finished, clear the action bar if this was the active boat
          if (activeBoat[playerId] === boatId) {
            clearActionBar(player);
          }

          // Reset the cooldown for this specific boat
          cooldowns[playerId][boatId] = false;
          remainingCooldowns[playerId][boatId] = undefined; // Clear remaining time
          system.clearRun(intervalId);
        }

        // Store the remaining time for the boat
        remainingCooldowns[playerId][boatId] = remainingTime;
      }, 20); // Update every second (20 ticks = 1 second)
    }, delay); // Apply the delay before activating the ability
  } else {
    world.sendMessage("§cThis boat has no Special Ability.");
  }
}

// Activate boat cooldown and action bar display
export function activateBoatCooldown(player, boatId) {
  if (!player || !boatId) {
    //world.sendMessage("§cNo valid player or boat found.");
    return;
  }

  const boat = boats[boatId];
  const playerId = player?.nameTag;

  // Initialize the player's cooldowns and active boat tracking if not present
  if (!cooldowns[playerId]) {
    cooldowns[playerId] = {};
    remainingCooldowns[playerId] = {}; // Initialize remaining cooldowns for the player
  }

  // Check if the specific boat for this player is on cooldown
  if (cooldowns[playerId][boatId]) {
    world.sendMessage("§cPlease wait to use the ability again.");
    return;
  }

  if (boat) {
    // Delay before activating the ability and starting cooldown
    const delay = boat.delay * 20; // Convert ticks to seconds
    //boat.activate(player); // Activate the boat ability

    // Start the cooldown for this boat for this player
    cooldowns[playerId][boatId] = true;

    system.runTimeout(() => {
      // Track the player's current boat
      playerBoatStatus[playerId] = boatId;

      // Get the boat's specific cooldown (default to 10 seconds if not specified)
      const boatCooldown = boat.cooldown || 10;
      let remainingTime = remainingCooldowns[playerId][boatId] || boatCooldown;

      // Set this boat as the currently active boat for displaying cooldown
      activeBoat[playerId] = boatId;

      // Display the initial cooldown in the player's action bar
      displayCooldown(player, remainingTime, boatId);

      // Update the cooldown in the action bar every second
      const intervalId = system.runInterval(() => {
        remainingTime--;

        // Only update the action bar if the player is in the current boat
        if (remainingTime > 0) {
          if (playerBoatStatus[playerId] === boatId) {
            displayCooldown(player, remainingTime, boatId);
          }
        } else {
          // Cooldown finished, clear the action bar if this was the active boat
          if (activeBoat[playerId] === boatId) {
            clearActionBar(player);
          }

          // Reset the cooldown for this specific boat
          cooldowns[playerId][boatId] = false;
          remainingCooldowns[playerId][boatId] = undefined; // Clear remaining time
          system.clearRun(intervalId);
        }

        //Ending cooldown
        if (remainingTime <= 0) {
          player?.setProperty("pc:standing_seat", false);
        }

        // Store the remaining time for the boat
        remainingCooldowns[playerId][boatId] = remainingTime;
      }, 20); // Update every second (20 ticks = 1 second)
    }, delay); // Apply the delay before activating the ability
  } else {
    world.sendMessage("§cThis boat has no Special Ability.");
  }
}

// Handle player leaving a boat
export function handlePlayerLeaveBoat(player) {
  const playerId = player?.nameTag;
  player?.setProperty("pc:standing_seat", false);
  player?.removeEffect("water_breathing");
  player?.removeEffect("resistance");
  player?.removeEffect("night_vision");
  player?.runCommandAsync(
    `/tag @e[r=15, type=pc:flyingboat, c=1] remove descentActive`
  );
  player?.runCommandAsync(
    `/effect @e[type=pc:flyingboat, c=1] clear slow_falling`
  );
  player?.runCommandAsync(`/effect @s clear night_vision`);
  player?.runCommandAsync(`/fog @s remove submarine`);
  player.setDynamicProperty(`nightvision`, false);

  if (player?.hasTag("fishingTime")) {
    removeFishingRod(player);
  }

  // Clear the action bar when the player leaves the boat
  clearActionBar(player);

  // Remove the player's active boat status
  delete playerBoatStatus[playerId];
}

// Handle player entering a boat
export function handlePlayerEnterBoat(player, boatId) {
  const playerId = player?.nameTag;

  // Set the current boat the player is in
  playerBoatStatus[playerId] = boatId;

  if (boatId === "pc:turtleboat") {
    player?.setProperty("pc:standing_seat", true);
  }
  if (boatId === "pc:pirateboat") {
    player?.setProperty("pc:standing_seat", true);
  }
  if (boatId === "pc:ghostboat") {
    player?.setProperty("pc:standing_seat", true);
  }

  if (player?.hasTag("fishingTime")) {
    giveFishingRod(player);
  }

  // Check if the boat has the skin_id component and its value is 1
  const boat = player?.getComponent("riding")?.entityRidingOn;
  if (!boat) {
    return;
  }
  if (boat?.hasTag("submarineOn")) {
    player?.runCommandAsync(`/fog @s push pc:submarine_fog submarine`);
    // Give the player water breathing effect if skin_id is 1
    player?.addEffect("water_breathing", 999999, {
      amplifier: 245,
      showParticles: false,
    });
  }

  // Check and resume cooldown if necessary
  checkAndResumeCooldown(player);
}

let playerBoatStatus2 = {}; // Store player boat status

system.runInterval(() => {
  world.getAllPlayers().forEach((player) => {
    try {
      const playerName = player?.nameTag;
      const boatId = player?.getComponent("riding")?.entityRidingOn?.typeId;

      // For test
      // player.setDynamicProperty(`nightvision`, false);

      if (boatId) {
        if (
          !playerBoatStatus2[playerName] ||
          playerBoatStatus2[playerName] !== boatId
        ) {
          //world.sendMessage(`${playerName} entered a boat: ${boatId}`);
          playerBoatStatus2[playerName] = boatId; // Update the boat status
          handlePlayerEnterBoat(player, boatId);
        }
      } else if (playerBoatStatus2[playerName]) {
        //world.sendMessage(`${playerName} left the boat.`);
        handlePlayerLeaveBoat(player);
        delete playerBoatStatus2[playerName]; // Remove the player from the status
      }
    } catch {}
  });
}, 20); // Run every second (20 ticks)
