import { Events, VoiceState, ChannelType } from "discord.js"; // Added ChannelType
import logger from "../utils/logger.js";
import { BotClient } from "../index.js"; // Assuming BotClient is exported from index

export default {
  // Use export default for ES modules
  name: Events.VoiceStateUpdate,
  execute(oldState: VoiceState, newState: VoiceState, _client: BotClient) {
    // Added types
    // Shoukaku handles voice state updates internally via its connector.
    // We don't need to manually pass the update like with Erela.js.
    // The warning about Erela.js manager not being initialized can be ignored/removed.

    // Custom logic for player cleanup based on voice state changes.
    const shoukaku = _client.shoukaku; // Access Shoukaku instance
    if (!shoukaku) {
      // Shoukaku might not be initialized yet
      logger.debug("Voice state update received, but Shoukaku is not ready yet.");
      return;
    }

    const player = shoukaku.players.get(newState.guild.id); // Get player from Shoukaku players collection
    if (!player) return; // No active player for this guild

    // Get the connection associated with the player's guild
    const connection = shoukaku.connections.get(player.guildId);
    const currentChannelId = connection?.channelId; // Get channelId from connection

    // Check if the bot was disconnected (newState has no channelId for the bot)
    // Add null check for _client.user
    if (
      _client.user &&
      newState.id === _client.user.id &&
      !newState.channelId &&
      oldState.channelId === currentChannelId
    ) {
      logger.info(
        `Bot was disconnected from voice channel ${oldState.channel?.name || oldState.channelId} in guild ${newState.guild.id}. Destroying player.`,
      );
      player.destroy(); // Use Shoukaku player's destroy method
      return; // Exit early as the player is destroyed
    }

    // Check if the bot's channel is now empty (excluding the bot itself)
    const channel = currentChannelId ? _client.channels.cache.get(currentChannelId) : undefined;

    // Ensure the channel exists, is voice-based, and the update is relevant
    if (
      channel?.isVoiceBased() &&
      (newState.channelId === currentChannelId || oldState.channelId === currentChannelId)
    ) {
      // Fetch members again to ensure freshness after the update
      const members = channel.members; // Safe to access members now
      // Add null check for _client.user
      if (_client.user && members.size === 1 && members.has(_client.user.id)) {
        logger.info(
          `Voice channel ${channel.name} (${currentChannelId}) in guild ${newState.guild.id} is now empty (only bot left). Destroying player.`,
        ); // Safe to access name
        // Optional: Add a timeout before destroying
        // setTimeout(() => {
        //     const currentChannel = _client.channels.cache.get(player.voiceChannel);
        //     const currentMembers = currentChannel?.members;
        //     if (currentMembers && currentMembers.size === 1 && currentMembers.has(_client.user.id)) {
        //         logger.info(`Timeout finished: Destroying player in empty channel ${channel.name}.`);
        //         player.destroy();
        //     } else {
        //          logger.info(`Timeout finished: Channel ${channel.name} is no longer empty. Player not destroyed.`);
        //     }
        // }, 60000); // e.g., 1 minute timeout
        player.destroy(); // Destroy immediately for now
      }
    }
  },
};
