// Menus.kt
package com.example.cctv.menus

import org.bukkit.Bukkit
import org.bukkit.Material
import org.bukkit.entity.Player
import org.bukkit.inventory.Inventory
import org.bukkit.inventory.InventoryHolder
import org.bukkit.inventory.ItemStack
import org.bukkit.inventory.meta.ItemMeta
import java.util.*
import com.example.cctv.CctvPlugin

interface CctvMenu : InventoryHolder {
    fun open()
    fun handleClick(player: Player, item: ItemStack, slot: Int)
}

class MainMenu(private val plugin: CctvPlugin, private val player: Player) : CctvMenu {
    private val inventory: Inventory = Bukkit.createInventory(this, 27, "CCTV System")

    override fun getInventory(): Inventory = inventory

    override fun open() {
        // Create menu items
        val placeCameraItem = createItem(Material.ENDER_EYE, "§aPlace New Camera", listOf("§7Click to place a camera", "§7at your current location"))
        val viewCamerasItem = createItem(Material.SPYGLASS, "§bView Cameras", listOf("§7Click to view available cameras"))
        val manageCamerasItem = createItem(Material.REDSTONE_BLOCK, "§cManage Your Cameras", listOf("§7Click to manage your cameras"))

        // Place items in inventory
        inventory.setItem(11, placeCameraItem)
        inventory.setItem(13, viewCamerasItem)
        inventory.setItem(15, manageCamerasItem)

        // Open inventory for player
        player.openInventory(inventory)
    }

    override fun handleClick(player: Player, item: ItemStack, slot: Int) {
        when (slot) {
            11 -> {
                if (player.hasPermission("cctv.place")) {
                    player.closeInventory()
                    PlaceCameraMenu(plugin, player).open()
                } else {
                    player.sendMessage("§cYou don't have permission to place cameras.")
                }
            }
            13 -> {
                player.closeInventory()
                ViewCamerasMenu(plugin, player).open()
            }
            15 -> {
                player.closeInventory()
                ManageCamerasMenu(plugin, player).open()
            }
        }
    }

    private fun createItem(material: Material, name: String, lore: List<String>): ItemStack {
        val item = ItemStack(material)
        val meta = item.itemMeta

        meta?.setDisplayName(name)
        meta?.lore = lore

        item.itemMeta = meta
        return item
    }
}

class PlaceCameraMenu(private val plugin: CctvPlugin, private val player: Player) : CctvMenu {
    private val inventory: Inventory = Bukkit.createInventory(this, 36, "Place Camera")

    override fun getInventory(): Inventory = inventory

    override fun open() {
        // Create menu items
        for (i in 0..7) {
            val cameraItem = createItem(Material.ENDER_EYE, "§aCamera ${i + 1}", listOf("§7Click to place", "§7Camera ${i + 1} at your location"))
            inventory.setItem(10 + i, cameraItem)
        }

        val closeItem = createItem(Material.BARRIER, "§cCancel", listOf("§7Click to return to main menu"))
        inventory.setItem(31, closeItem)

        // Open inventory for player
        player.openInventory(inventory)
    }

    override fun handleClick(player: Player, item: ItemStack, slot: Int) {
        if (slot in 10..17) {
            val name = item.itemMeta?.displayName?.replace("§a", "") ?: "Camera"
            if (plugin.createCamera(player, name)) {
                player.sendMessage("§aCamera '$name' placed successfully at your location!")
            } else {
                player.sendMessage("§cFailed to place camera.")
            }
            player.closeInventory()
            MainMenu(plugin, player).open()
        } else if (slot == 31) {
            player.closeInventory()
            MainMenu(plugin, player).open()
        }
    }

    private fun createItem(material: Material, name: String, lore: List<String>): ItemStack {
        val item = ItemStack(material)
        val meta = item.itemMeta

        meta?.setDisplayName(name)
        meta?.lore = lore

        item.itemMeta = meta
        return item
    }
}

class ViewCamerasMenu(private val plugin: CctvPlugin, private val player: Player) : CctvMenu {
    private val inventory: Inventory = Bukkit.createInventory(this, 54, "View Cameras")

    override fun getInventory(): Inventory = inventory

    override fun open() {
        val cameras = plugin.getCameras()

        if (cameras.isEmpty()) {
            val noItem = createItem(Material.BARRIER, "§cNo Cameras Available", listOf("§7No cameras have been placed yet"))
            inventory.setItem(22, noItem)
        } else {
            var slot = 0
            cameras.forEach { (id, camera) ->
                if (slot < 45) {
                    val cameraItem = createItem(
                        Material.ENDER_EYE,
                        "§a${camera.name}",
                        listOf(
                            "§7ID: §f$id",
                            "§7Location: §f${camera.location.world?.name} (${camera.location.blockX}, ${camera.location.blockY}, ${camera.location.blockZ})",
                            "§7Owner: §f${Bukkit.getOfflinePlayer(camera.owner).name ?: "Unknown"}",
                            "",
                            "§eClick to view this camera"
                        )
                    )

                    // Store camera ID in item NBT
                    val meta = cameraItem.itemMeta
                    meta?.persistentDataContainer?.set(
                        org.bukkit.NamespacedKey(plugin, "camera-id"),
                        org.bukkit.persistence.PersistentDataType.STRING,
                        id
                    )
                    cameraItem.itemMeta = meta

                    inventory.setItem(slot, cameraItem)
                    slot++
                }
            }
        }

        val backItem = createItem(Material.ARROW, "§cBack", listOf("§7Return to main menu"))
        inventory.setItem(49, backItem)

        // Open inventory for player
        player.openInventory(inventory)
    }

    override fun handleClick(player: Player, item: ItemStack, slot: Int) {
        if (slot == 49) {
            player.closeInventory()
            MainMenu(plugin, player).open()
            return
        }

        if (item.type == Material.ENDER_EYE) {
            val meta = item.itemMeta ?: return
            val cameraId = meta.persistentDataContainer.get(
                org.bukkit.NamespacedKey(plugin, "camera-id"),
                org.bukkit.persistence.PersistentDataType.STRING
            ) ?: return

            player.closeInventory()
            if (plugin.startViewing(player, cameraId)) {
                player.sendMessage("§aViewing camera feed. Type /cctv to return.")
            } else {
                player.sendMessage("§cFailed to view camera.")
                MainMenu(plugin, player).open()
            }
        }
    }

    private fun createItem(material: Material, name: String, lore: List<String>): ItemStack {
        val item = ItemStack(material)
        val meta = item.itemMeta

        meta?.setDisplayName(name)
        meta?.lore = lore

        item.itemMeta = meta
        return item
    }
}

class ManageCamerasMenu(private val plugin: CctvPlugin, private val player: Player) : CctvMenu {
    private val inventory: Inventory = Bukkit.createInventory(this, 54, "Manage Cameras")

    override fun getInventory(): Inventory = inventory

    override fun open() {
        val cameras = plugin.getCameras().filter {
            it.value.owner == player.uniqueId || player.hasPermission("cctv.admin")
        }

        if (cameras.isEmpty()) {
            val noItem = createItem(Material.BARRIER, "§cNo Cameras Available", listOf("§7You don't have any cameras to manage"))
            inventory.setItem(22, noItem)
        } else {
            var slot = 0
            cameras.forEach { (id, camera) ->
                if (slot < 45) {
                    val cameraItem = createItem(
                        Material.ENDER_EYE,
                        "§a${camera.name}",
                        listOf(
                            "§7ID: §f$id",
                            "§7Location: §f${camera.location.world?.name} (${camera.location.blockX}, ${camera.location.blockY}, ${camera.location.blockZ})",
                            "",
                            "§eClick to remove this camera"
                        )
                    )

                    // Store camera ID in item NBT
                    val meta = cameraItem.itemMeta
                    meta?.persistentDataContainer?.set(
                        org.bukkit.NamespacedKey(plugin, "camera-id"),
                        org.bukkit.persistence.PersistentDataType.STRING,
                        id
                    )
                    cameraItem.itemMeta = meta

                    inventory.setItem(slot, cameraItem)
                    slot++
                }
            }
        }

        val backItem = createItem(Material.ARROW, "§cBack", listOf("§7Return to main menu"))
        inventory.setItem(49, backItem)

        // Open inventory for player
        player.openInventory(inventory)
    }

    override fun handleClick(player: Player, item: ItemStack, slot: Int) {
        if (slot == 49) {
            player.closeInventory()
            MainMenu(plugin, player).open()
            return
        }

        if (item.type == Material.ENDER_EYE) {
            val meta = item.itemMeta ?: return
            val cameraId = meta.persistentDataContainer.get(
                org.bukkit.NamespacedKey(plugin, "camera-id"),
                org.bukkit.persistence.PersistentDataType.STRING
            ) ?: return

            player.closeInventory()
            if (plugin.removeCamera(cameraId, player)) {
                player.sendMessage("§aCamera removed successfully!")
            } else {
                player.sendMessage("§cFailed to remove camera. Make sure you own it or have admin permissions.")
            }
            ManageCamerasMenu(plugin, player).open()
        }
    }

    private fun createItem(material: Material, name: String, lore: List<String>): ItemStack {
        val item = ItemStack(material)
        val meta = item.itemMeta

        meta?.setDisplayName(name)
        meta?.lore = lore

        item.itemMeta = meta
        return item
    }
}