#include <iostream>

#include <glad/glad.h> // Must be included before GLFW
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>

#include "Shader.h"
#include "Player.h"
#include "Camera.h"
#include "Object3D.h"
#include "World.h"

// Window dimensions
unsigned int SCR_WIDTH = 1920;
unsigned int SCR_HEIGHT = 1080;

const int EDIT_RANGE = 5;

// Jump
const float JUMP_COOLDOWN = 0.0f;
const float JUMP_POWER = 7.5f; // Initial Jump Speed
float last_jump = 0.0f;

// Camera
const float CAMERA_SPEED = 1.0f;
const float MAX_CAMERA_SPEED = 2.0f;
const float LOOK_SENSITIVITY = 0.1f;

const float Z_FAR = 1000.0f;
const float Z_NEAR = 0.1f;
bool WIREFRAME_MODE = !true;
const float FOV = 110.0f;

const std::string VERSION = "0.9.0";

const int VIEW_DISTANCE = 4;

bool W_pressed, S_pressed, A_pressed, D_pressed = false;

glm::mat4 projection = glm::mat4(1.0f);
Player player = Player(CAMERA_SPEED, glm::vec3(0.0f, 20.0f, 0.0f));
Camera camera = Camera(&player);

// Targeted block for highlighting
std::optional<glm::ivec3> targeted_block = std::nullopt;

// Callback function for when the window is resized
// glfw: whenever the window size changed (by OS or user resize) this callback function executes
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
    // make sure the viewport matches the new window dimensions; note that width and
    // height will be significantly larger than specified on retina displays.
    glViewport(0, 0, width, height);
    SCR_WIDTH = width;
    SCR_HEIGHT = height;

    // Perspective needs to be recalculated on window size change
    projection = glm::perspective(glm::radians(FOV), (float)SCR_WIDTH / (float)SCR_HEIGHT, Z_NEAR, Z_FAR);
}

float yaw, pitch = 0;
bool first_mouse = true;
bool mouse_lock = true;
float last_x = 400, last_y = 300;

World world;

// Mouse Look
void mouse_callback(GLFWwindow * window, double xpos, double ypos)
{
    float x_offset = xpos - last_x;
    float y_offset = last_y - ypos;  // Inverted Y for typical FPS controls
    last_x = xpos;
    last_y = ypos;

    if (first_mouse)
    {
        first_mouse = false;
        return;
    }

    x_offset *= LOOK_SENSITIVITY;
    y_offset *= LOOK_SENSITIVITY;

    yaw += x_offset;
    pitch += y_offset;

    if (pitch > 89.0f)
        pitch = 89.0f;
    if (pitch < -89.0f)
        pitch = -89.0f;

    glm::vec3 direction;
    direction.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch));
    direction.y = sin(glm::radians(pitch));  // Positive Y is up
    direction.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch));
    camera.target = glm::normalize(direction);
}

// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
void processInput(GLFWwindow *window)
{
    float current_time = glfwGetTime();

    if (glfwGetKey(window, GLFW_KEY_P) == GLFW_PRESS) {
        glm::vec3 eye = camera.getEyePosition();
        glm::mat4 view = camera.getView();
        glm::vec3 forward = -glm::vec3(view[0][2], view[1][2], view[2][2]); // Extract forward from view matrix

        std::cout << "Camera target (from pitch/yaw): (" << camera.target.x << ", " << camera.target.y << ", " << camera.target.z << ")" << std::endl;
        std::cout << "Camera forward (from view matrix): (" << forward.x << ", " << forward.y << ", " << forward.z << ")" << std::endl;
        std::cout << "Match: " << (glm::length(camera.target - forward) < 0.01f ? "YES" : "NO") << std::endl;
    }

    // Update targeted block every frame for highlight
    std::optional<std::pair<glm::ivec3, glm::ivec3>> raycast_result =
        world.raycast_voxel(camera.getEyePosition(), camera.target, EDIT_RANGE);
    if (raycast_result.has_value()) {
        targeted_block = raycast_result.value().first;

        // Debug: print occasionally
        static int frame_count = 0;
        if (frame_count % 60 == 0) {
            std::cout << "Camera eye: (" << camera.getEyePosition().x << ", " << camera.getEyePosition().y << ", " << camera.getEyePosition().z << ")" << std::endl;
            std::cout << "Camera target dir: (" << camera.target.x << ", " << camera.target.y << ", " << camera.target.z << ")" << std::endl;
            std::cout << "Highlighted block: (" << targeted_block.value().x << ", " << targeted_block.value().y << ", " << targeted_block.value().z << ")" << std::endl;
        }
        frame_count++;
    } else {
        targeted_block = std::nullopt;
    }

    if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) {
        // if (mouse_lock) {
        //     glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
        //     mouse_lock = false;
        // } else {
        //     glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
        //     mouse_lock = true;
        // }
        glfwSetWindowShouldClose(window, true);
    }

    // ---- Movement ----
    // Forward / Backward
    if(glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
    {
        player.forward_velocity = player.speed * glm::vec3(camera.target.x, 0.0f, camera.target.z);
        W_pressed = true;
    }

    if(glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
    {
        player.forward_velocity = -player.speed * glm::vec3(camera.target.x, 0.0f, camera.target.z);
        S_pressed = true;
    }


    if(glfwGetKey(window, GLFW_KEY_S) == GLFW_RELEASE && S_pressed)
    {
        player.forward_velocity = glm::vec3(0.0f);
        S_pressed = false;
    }
    if(glfwGetKey(window, GLFW_KEY_W) == GLFW_RELEASE && W_pressed)
    {
        player.forward_velocity = glm::vec3(0.0f);
        W_pressed = false;
    }


    // Horizontal
    if(glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
    {
        player.horizontal_velocity = -glm::normalize(glm::cross(glm::vec3(camera.target.x, 0.0f, camera.target.z), camera.worldUp)) * player.speed;
        A_pressed = true;
    }
    if(glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
    {
        player.horizontal_velocity = glm::normalize(glm::cross(glm::vec3(camera.target.x, 0.0f, camera.target.z), camera.worldUp)) * player.speed;
        D_pressed = true;
    }


    if(glfwGetKey(window, GLFW_KEY_A) == GLFW_RELEASE && A_pressed)
    {
        player.horizontal_velocity = glm::vec3(0.0f);
        A_pressed = false;
    }
    if(glfwGetKey(window, GLFW_KEY_D) == GLFW_RELEASE && D_pressed)
    {
        player.horizontal_velocity = glm::vec3(0.0f);
        D_pressed = false;
    }


    // Jump
    if(glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS)
        // player.velocity -= glm::normalize(glm::cross(camera.target, glm::normalize(glm::cross(camera.target, camera.worldUp)))) * player.speed * 0.5f;
    {
        if (current_time - last_jump > JUMP_COOLDOWN && player.grounded)
        {
            player.vertical_velocity.y = JUMP_POWER;
            last_jump = current_time;
        }
    }

    // Sprint
    if(glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS)
        player.speed = CAMERA_SPEED * 7.5;
    if(glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_RELEASE)
        player.speed = CAMERA_SPEED * 20;

    static bool left_mouse_pressed = false;
    static bool right_mouse_pressed = false;

    // Left click - place block
    if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS && !left_mouse_pressed) {
        left_mouse_pressed = true;
        std::cout << "\n=== LEFT CLICK (PLACE) ===" << std::endl;
        std::cout << "Camera eye pos: (" << camera.getEyePosition().x << ", " << camera.getEyePosition().y << ", " << camera.getEyePosition().z << ")" << std::endl;
        std::cout << "Camera target: (" << camera.target.x << ", " << camera.target.y << ", " << camera.target.z << ")" << std::endl;

        std::optional<std::pair<glm::ivec3, glm::ivec3>> raycast_result =
            world.raycast_voxel(camera.getEyePosition(), camera.target, EDIT_RANGE);

        if (raycast_result.has_value()) {
            auto [target_block, normal] = raycast_result.value();
            std::cout << "Hit block at: (" << target_block.x << ", " << target_block.y << ", " << target_block.z << ")" << std::endl;
            std::cout << "Normal: (" << normal.x << ", " << normal.y << ", " << normal.z << ")" << std::endl;
            glm::ivec3 place_pos = target_block + normal;
            std::cout << "Placing at: (" << place_pos.x << ", " << place_pos.y << ", " << place_pos.z << ")" << std::endl;
            world.set_voxel(place_pos, VoxelKind::Stone);
        } else {
            std::cout << "No block hit within range" << std::endl;
        }
    }
    if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_RELEASE) {
        left_mouse_pressed = false;
    }

    // Right click - remove block
    if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS && !right_mouse_pressed) {
        right_mouse_pressed = true;
        std::cout << "\n=== RIGHT CLICK (REMOVE) ===" << std::endl;
        std::cout << "Camera eye pos: (" << camera.getEyePosition().x << ", " << camera.getEyePosition().y << ", " << camera.getEyePosition().z << ")" << std::endl;
        std::cout << "Camera target: (" << camera.target.x << ", " << camera.target.y << ", " << camera.target.z << ")" << std::endl;

        std::optional<std::pair<glm::ivec3, glm::ivec3>> raycast_result =
            world.raycast_voxel(camera.getEyePosition(), camera.target, EDIT_RANGE);

        if (raycast_result.has_value()) {
            auto [target_block, normal] = raycast_result.value();
            std::cout << "Hit block at: (" << target_block.x << ", " << target_block.y << ", " << target_block.z << ")" << std::endl;
            std::cout << "Removing block at: (" << target_block.x << ", " << target_block.y << ", " << target_block.z << ")" << std::endl;
            world.set_voxel(target_block, VoxelKind::Air);
        } else {
            std::cout << "No block hit within range" << std::endl;
        }
    }
    if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT) == GLFW_RELEASE) {
        right_mouse_pressed = false;
    }
}

int main() {
    // 1. --- Initialize GLFW ---
    if (!glfwInit()) {
        std::cerr << "Failed to initialize GLFW" << std::endl;
        return -1;
    }
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    // 2. --- Create a Window ---
    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, ("Voxel Engine " + VERSION).c_str(), NULL, NULL);
    if (window == NULL) {
        std::cerr << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

    // 3. --- Initialize GLAD ---
    if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
        std::cerr << "Failed to initialize GLAD" << std::endl;
        return -1;
    }

    glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT);

    // 4. Shader Setup
    Shader shader("shaders/cube_vert.glsl", "shaders/cube_frag.glsl");

    // 5. --- Set up Vertex Data and Buffers ---

    // Load Cube OBJ
    // Object3D cube = Object3D("objs/cube.obj");

    // std::cout << "World created with " << world.chunks.size() << " chunks" << std::endl;
    // Mesh generation now happens automatically when first rendering

    if (WIREFRAME_MODE)
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

    // Setup mouse look
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    glfwSetCursorPosCallback(window, mouse_callback);

    // Setup projection matrix
    projection = glm::perspective(glm::radians(FOV), (float)SCR_WIDTH / (float)SCR_HEIGHT, Z_NEAR, Z_FAR); // This doesn't need to be recalculated every frame

    // Setup crosshair
    unsigned int crosshairVAO, crosshairVBO;
    glGenVertexArrays(1, &crosshairVAO);
    glGenBuffers(1, &crosshairVBO);

    glBindVertexArray(crosshairVAO);
    glBindBuffer(GL_ARRAY_BUFFER, crosshairVBO);

    // Crosshair vertices in NDC (Normalized Device Coordinates: -1 to 1)
    float crosshairSize = 0.02f; // Size in NDC
    float crosshairVertices[] = {
        // Horizontal line
        -crosshairSize, 0.0f, 0.0f,
         crosshairSize, 0.0f, 0.0f,
        // Vertical line
         0.0f, -crosshairSize, 0.0f,
         0.0f,  crosshairSize, 0.0f
    };

    glBufferData(GL_ARRAY_BUFFER, sizeof(crosshairVertices), crosshairVertices, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);
    glBindVertexArray(0);

    // Setup highlight box (cube outline)
    unsigned int highlightVAO, highlightVBO, highlightEBO;
    glGenVertexArrays(1, &highlightVAO);
    glGenBuffers(1, &highlightVBO);
    glGenBuffers(1, &highlightEBO);

    glBindVertexArray(highlightVAO);
    glBindBuffer(GL_ARRAY_BUFFER, highlightVBO);

    // Cube outline vertices (slightly larger than 1 unit cube for visibility)
    float offset = 0.001f; // Slight offset to prevent z-fighting
    float highlightVertices[] = {
        // 8 corners of a cube
        -0.5f - offset, -0.5f - offset, -0.5f - offset,  // 0
         0.5f + offset, -0.5f - offset, -0.5f - offset,  // 1
         0.5f + offset,  0.5f + offset, -0.5f - offset,  // 2
        -0.5f - offset,  0.5f + offset, -0.5f - offset,  // 3
        -0.5f - offset, -0.5f - offset,  0.5f + offset,  // 4
         0.5f + offset, -0.5f - offset,  0.5f + offset,  // 5
         0.5f + offset,  0.5f + offset,  0.5f + offset,  // 6
        -0.5f - offset,  0.5f + offset,  0.5f + offset   // 7
    };

    // Indices for the 12 edges of the cube
    unsigned int highlightIndices[] = {
        // Bottom face
        0, 1,  1, 2,  2, 3,  3, 0,
        // Top face
        4, 5,  5, 6,  6, 7,  7, 4,
        // Vertical edges
        0, 4,  1, 5,  2, 6,  3, 7
    };

    glBufferData(GL_ARRAY_BUFFER, sizeof(highlightVertices), highlightVertices, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, highlightEBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(highlightIndices), highlightIndices, GL_STATIC_DRAW);
    glBindVertexArray(0);

    // Setup debug ray
    unsigned int debugRayVAO, debugRayVBO;
    glGenVertexArrays(1, &debugRayVAO);
    glGenBuffers(1, &debugRayVBO);

    glBindVertexArray(debugRayVAO);
    glBindBuffer(GL_ARRAY_BUFFER, debugRayVBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 6, nullptr, GL_DYNAMIC_DRAW); // 2 points * 3 coords
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);
    glBindVertexArray(0);

    glm::mat4 view;
    double start_time = glfwGetTime();
    double move_time = glfwGetTime();

    glEnable(GL_DEPTH_TEST);
    bool debug_printed = false;

    // FPS counter variables
    double last_fps_update = glfwGetTime();
    int frame_count = 0;
    double fps = 0.0;

    // 6. --- The Render Loop ---
    while (!glfwWindowShouldClose(window)) {
        // Update FPS counter
        double current_time = glfwGetTime();
        frame_count++;
        if (current_time - last_fps_update >= 1.0) {
            fps = frame_count / (current_time - last_fps_update);
            std::string title = "Voxel Engine " + VERSION + " | FPS: " + std::to_string((int)fps);
            glfwSetWindowTitle(window, title.c_str());
            frame_count = 0;
            last_fps_update = current_time;
        }

        // Input (e.g., close window on ESC)
        processInput(window);

        glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Clear screen
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Z-Buffer

        view = camera.getView();

        shader.use();

        // Generate chunks around the player
        glm::ivec3 camera_chunk = glm::ivec3(
            std::floor(player.position.x / CHUNK_SIZE),
            std::floor(player.position.y / CHUNK_SIZE),
            std::floor(player.position.z / CHUNK_SIZE)
        );

        // Create frustum for culling from view-projection matrix
        glm::mat4 viewProj = projection * view;
        Frustum frustum = camera.createFrustumFromMatrix(viewProj);

        // ---- PASS 1: Draw solid grey cubes ----
        glEnable(GL_POLYGON_OFFSET_FILL);
        glPolygonOffset(1.0, 1.0); // Push solid faces "back"
        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
        shader.setVec3("u_Color", glm::vec3(0.5, 0.5, 0.5));

        for (int y = -2; y < 2; y++) {  // Reduced from -VIEW_DISTANCE to VIEW_DISTANCE
            for (int z = -VIEW_DISTANCE; z < VIEW_DISTANCE; z++) {
                for (int x = -VIEW_DISTANCE; x < VIEW_DISTANCE; x++) {
                    glm::ivec3 chunk_offset = glm::ivec3(x, y, z);
                    glm::ivec3 chunk_pos = camera_chunk + chunk_offset;

                    // Create AABB for this chunk
                    glm::vec3 chunkWorldPos = glm::vec3(chunk_pos * CHUNK_SIZE);
                    AABB chunkAABB;
                    chunkAABB.min = chunkWorldPos;
                    chunkAABB.max = chunkWorldPos + glm::vec3(CHUNK_SIZE);

                    // Frustum culling - skip if chunk is not visible
                    if (!frustum.isAABBVisible(chunkAABB)) {
                        continue;
                    }

                    glm::mat4 model = glm::mat4(1.0f);
                    model = glm::translate(model, glm::vec3(chunk_pos * CHUNK_SIZE));
                    glm::mat4 mvp = projection * view * model;
                    shader.setMat4("u_mvp", mvp);

                    Chunk* chunk = world.get_or_create_chunk(chunk_pos);

                    Mesh* chunk_mesh = chunk->getMesh();
                    if (chunk_mesh)
                        chunk_mesh->draw();
                }
            }
        }

        // if (!debug_printed) {
        //     debug_printed = true;
        // }

        glDisable(GL_POLYGON_OFFSET_FILL);

        // ---- PASS 2: Draw wireframe on top ----
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // Just the lines
        shader.setVec3("u_Color", glm::vec3(1.0, 1.0, 1.0));

        for (int y = -2; y < 2; y++) {  // Reduced from -VIEW_DISTANCE to VIEW_DISTANCE
            for (int z = -VIEW_DISTANCE; z < VIEW_DISTANCE; z++) {
                for (int x = -VIEW_DISTANCE; x < VIEW_DISTANCE; x++) {
                    glm::ivec3 chunk_offset = glm::ivec3(x, y, z);
                    glm::ivec3 chunk_pos = camera_chunk + chunk_offset;

                    // Create AABB for this chunk
                    glm::vec3 chunkWorldPos = glm::vec3(chunk_pos * CHUNK_SIZE);
                    AABB chunkAABB;
                    chunkAABB.min = chunkWorldPos;
                    chunkAABB.max = chunkWorldPos + glm::vec3(CHUNK_SIZE);

                    // Frustum culling - skip if chunk is not visible
                    if (!frustum.isAABBVisible(chunkAABB)) {
                        continue;
                    }

                    glm::mat4 model = glm::mat4(1.0f);
                    model = glm::translate(model, glm::vec3(chunk_pos * CHUNK_SIZE));
                    glm::mat4 mvp = projection * view * model;
                    shader.setMat4("u_mvp", mvp);

                    Chunk* chunk = world.get_or_create_chunk(chunk_pos);

                    Mesh* chunk_mesh = chunk->getMesh();
                    if (chunk_mesh)
                        chunk_mesh->draw();
                }
            }
        }

        // --- Reset polygon mode for next frame (good practice) ---
        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

        // ---- Draw Highlighted Block ----
        if (targeted_block.has_value()) {
            shader.use();
            glm::mat4 model = glm::mat4(1.0f);
            // Voxels are centered on integer coordinates, so no need to add 0.5
            model = glm::translate(model, glm::vec3(targeted_block.value()));
            glm::mat4 mvp = projection * view * model;
            shader.setMat4("u_mvp", mvp);
            shader.setVec3("u_Color", glm::vec3(0.0f, 0.0f, 0.0f)); // Black outline

            glLineWidth(2.0f);
            glBindVertexArray(highlightVAO);
            glDrawElements(GL_LINES, 24, GL_UNSIGNED_INT, 0); // 24 indices = 12 edges
            glBindVertexArray(0);
        }

        // ---- Draw Crosshair ----
        glDisable(GL_DEPTH_TEST); // Draw on top of everything
        shader.use();
        shader.setMat4("u_mvp", glm::mat4(1.0f)); // Identity matrix (NDC coordinates)
        shader.setVec3("u_Color", glm::vec3(1.0f, 1.0f, 1.0f)); // White
        glBindVertexArray(crosshairVAO);
        glDrawArrays(GL_LINES, 0, 4); // 4 vertices = 2 lines
        glBindVertexArray(0);
        glEnable(GL_DEPTH_TEST);

        double end_time = glfwGetTime();
        float time_since_last_move = end_time - move_time;
        if (time_since_last_move  >= 0.017)
        {
            player.move(&world, time_since_last_move);
            move_time = end_time;
        }

        // Swap buffers and poll for events
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwTerminate(); // Clean up GLFW
    return 0;
}
