package com.yaohun.demonskills.listener;

import com.yaohun.demonskills.SkillsMain;
import com.yaohun.demonskills.config.Config;
import com.yaohun.demonskills.config.MessageUtil;
import com.yaohun.demonskills.core.Skill;
import com.yaohun.demonskills.event.SkillCastEvent;
import com.yaohun.demonskills.gui.SkillsGui;
import com.yaohun.demonskills.manage.SkillManager;
import com.yaohun.demonskills.data.PlayerData;
import com.yaohun.demonskills.manage.PlayerManager;
import com.yaohun.demonskills.skills.skillsapi.Skill_前翻滚;
import com.yaohun.demonskills.skills.skillsapi.Skill_右翻滚;
import com.yaohun.demonskills.skills.skillsapi.Skill_后翻滚;
import com.yaohun.demonskills.skills.skillsapi.Skill_左翻滚;
import com.yaohun.demonskills.util.CDTimeAPI;
import lk.vexview.event.KeyBoardPressEvent;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.util.Vector;

import java.util.*;

public class SkillKeyListener implements Listener {

    @EventHandler
    public void onKey(KeyBoardPressEvent e){
        if(!e.getEventKeyState()){return;}
        Player player = e.getPlayer();
        UUID uuid = player.getUniqueId();
        if (e.getKey() == 19) {
            if(CDTimeAPI.isCD(uuid,"keyBoardCd")){return;}
            castSkill(player,e.getKey());
        }
        if (e.getKey() == 44) {
            if(CDTimeAPI.isCD(uuid,"keyBoardCd")){return;}
            castSkill(player,e.getKey());
        }
        if (e.getKey() == 45) {
            if(CDTimeAPI.isCD(uuid,"keyBoardCd")){return;}
            castSkill(player,e.getKey());
        }
        if (e.getKey() == 46) {
            if(CDTimeAPI.isCD(uuid,"keyBoardCd")){return;}
            castSkill(player,e.getKey());
        }
        if (e.getKey() == 47) {
            if(CDTimeAPI.isCD(uuid,"keyBoardCd")){return;}
            castSkill(player,e.getKey());
        }
        if(e.getKey() == 29){ // Ctrl键
            String cooldownKey = "skill_翻滚";
            if(CDTimeAPI.isCD(uuid,cooldownKey))return;
            if(CDTimeAPI.isCD(uuid,"coreSkillCd")){return;}
            CDTimeAPI.setPlayerCD(uuid,"翻滚激活",500);
        }
    }


    private final Map<UUID, List<Long>> rollTimestamps = new HashMap<>();

    @EventHandler
    public void onPlayerMove(PlayerMoveEvent event) {
        Player player = event.getPlayer();
        UUID uuid = player.getUniqueId();
        Location from = event.getFrom();
        Location to = event.getTo();
        if (to == null) return;
        if(CDTimeAPI.isCD(uuid,"翻滚激活")) {
            String cooldownKey = "skill_翻滚";
            if(CDTimeAPI.isCD(uuid,cooldownKey)) {
                return;
            }
            CDTimeAPI.setPlayerCD(uuid,"翻滚激活",-1);
            Vector moveVec = to.toVector().subtract(from.toVector());
            moveVec.setY(0); // 忽略Y轴，判断水平面

            if (moveVec.length() < 0.01) return; // 几乎没动，忽略

            Vector direction = event.getPlayer().getLocation().getDirection().setY(0).normalize();
            Vector right = new Vector(direction.getZ(), 0, -direction.getX()); // 右侧方向

            double forwardDot = moveVec.normalize().dot(direction); // 与面朝方向夹角余弦
            double rightDot = moveVec.normalize().dot(right);       // 与右侧方向夹角余弦

            // 记录时间戳
            long now = System.currentTimeMillis();
            List<Long> timestamps = rollTimestamps.computeIfAbsent(uuid, k -> new ArrayList<>());
            timestamps.removeIf(t -> now - t > 5000); // 只保留5秒内的
            timestamps.add(now);

            // 判断方向（你可以设置一个容错范围 0.7~1.0 表示大致方向）
            Skill skill;
            if (forwardDot > 0.7) {
                skill = Skill_前翻滚.getSkillData();
            } else if (forwardDot < -0.7) {
                skill = Skill_后翻滚.getSkillData();
            } else if (rightDot > 0.7) {
                skill = Skill_左翻滚.getSkillData();
            } else {
                skill = Skill_右翻滚.getSkillData();
            }
            // 执行技能
            skill.cast(player);
            if (timestamps.size() >= 3) {
                // 满足条件，设置CD
                CDTimeAPI.setPlayerCD(uuid, cooldownKey, (long) (skill.cooldownTime * 1000L));
                rollTimestamps.remove(uuid); // 重置次数
            }
            CDTimeAPI.setPlayerCD(uuid,"coreSkillCd", (long) (skill.coreCooldown * 800L));
        }
    }

    public void castSkill(Player player,int keyBoard){
        World world = player.getWorld();
        if(Config.isDisableWorld(world.getName())){
            MessageUtil.sendMessage(player,Config.langData.getMessage("disableWorldSkills"), Sound.ENTITY_VILLAGER_NO);
            return;
        }
        String playerName = player.getName();
        PlayerManager playerManager = SkillsMain.getPlayerManager();
        PlayerData playerData = playerManager.getPlayerData(playerName);
        if(playerData == null){
            return;
        }
        String skillName = playerData.getSkillNameBind(keyBoard);
        if(skillName.equalsIgnoreCase("default")){
            if(keyBoard == 19){
                SkillsGui.OpenGui(player);
            }
            return;
        }
        CDTimeAPI.setPlayerCD(player.getUniqueId(),"keyBoardCd",500L);
        Skill skill = SkillManager.getNameConvertSkill(player,skillName);
        if(skill == null){return;}
        SkillManager.castSkill(player, skill);
        SkillCastEvent skillCastEvent = new SkillCastEvent(player, skill);
        Bukkit.getPluginManager().callEvent(skillCastEvent);
    }
}
