package org.server_info.MOTD

import org.bukkit.ChatColor
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player

@Suppress("DEPRECATION")
class MOTDCommand(private val plugin: MOTD) : CommandExecutor {
    override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
        if (args.isEmpty()) {
            // Display help
            displayHelp(sender)
            return true
        }

        when (args[0].lowercase()) {
            "refresh" -> {
                if (!sender.hasPermission("motd.refresh")) {
                    sender.sendMessage("${ChatColor.RED}You don't have permission to use this command.")
                    return true
                }

                sender.sendMessage("${ChatColor.YELLOW}Setting a new random quote...")
                plugin.updateServerMOTD()
                sender.sendMessage("${ChatColor.GREEN}MOTD has been updated!")
                return true
            }

            "reload" -> {
                if (!sender.hasPermission("motd.reload")) {
                    sender.sendMessage("${ChatColor.RED}You don't have permission to use this command.")
                    return true
                }

                plugin.reloadQuotes()
                plugin.startQuoteTask()
                sender.sendMessage("${ChatColor.GREEN}MOTD quotes reloaded from config!")
                return true
            }

            "list" -> {
                if (!sender.hasPermission("motd.list")) {
                    sender.sendMessage("${ChatColor.RED}You don't have permission to use this command.")
                    return true
                }

                listQuotes(sender)
                return true
            }

            "add" -> {
                if (!sender.hasPermission("motd.edit")) {
                    sender.sendMessage("${ChatColor.RED}You don't have permission to use this command.")
                    return true
                }

                if (args.size < 2) {
                    sender.sendMessage("${ChatColor.RED}Usage: /motd add <text> [color]")
                    return true
                }

                // Extract text from arguments (can contain spaces)
                val text = args.slice(1 until if (args.size > 2 && args.last().matches(Regex("&[0-9a-fA-Fk-oK-OrR]"))) args.size - 1 else args.size).joinToString(" ")

                // Extract color if provided
                val colorCode = if (args.size > 2 && args.last().matches(Regex("&[0-9a-fA-Fk-oK-OrR]"))) {
                    args.last().replace('&', '§')
                } else {
                    "§f" // Default to white
                }

                if (plugin.addQuote(text, colorCode)) {
                    sender.sendMessage("${ChatColor.GREEN}Added new quote: ${colorCode}$text")
                } else {
                    sender.sendMessage("${ChatColor.RED}Failed to add quote. Make sure the text is not empty.")
                }

                return true
            }

            "remove" -> {
                if (!sender.hasPermission("motd.edit")) {
                    sender.sendMessage("${ChatColor.RED}You don't have permission to use this command.")
                    return true
                }

                if (args.size < 2 || args[1].toIntOrNull() == null) {
                    sender.sendMessage("${ChatColor.RED}Usage: /motd remove <index>")
                    sender.sendMessage("${ChatColor.YELLOW}Use /motd list to view quote indices.")
                    return true
                }

                val index = args[1].toInt() - 1 // Convert to 0-based index

                if (plugin.removeQuote(index)) {
                    sender.sendMessage("${ChatColor.GREEN}Successfully removed quote #${index + 1}.")
                } else {
                    sender.sendMessage("${ChatColor.RED}Invalid quote index. Use /motd list to view valid indices.")
                }

                return true
            }

            "edit" -> {
                if (!sender.hasPermission("motd.edit")) {
                    sender.sendMessage("${ChatColor.RED}You don't have permission to use this command.")
                    return true
                }

                if (args.size < 3 || args[1].toIntOrNull() == null) {
                    sender.sendMessage("${ChatColor.RED}Usage: /motd edit <index> <text> [color]")
                    sender.sendMessage("${ChatColor.YELLOW}Use /motd list to view quote indices.")
                    return true
                }

                val index = args[1].toInt() - 1 // Convert to 0-based index

                // Extract text from arguments (can contain spaces)
                val text = args.slice(2 until if (args.size > 3 && args.last().matches(Regex("&[0-9a-fA-Fk-oK-OrR]"))) args.size - 1 else args.size).joinToString(" ")

                // Extract color if provided
                val colorCode = if (args.size > 3 && args.last().matches(Regex("&[0-9a-fA-Fk-oK-OrR]"))) {
                    args.last().replace('&', '§')
                } else {
                    // Keep existing color if not specified
                    val quotes = plugin.getCurrentQuotes()
                    if (index >= 0 && index < quotes.size) {
                        quotes[index].color
                    } else {
                        "§f" // Default to white
                    }
                }

                if (plugin.editQuote(index, text, colorCode)) {
                    sender.sendMessage("${ChatColor.GREEN}Successfully edited quote #${index + 1}.")
                } else {
                    sender.sendMessage("${ChatColor.RED}Failed to edit quote. Check the index and make sure the text is not empty.")
                }

                return true
            }

            "gui" -> {
                if (!sender.hasPermission("motd.gui")) {
                    sender.sendMessage("${ChatColor.RED}You don't have permission to use this command.")
                    return true
                }

                if (sender !is Player) {
                    sender.sendMessage("${ChatColor.RED}This command can only be used by players.")
                    return true
                }

                // Open the GUI for the player
                MOTDGuiHandler(plugin).openQuotesGui(sender)
                return true
            }

            else -> {
                displayHelp(sender)
                return true
            }
        }
    }

    private fun displayHelp(sender: CommandSender) {
        sender.sendMessage("${ChatColor.GOLD}==== MOTD Quote Plugin ====")
        sender.sendMessage("${ChatColor.YELLOW}/motd refresh ${ChatColor.WHITE}- Set a new random quote")
        sender.sendMessage("${ChatColor.YELLOW}/motd reload ${ChatColor.WHITE}- Reload quotes from config")
        sender.sendMessage("${ChatColor.YELLOW}/motd list ${ChatColor.WHITE}- List all available quotes")
        sender.sendMessage("${ChatColor.YELLOW}/motd add <text> [color] ${ChatColor.WHITE}- Add a new quote")
        sender.sendMessage("${ChatColor.YELLOW}/motd remove <index> ${ChatColor.WHITE}- Remove a quote")
        sender.sendMessage("${ChatColor.YELLOW}/motd edit <index> <text> [color] ${ChatColor.WHITE}- Edit a quote")
        sender.sendMessage("${ChatColor.YELLOW}/motd gui ${ChatColor.WHITE}- Open quote management GUI")
        sender.sendMessage("${ChatColor.AQUA}Colors: &0-&9, &a-&f, &k-&o, &r (Example: &e for yellow)")
    }

    private fun listQuotes(sender: CommandSender) {
        val quotes = plugin.getCurrentQuotes()

        if (quotes.isEmpty()) {
            sender.sendMessage("${ChatColor.YELLOW}No quotes are currently configured.")
            return
        }

        sender.sendMessage("${ChatColor.GOLD}==== MOTD Quotes (${quotes.size}) ====")

        // List all quotes with their indices
        quotes.forEachIndexed { index, quoteItem ->
            // Show the quote with its actual color
            sender.sendMessage("${ChatColor.GREEN}${index + 1}. ${quoteItem.color}${quoteItem.text}${ChatColor.GRAY} [${quoteItem.color.replace('§', '&')}]")
        }
    }
}