#include "core/input/input.hpp"

#include <SDL3/SDL.h>

#include <algorithm>      // Para find
#include <iostream>       // Para basic_ostream, operator<<, cout, endl
#include <iterator>       // Para distance
#include <unordered_map>  // Para unordered_map, operator==, _Node_cons...
#include <utility>        // Para pair

// [SINGLETON]
Input* Input::input = nullptr;

// [SINGLETON] Crearemos el objeto con esta función estática
void Input::init(const std::string& game_controller_db_path) {
    Input::input = new Input(game_controller_db_path);
}

// [SINGLETON] Destruiremos el objeto con esta función estática
void Input::destroy() {
    delete Input::input;
}

// [SINGLETON] Con este método obtenemos el objeto y podemos trabajar con él
auto Input::get() -> Input* {
    return Input::input;
}

// Constructor
Input::Input(const std::string& game_controller_db_path)
    : game_controller_db_path_(game_controller_db_path) {
    // Busca si hay mandos conectados
    discoverGameControllers();

    // Inicializa los vectores
    key_bindings_.resize(static_cast<int>(InputAction::SIZE), KeyBindings());
    controller_bindings_.resize(num_gamepads_, std::vector<ControllerBindings>(static_cast<int>(InputAction::SIZE), ControllerBindings()));

    // Listado de los inputs para jugar que utilizan botones, ni palancas ni crucetas
    button_inputs_ = {InputAction::JUMP};
}

// Asigna inputs a teclas
void Input::bindKey(InputAction input, SDL_Scancode code) {
    key_bindings_.at(static_cast<int>(input)).scancode = code;
}

// Asigna inputs a botones del mando
void Input::bindGameControllerButton(int controller_index, InputAction input, SDL_GamepadButton button) {
    if (controller_index < num_gamepads_) {
        controller_bindings_.at(controller_index).at(static_cast<int>(input)).button = button;
    }
}

// Asigna inputs a botones del mando
void Input::bindGameControllerButton(int controller_index, InputAction input_target, InputAction input_source) {
    if (controller_index < num_gamepads_) {
        controller_bindings_.at(controller_index).at(static_cast<int>(input_target)).button = controller_bindings_.at(controller_index).at(static_cast<int>(input_source)).button;
    }
}

// Comprueba si un input esta activo
auto Input::checkInput(InputAction input, bool repeat, InputDeviceToUse device, int controller_index) -> bool {
    bool success_keyboard = false;
    bool success_controller = false;
    const int INPUT_INDEX = static_cast<int>(input);

    if (device == InputDeviceToUse::KEYBOARD || device == InputDeviceToUse::ANY) {
        const auto* key_states = SDL_GetKeyboardState(nullptr);

        if (repeat) {
            success_keyboard = static_cast<int>(key_states[key_bindings_[INPUT_INDEX].scancode]) != 0;
        } else {
            if (!key_bindings_[INPUT_INDEX].active) {
                if (static_cast<int>(key_states[key_bindings_[INPUT_INDEX].scancode]) != 0) {
                    key_bindings_[INPUT_INDEX].active = true;
                    success_keyboard = true;
                } else {
                    success_keyboard = false;
                }
            } else {
                if (static_cast<int>(key_states[key_bindings_[INPUT_INDEX].scancode]) == 0) {
                    key_bindings_[INPUT_INDEX].active = false;
                }
                success_keyboard = false;
            }
        }
    }

    if (gameControllerFound() && controller_index >= 0 && controller_index < num_gamepads_) {
        if ((device == InputDeviceToUse::CONTROLLER) || (device == InputDeviceToUse::ANY)) {
            success_controller = checkAxisInput(input, controller_index, repeat);

            if (!success_controller) {
                if (repeat) {
                    success_controller = static_cast<int>(SDL_GetGamepadButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(INPUT_INDEX).button)) != 0;
                } else {
                    if (!controller_bindings_.at(controller_index).at(INPUT_INDEX).active) {
                        if (static_cast<int>(SDL_GetGamepadButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(INPUT_INDEX).button)) != 0) {
                            controller_bindings_.at(controller_index).at(INPUT_INDEX).active = true;
                            success_controller = true;
                        } else {
                            success_controller = false;
                        }
                    } else {
                        if (static_cast<int>(SDL_GetGamepadButton(connected_controllers_.at(controller_index), controller_bindings_.at(controller_index).at(INPUT_INDEX).button)) == 0) {
                            controller_bindings_.at(controller_index).at(INPUT_INDEX).active = false;
                        }
                        success_controller = false;
                    }
                }
            }
        }
    }

    return (success_keyboard || success_controller);
}

// Comprueba si hay almenos un input activo
auto Input::checkAnyInput(InputDeviceToUse device, int controller_index) -> bool {
    if (device == InputDeviceToUse::KEYBOARD || device == InputDeviceToUse::ANY) {
        const bool* key_states = SDL_GetKeyboardState(nullptr);

        for (auto& key_binding : key_bindings_) {
            if (static_cast<int>(key_states[key_binding.scancode]) != 0 && !key_binding.active) {
                key_binding.active = true;
                return true;
            }
        }
    }

    if (gameControllerFound()) {
        if (device == InputDeviceToUse::CONTROLLER || device == InputDeviceToUse::ANY) {
            for (int i = 0; i < (int)controller_bindings_.size(); ++i) {
                if (static_cast<int>(SDL_GetGamepadButton(connected_controllers_[controller_index], controller_bindings_[controller_index][i].button)) != 0 && !controller_bindings_[controller_index][i].active) {
                    controller_bindings_[controller_index][i].active = true;
                    return true;
                }
            }
        }
    }

    return false;
}

// Busca si hay mandos conectados
auto Input::discoverGameControllers() -> bool {
    bool found = false;

    // Asegúrate de que el subsistema de gamepads está inicializado
    if (SDL_WasInit(SDL_INIT_GAMEPAD) != 1) {
        SDL_InitSubSystem(SDL_INIT_GAMEPAD);
    }

    // Carga el mapping de mandos desde archivo
    if (SDL_AddGamepadMappingsFromFile(game_controller_db_path_.c_str()) < 0) {
        std::cout << "Error, could not load " << game_controller_db_path_.c_str()
                  << " file: " << SDL_GetError() << '\n';
    }

    // En SDL3 ya no existe SDL_NumJoysticks()
    // Ahora se obtiene un array dinámico de IDs
    int num_joysticks = 0;
    SDL_JoystickID* joystick_ids = SDL_GetJoysticks(&num_joysticks);

    num_joysticks_ = num_joysticks;
    num_gamepads_ = 0;
    joysticks_.clear();

    // Recorremos todos los joysticks detectados
    for (int i = 0; i < num_joysticks_; ++i) {
        SDL_Joystick* joy = SDL_OpenJoystick(joystick_ids[i]);
        joysticks_.push_back(joy);

        if (SDL_IsGamepad(joystick_ids[i])) {
            num_gamepads_++;
        }
    }

    std::cout << "\n** LOOKING FOR GAME CONTROLLERS" << '\n';
    if (num_joysticks_ != num_gamepads_) {
        std::cout << "Joysticks found: " << num_joysticks_ << '\n';
        std::cout << "Gamepads found : " << num_gamepads_ << '\n';
    } else {
        std::cout << "Gamepads found: " << num_gamepads_ << '\n';
    }

    if (num_gamepads_ > 0) {
        found = true;

        for (int i = 0; i < num_joysticks_; i++) {
            if (SDL_IsGamepad(joystick_ids[i])) {
                SDL_Gamepad* pad = SDL_OpenGamepad(joystick_ids[i]);
                if ((pad != nullptr) && SDL_GamepadConnected(pad)) {
                    connected_controllers_.push_back(pad);

                    const char* name = SDL_GetGamepadName(pad);
                    std::cout << "#" << i << ": " << ((name != nullptr) ? name : "Unknown") << '\n';
                    controller_names_.emplace_back((name != nullptr) ? name : "Unknown");
                } else {
                    std::cout << "SDL_GetError() = " << SDL_GetError() << '\n';
                }
            }
        }

        // En SDL3 ya no hace falta SDL_GameControllerEventState()
        // Los eventos de gamepad están siempre habilitados
    }

    SDL_free(joystick_ids);

    std::cout << "\n** FINISHED LOOKING FOR GAME CONTROLLERS" << '\n';
    return found;
}

// Comprueba si hay algun mando conectado
auto Input::gameControllerFound() const -> bool { return num_gamepads_ > 0; }

// Obten el nombre de un mando de juego
auto Input::getControllerName(int controller_index) const -> std::string { return num_gamepads_ > 0 ? controller_names_.at(controller_index) : std::string(); }

// Obten el número de mandos conectados
auto Input::getNumControllers() const -> int { return num_gamepads_; }

// Obtiene el indice del controlador a partir de un event.id
auto Input::getJoyIndex(SDL_JoystickID id) const -> int {
    for (int i = 0; i < num_joysticks_; ++i) {
        if (SDL_GetJoystickID(joysticks_[i]) == id) {
            return i;
        }
    }
    return -1;
}

// Obtiene el SDL_GamepadButton asignado a un input
auto Input::getControllerBinding(int controller_index, InputAction input) const -> SDL_GamepadButton {
    return controller_bindings_[controller_index][static_cast<int>(input)].button;
}

// Obtiene el indice a partir del nombre del mando
auto Input::getIndexByName(const std::string& name) const -> int {
    auto it = std::ranges::find(controller_names_, name);
    return it != controller_names_.end() ? std::distance(controller_names_.begin(), it) : -1;
}

// Comprueba el eje del mando
auto Input::checkAxisInput(InputAction input, int controller_index, bool repeat) -> bool {
    // Umbral para considerar el eje como activo
    const Sint16 THRESHOLD = 30000;
    bool axis_active_now = false;

    switch (input) {
        case InputAction::LEFT:
            axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) < -THRESHOLD;
            break;
        case InputAction::RIGHT:
            axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTX) > THRESHOLD;
            break;
        case InputAction::UP:
            axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) < -THRESHOLD;
            break;
        case InputAction::DOWN:
            axis_active_now = SDL_GetGamepadAxis(connected_controllers_[controller_index], SDL_GAMEPAD_AXIS_LEFTY) > THRESHOLD;
            break;
        default:
            return false;
    }

    // Referencia al binding correspondiente
    auto& binding = controller_bindings_.at(controller_index).at(static_cast<int>(input));

    if (repeat) {
        // Si se permite repetir, simplemente devolvemos el estado actual
        return axis_active_now;
    }  // Si no se permite repetir, aplicamos la lógica de transición
    if (axis_active_now && !binding.axis_active) {
        // Transición de inactivo a activo
        binding.axis_active = true;
        return true;
    }
    if (!axis_active_now && binding.axis_active) {
        // Transición de activo a inactivo
        binding.axis_active = false;
    }
    // Mantener el estado actual
    return false;
}