#include <tt_app.h>
#include <tt_lvgl.h>
#include <tt_lvgl_toolbar.h>

#include <tactility/device.h>
#include <tactility/drivers/audio_stream.h>
#include <tactility/drivers/audio_codec.h>

#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"

#define MINIMP3_IMPLEMENTATION
#define MINIMP3_NO_SIMD
#include "minimp3.h"

#define TAG "Mp3Player"
#define MP3_INPUT_BUFFER_SIZE 16384

typedef enum {
    STATE_IDLE,
    STATE_PLAYING,
    STATE_PAUSED
} PlaybackState;

typedef struct {
    struct Device* stream_dev;
    AudioStreamHandle stream_handle;
    char           filepath[512];
    PlaybackState  state;
    
    // UI elements
    lv_obj_t*      lbl_title;
    lv_obj_t*      lbl_status;
    lv_obj_t*      bar_progress;
    lv_obj_t*      btn_play_pause;
    lv_obj_t*      btn_stop;
    
    // Playback state variables
    FILE*          file;
    mp3dec_t       decoder;
    uint8_t*       input_buf;
    mp3d_sample_t* pcm_buf;
    size_t         buffered_bytes;
    bool           eof;
    int            volume;
    
    int            sample_rate;
    int            channels;
    
    // Progress calculation
    size_t         file_size;
    size_t         bytes_read_total;
    
    TaskHandle_t   playback_task_handle;
} AppCtx;

static AppCtx g_ctx;

/* ─── Update UI ─── */
static void update_ui(AppCtx* ctx) {
    if (!ctx->lbl_status) return;

    switch (ctx->state) {
        case STATE_PLAYING:
            lv_label_set_text(ctx->lbl_status, "Playing...");
            lv_label_set_text(lv_obj_get_child(ctx->btn_play_pause, 0), LV_SYMBOL_PAUSE " Pause");
            lv_obj_clear_state(ctx->btn_play_pause, LV_STATE_DISABLED);
            lv_obj_clear_state(ctx->btn_stop, LV_STATE_DISABLED);
            break;
        case STATE_PAUSED:
            lv_label_set_text(ctx->lbl_status, "Paused");
            lv_label_set_text(lv_obj_get_child(ctx->btn_play_pause, 0), LV_SYMBOL_PLAY " Play");
            lv_obj_clear_state(ctx->btn_play_pause, LV_STATE_DISABLED);
            lv_obj_clear_state(ctx->btn_stop, LV_STATE_DISABLED);
            break;
        case STATE_IDLE:
        default:
            if (ctx->filepath[0] != '\0') {
                lv_label_set_text(ctx->lbl_status, "Ready");
                lv_obj_clear_state(ctx->btn_play_pause, LV_STATE_DISABLED);
            } else {
                lv_label_set_text(ctx->lbl_status, "No file loaded");
                lv_obj_add_state(ctx->btn_play_pause, LV_STATE_DISABLED);
            }
            lv_label_set_text(lv_obj_get_child(ctx->btn_play_pause, 0), LV_SYMBOL_PLAY " Play");
            lv_obj_add_state(ctx->btn_stop, LV_STATE_DISABLED);
            lv_bar_set_value(ctx->bar_progress, 0, LV_ANIM_OFF);
            break;
    }
}

/* ─── Playback Task ─── */
static void mp3_playback_task(void* arg) {
    AppCtx* ctx = (AppCtx*)arg;
    
    ctx->file = fopen(ctx->filepath, "rb");
    if (!ctx->file) {
        ESP_LOGE(TAG, "Failed to open file: %s", ctx->filepath);
        tt_lvgl_lock(portMAX_DELAY);
        ctx->state = STATE_IDLE;
        lv_label_set_text(ctx->lbl_status, "Error: File not found");
        update_ui(ctx);
        tt_lvgl_unlock();
        ctx->playback_task_handle = NULL;
        vTaskDelete(NULL);
        return;
    }
    
    fseek(ctx->file, 0, SEEK_END);
    ctx->file_size = ftell(ctx->file);
    fseek(ctx->file, 0, SEEK_SET);
    ctx->bytes_read_total = 0;
    
    mp3dec_init(&ctx->decoder);
    ctx->buffered_bytes = 0;
    ctx->eof = false;
    ctx->sample_rate = 0;
    ctx->channels = 0;
    ctx->stream_handle = NULL;
    
    ESP_LOGI(TAG, "Starting MP3 playback: %s (size: %d bytes)", ctx->filepath, ctx->file_size);
    
    while (ctx->state != STATE_IDLE) {
        if (ctx->state == STATE_PAUSED) {
            if (ctx->stream_handle != NULL) {
                // Close stream immediately on pause to stop DMA
                audio_stream_close(ctx->stream_handle);
                ctx->stream_handle = NULL;
                // Clear cached format to force re-open on resume
                ctx->sample_rate = 0;
                ctx->channels = 0;
            }
            vTaskDelay(pdMS_TO_TICKS(50));
            continue;
        }
        
        // Fill input buffer
        if (!ctx->eof && ctx->buffered_bytes < MP3_INPUT_BUFFER_SIZE) {
            size_t to_read = MP3_INPUT_BUFFER_SIZE - ctx->buffered_bytes;
            size_t read_bytes = fread(ctx->input_buf + ctx->buffered_bytes, 1, to_read, ctx->file);
            ctx->buffered_bytes += read_bytes;
            ctx->bytes_read_total += read_bytes;
            if (read_bytes == 0) {
                ctx->eof = true;
            }
        }
        
        if (ctx->buffered_bytes == 0 && ctx->eof) {
            ESP_LOGI(TAG, "Reached EOF");
            break;
        }
        
        // Decode one frame
        mp3dec_frame_info_t info;
        memset(&info, 0, sizeof(info));
        int samples = mp3dec_decode_frame(&ctx->decoder, ctx->input_buf, (int)ctx->buffered_bytes, ctx->pcm_buf, &info);
        
        if (info.frame_bytes <= 0) {
            if (ctx->eof) {
                break;
            }
            // Move 1 byte forward to resync
            memmove(ctx->input_buf, ctx->input_buf + 1, --ctx->buffered_bytes);
            continue;
        }
        
        size_t consumed = (size_t)info.frame_bytes;
        ctx->buffered_bytes -= consumed;
        memmove(ctx->input_buf, ctx->input_buf + consumed, ctx->buffered_bytes);
        
        if (samples > 0) {
            // Configure audio-stream if format changed
            if (ctx->sample_rate != info.hz || ctx->channels != info.channels) {
                if (ctx->stream_handle != NULL) {
                    audio_stream_close(ctx->stream_handle);
                    ctx->stream_handle = NULL;
                }

                struct AudioStreamConfig config = {
                    .sample_rate = (uint32_t)info.hz,
                    .bits_per_sample = 16,
                    .channels = (uint8_t)info.channels
                };

                error_t err = audio_stream_open_output(ctx->stream_dev, &config, &ctx->stream_handle);
                if (err != ERROR_NONE) {
                    ESP_LOGE(TAG, "Failed to open audio stream: %d", err);
                    break;
                }
                ctx->sample_rate = info.hz;
                ctx->channels = info.channels;
                ESP_LOGI(TAG, "Audio stream opened: %d Hz, %d channels", info.hz, info.channels);
            }
            
            // Adjust volume (after resampler)
            int vol = ctx->volume;
            int16_t* samples_ptr = (int16_t*)ctx->pcm_buf;
            size_t sample_count = (size_t)samples * info.channels;
            for (size_t i = 0; i < sample_count; ++i) {
                int32_t scaled = (int32_t)samples_ptr[i] * vol / 100;
                samples_ptr[i] = (int16_t)scaled;
            }
            
            // Play audio via audio-stream (resampled to native 44100)
            size_t offset = 0;
            size_t data_size = sample_count * sizeof(int16_t);
            bool write_err = false;
            while (offset < data_size && ctx->state == STATE_PLAYING) {
                size_t written = 0;
                error_t err = audio_stream_write(ctx->stream_handle, (uint8_t*)ctx->pcm_buf + offset, data_size - offset, &written, pdMS_TO_TICKS(500));
                if (err != ERROR_NONE || written == 0) {
                    ESP_LOGE(TAG, "Audio stream write failed: %d", err);
                    write_err = true;
                    break;
                }
                offset += written;
            }
            if (write_err) {
                break;
            }
        }
        
        // Update progress UI
        if (ctx->file_size > 0) {
            int pct = (int)((ctx->bytes_read_total - ctx->buffered_bytes) * 100 / ctx->file_size);
            if (pct < 0) pct = 0;
            if (pct > 100) pct = 100;
            tt_lvgl_lock(portMAX_DELAY);
            lv_bar_set_value(ctx->bar_progress, pct, LV_ANIM_OFF);
            tt_lvgl_unlock();
        }
    }
    
    fclose(ctx->file);
    ctx->file = NULL;
    
    // Close audio stream to clean up DMA / resampler task
    if (ctx->stream_handle != NULL) {
        audio_stream_close(ctx->stream_handle);
        ctx->stream_handle = NULL;
    }
    
    ESP_LOGI(TAG, "Playback task finished");
    
    tt_lvgl_lock(portMAX_DELAY);
    ctx->state = STATE_IDLE;
    update_ui(ctx);
    tt_lvgl_unlock();
    
    ctx->playback_task_handle = NULL;
    vTaskDelete(NULL);
}

/* ─── Callbacks ─── */
static void on_play_pause_click(lv_event_t* e) {
    AppCtx* ctx = (AppCtx*)lv_event_get_user_data(e);
    if (ctx->filepath[0] == '\0') return;
    
    if (ctx->state == STATE_IDLE) {
        ctx->state = STATE_PLAYING;
        update_ui(ctx);
        xTaskCreate(mp3_playback_task, "mp3_play", 6144, ctx, 6, &ctx->playback_task_handle);
    } else if (ctx->state == STATE_PLAYING) {
        ctx->state = STATE_PAUSED;
        update_ui(ctx);
    } else if (ctx->state == STATE_PAUSED) {
        ctx->state = STATE_PLAYING;
        update_ui(ctx);
    }
}

static void on_stop_click(lv_event_t* e) {
    AppCtx* ctx = (AppCtx*)lv_event_get_user_data(e);
    if (ctx->state == STATE_IDLE) return;
    
    ctx->state = STATE_IDLE;
    update_ui(ctx);
}

/* ─── App Lifecycle ─── */
static void onShowApp(AppHandle app, void* data, lv_obj_t* parent) {
    memset(&g_ctx, 0, sizeof(g_ctx));
    g_ctx.volume = 80;
    
    // Allocate memory buffers
    g_ctx.input_buf = (uint8_t*)malloc(MP3_INPUT_BUFFER_SIZE);
    g_ctx.pcm_buf = (mp3d_sample_t*)malloc(MINIMP3_MAX_SAMPLES_PER_FRAME * sizeof(mp3d_sample_t));
    
    // Find audio-stream device (resampling layer over ES8311 codec)
    g_ctx.stream_dev = device_find_by_name("audio-stream");
    if (!g_ctx.stream_dev) {
        ESP_LOGE(TAG, "Audio-stream device not found!");
    }
    
    // Parse launch parameters
    BundleHandle bundle = tt_app_get_parameters(app);
    if (bundle) {
        char file_param[256] = {0};
        if (tt_bundle_opt_string(bundle, "file", file_param, sizeof(file_param))) {
            // Safely resolve SD card path
            if (strncmp(file_param, "/sdcard", 7) == 0) {
                strncpy(g_ctx.filepath, file_param, sizeof(g_ctx.filepath) - 1);
            } else {
                if (file_param[0] == '/') {
                    snprintf(g_ctx.filepath, sizeof(g_ctx.filepath), "/sdcard%s", file_param);
                } else {
                    snprintf(g_ctx.filepath, sizeof(g_ctx.filepath), "/sdcard/%s", file_param);
                }
            }
        }
    }
    
    // ─── UI Layout ───
    lv_obj_t* toolbar = tt_lvgl_toolbar_create_for_app(parent, app);
    lv_obj_align(toolbar, LV_ALIGN_TOP_MID, 0, 0);
    
    // Player Card (rounded box)
    lv_obj_t* card = lv_obj_create(parent);
    lv_obj_set_size(card, lv_pct(90), lv_pct(70));
    lv_obj_align(card, LV_ALIGN_CENTER, 0, 15);
    lv_obj_set_style_radius(card, 15, 0);
    lv_obj_set_style_bg_color(card, lv_color_hex(0x1E1E2E), 0);
    lv_obj_set_style_border_color(card, lv_color_hex(0x313244), 0);
    lv_obj_set_style_border_width(card, 2, 0);
    lv_obj_set_flex_flow(card, LV_FLEX_FLOW_COLUMN);
    lv_obj_set_flex_align(card, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
    lv_obj_set_style_pad_all(card, 15, 0);
    lv_obj_set_style_pad_gap(card, 15, 0);
    
    // Audio Icon
    lv_obj_t* icon = lv_label_create(card);
    lv_label_set_text(icon, LV_SYMBOL_AUDIO);
    lv_obj_set_style_text_color(icon, lv_color_hex(0x89B4FA), 0);
    
    // Track Title
    g_ctx.lbl_title = lv_label_create(card);
    lv_obj_set_width(g_ctx.lbl_title, lv_pct(95));
    lv_obj_set_style_text_align(g_ctx.lbl_title, LV_TEXT_ALIGN_CENTER, 0);
    lv_obj_set_style_text_color(g_ctx.lbl_title, lv_color_hex(0xCDD6F4), 0);
    if (g_ctx.filepath[0] != '\0') {
        const char* last_slash = strrchr(g_ctx.filepath, '/');
        const char* filename = last_slash ? last_slash + 1 : g_ctx.filepath;
        lv_label_set_text(g_ctx.lbl_title, filename);
        lv_label_set_long_mode(g_ctx.lbl_title, LV_LABEL_LONG_SCROLL_CIRCULAR);
    } else {
        lv_label_set_text(g_ctx.lbl_title, "No File Parameter");
    }
    
    // Playback Status
    g_ctx.lbl_status = lv_label_create(card);
    lv_obj_set_style_text_color(g_ctx.lbl_status, lv_color_hex(0xA6ADC8), 0);
    
    // Progress Bar
    g_ctx.bar_progress = lv_bar_create(card);
    lv_obj_set_size(g_ctx.bar_progress, lv_pct(85), 8);
    lv_bar_set_range(g_ctx.bar_progress, 0, 100);
    lv_bar_set_value(g_ctx.bar_progress, 0, LV_ANIM_OFF);
    lv_obj_set_style_bg_color(g_ctx.bar_progress, lv_color_hex(0x45475A), LV_PART_MAIN);
    lv_obj_set_style_bg_color(g_ctx.bar_progress, lv_color_hex(0x89B4FA), LV_PART_INDICATOR);
    
    // Controls Container
    lv_obj_t* ctrl_box = lv_obj_create(card);
    lv_obj_remove_style_all(ctrl_box);
    lv_obj_set_size(ctrl_box, lv_pct(90), 45);
    lv_obj_set_flex_flow(ctrl_box, LV_FLEX_FLOW_ROW);
    lv_obj_set_flex_align(ctrl_box, LV_FLEX_ALIGN_SPACE_EVENLY, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
    
    // Play/Pause Button
    g_ctx.btn_play_pause = lv_btn_create(ctrl_box);
    lv_obj_set_size(g_ctx.btn_play_pause, 100, 36);
    lv_obj_set_style_radius(g_ctx.btn_play_pause, 18, 0);
    lv_obj_set_style_bg_color(g_ctx.btn_play_pause, lv_color_hex(0x89B4FA), 0);
    lv_obj_set_style_text_color(g_ctx.btn_play_pause, lv_color_hex(0x11111B), 0);
    lv_obj_t* lbl_play = lv_label_create(g_ctx.btn_play_pause);
    lv_label_set_text(lbl_play, LV_SYMBOL_PLAY " Play");
    lv_obj_center(lbl_play);
    lv_obj_add_event_cb(g_ctx.btn_play_pause, on_play_pause_click, LV_EVENT_CLICKED, &g_ctx);
    
    // Stop Button
    g_ctx.btn_stop = lv_btn_create(ctrl_box);
    lv_obj_set_size(g_ctx.btn_stop, 100, 36);
    lv_obj_set_style_radius(g_ctx.btn_stop, 18, 0);
    lv_obj_set_style_bg_color(g_ctx.btn_stop, lv_color_hex(0xF38BA8), 0);
    lv_obj_set_style_text_color(g_ctx.btn_stop, lv_color_hex(0x11111B), 0);
    lv_obj_t* lbl_stop = lv_label_create(g_ctx.btn_stop);
    lv_label_set_text(lbl_stop, LV_SYMBOL_STOP " Stop");
    lv_obj_center(lbl_stop);
    lv_obj_add_event_cb(g_ctx.btn_stop, on_stop_click, LV_EVENT_CLICKED, &g_ctx);
    
    if (!g_ctx.stream_dev) {
        lv_label_set_text(g_ctx.lbl_status, "Error: Audio Not Found");
        lv_obj_add_state(g_ctx.btn_play_pause, LV_STATE_DISABLED);
        lv_obj_add_state(g_ctx.btn_stop, LV_STATE_DISABLED);
    } else if (!g_ctx.input_buf || !g_ctx.pcm_buf) {
        lv_label_set_text(g_ctx.lbl_status, "Error: Out of Memory");
        lv_obj_add_state(g_ctx.btn_play_pause, LV_STATE_DISABLED);
        lv_obj_add_state(g_ctx.btn_stop, LV_STATE_DISABLED);
    } else {
        g_ctx.state = STATE_IDLE;
        update_ui(&g_ctx);
        
        // Auto-play if a file parameter was provided
        if (g_ctx.filepath[0] != '\0') {
            g_ctx.state = STATE_PLAYING;
            update_ui(&g_ctx);
            xTaskCreate(mp3_playback_task, "mp3_play", 6144, &g_ctx, 6, &g_ctx.playback_task_handle);
        }
    }
}

static void onHideApp(AppHandle app, void* data) {
    if (g_ctx.state != STATE_IDLE) {
        g_ctx.state = STATE_IDLE; // Signal task to stop
    }
    
    // Wait for the task to finish self-deletion to prevent resource leaks
    while (g_ctx.playback_task_handle != NULL) {
        vTaskDelay(pdMS_TO_TICKS(10));
    }
    
    // Close any open audio stream
    if (g_ctx.stream_handle != NULL) {
        audio_stream_close(g_ctx.stream_handle);
        g_ctx.stream_handle = NULL;
    }
    
    if (g_ctx.input_buf) {
        free(g_ctx.input_buf);
        g_ctx.input_buf = NULL;
    }
    if (g_ctx.pcm_buf) {
        free(g_ctx.pcm_buf);
        g_ctx.pcm_buf = NULL;
    }
}

int main(int argc, char* argv[]) {
    tt_app_register((AppRegistration) {
        .onShow = onShowApp,
        .onHide = onHideApp
    });
    return 0;
}
