/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2025 SteamWar.de-Serverteam
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package de.steamwar.tntleague.inventory

import de.steamwar.inventory.SWInventory
import de.steamwar.inventory.SWItem
import de.steamwar.kotlin.KotlinInventory
import de.steamwar.tntleague.config.TNTLeagueConfig
import de.steamwar.tntleague.game.TNTLeagueGame
import de.steamwar.tntleague.message
import de.steamwar.tntleague.plugin
import net.kyori.adventure.text.Component
import net.kyori.adventure.text.format.NamedTextColor
import net.kyori.adventure.text.format.TextDecoration
import org.bukkit.Material
import org.bukkit.NamespacedKey
import org.bukkit.Sound
import org.bukkit.entity.Player
import org.bukkit.event.inventory.InventoryClickEvent
import org.bukkit.inventory.ItemStack
import org.bukkit.persistence.PersistentDataType
import java.util.*

class DealerInventory(player: Player) : KotlinInventory(player) {

    init {
        this[10] = SWItem(Material.REDSTONE_BLOCK, message.parse("DEALER_REDSTONE", player)).itemStack to openCategory(TNTLeagueConfig.ItemCategory.REDSTONE)
        this[12] = SWItem(Material.END_STONE, message.parse("DEALER_BLOCKS", player)).itemStack to openCategory(TNTLeagueConfig.ItemCategory.BLOCKS)
        this[14] = SWItem(Material.DIAMOND_PICKAXE, message.parse("DEALER_TOOLS", player)).itemStack to openCategory(TNTLeagueConfig.ItemCategory.TOOLS)
        this[16] = SWItem(Material.BREWING_STAND, message.parse("DEALER_ANGLES", player)).itemStack to openCategory(TNTLeagueConfig.ItemCategory.ANGLES)

        pinnedItems.forEach { item ->
            this[item.key] = item.value.first to { buyItem(player, item.value, it) }
        }
    }

    private fun openCategory(cat: TNTLeagueConfig.ItemCategory): (e: InventoryClickEvent) -> Unit =
        { CategoryInventory(player, cat).open() }

    override fun createInventory() =
        SWInventory(player, 9 * 6, message.parse("DEALER", player))

    companion object {
        private val priceKey = NamespacedKey(plugin, "price")
        private val amountKey = NamespacedKey(plugin, "amount")
        val coinKey = NamespacedKey(plugin, "coin")

        val coins = ItemStack(Material.RAW_GOLD).apply {
            itemMeta = itemMeta.apply {
                displayName(Component.text("Coins").color(NamedTextColor.GOLD))
                persistentDataContainer.apply {
                    set(coinKey, PersistentDataType.INTEGER, 1)
                }
            }
        }

        val big_coins = ItemStack(Material.GOLD_INGOT).apply {
            itemMeta = itemMeta.apply {
                displayName(Component.text("Big Coins").color(NamedTextColor.GOLD))
                persistentDataContainer.apply {
                    set(coinKey, PersistentDataType.INTEGER, 3)
                }
            }
        }

        val huge_coins = ItemStack(Material.GOLD_BLOCK).apply {
            itemMeta = itemMeta.apply {
                displayName(Component.text("Huge Coins").color(NamedTextColor.GOLD))
                persistentDataContainer.apply {
                    set(coinKey, PersistentDataType.INTEGER, 9)
                }
            }
        }

        fun buyItem(player: Player, item: Pair<ItemStack, TNTLeagueConfig.Price>, e: InventoryClickEvent) {
            val price = item.second.price * if (e.isShiftClick) 5 else 1
            val amount = item.second.amount * if (e.isShiftClick) 5 else 1

            val team = TNTLeagueGame.getTeam(player)
                ?: return

            if (team.coins < price) {
                message.send("NOT_ENOUGH_COINS", player)
                player.playSound(player, Sound.ENTITY_VILLAGER_HURT, 1f, 1f)
                return
            }

            team.coins -= price
            player.inventory.addItem(ItemStack.of(item.first.type, amount).apply { item.second.extras.forEach { itemMeta = itemMeta.apply(it.func) } })
        }

        private val items by lazy {
            val prices = TNTLeagueConfig.config.prices

            prices.map { (material, price) ->
                ItemStack(material).apply {
                    itemMeta = itemMeta.apply {
                        displayName(
                            Component.text(
                                material.name.lowercase().replace("_", " ")
                                    .replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() })
                                .color(NamedTextColor.GRAY).appendSpace().append(Component.text(price.amount).color(NamedTextColor.YELLOW))
                        )


                        amount = price.amount
                        lore(listOf(Component.text(price.price).color(NamedTextColor.YELLOW).decorate(TextDecoration.BOLD).appendSpace().append(Component.text("Coins").color(NamedTextColor.YELLOW))))
                        persistentDataContainer.apply {
                            set(priceKey, PersistentDataType.INTEGER, price.price)
                            set(amountKey, PersistentDataType.INTEGER, price.amount)
                        }
                    }
                } to price
            }
        }

        val itemsByCategory = items.groupBy { it.second.category }
        val pinnedItems = items.filter { it.second.pinned != -1 }.associateBy { it.second.pinned }
    }
}
