#include <Arduino.h>
#include <Wire.h>
#include <lvgl.h>
#include <Arduino_GFX_Library.h>
#include "pin_config.h"
#include "TouchDrvCSTXXX.hpp"

#define EXAMPLE_LVGL_TICK_PERIOD_MS 2

static lv_disp_draw_buf_t gDrawBuf;
static lv_color_t *gBuf1 = nullptr;
static lv_color_t *gBuf2 = nullptr;
static lv_obj_t *gStatusLabel = nullptr;
static uint32_t gPressCount = 0;

static TouchDrvCST92xx gTouch;
static int16_t gTouchX[5];
static int16_t gTouchY[5];

Arduino_DataBus *gBus = new Arduino_ESP32QSPI(
    LCD_CS, LCD_SCLK, LCD_SDIO0, LCD_SDIO1, LCD_SDIO2, LCD_SDIO3);
Arduino_CO5300 *gfx = new Arduino_CO5300(
    gBus, LCD_RESET, 0, LCD_WIDTH, LCD_HEIGHT, 0, 0, 0, 0);

static void lvglFlushCb(lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *colorP) {
  uint32_t w = area->x2 - area->x1 + 1;
  uint32_t h = area->y2 - area->y1 + 1;
#if (LV_COLOR_16_SWAP != 0)
  gfx->draw16bitBeRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
#else
  gfx->draw16bitRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
#endif
  lv_disp_flush_ready(disp);
}

static void lvglTick(void *arg) {
  LV_UNUSED(arg);
  lv_tick_inc(EXAMPLE_LVGL_TICK_PERIOD_MS);
}

static void lvglTouchRead(lv_indev_drv_t *indevDrv, lv_indev_data_t *data) {
  LV_UNUSED(indevDrv);
  uint8_t touched = gTouch.getPoint(gTouchX, gTouchY, gTouch.getSupportTouchPoint());
  if (touched > 0) {
    data->state = LV_INDEV_STATE_PR;
    data->point.x = gTouchX[0];
    data->point.y = gTouchY[0];
    return;
  }

  data->state = LV_INDEV_STATE_REL;
}

static void buttonEventCb(lv_event_t *event) {
  if (lv_event_get_code(event) != LV_EVENT_CLICKED) {
    return;
  }

  lv_obj_t *btn = lv_event_get_target(event);
  const char *name = (const char *)lv_event_get_user_data(event);
  gPressCount++;

  lv_obj_set_style_outline_width(btn, 4, 0);
  lv_obj_set_style_outline_color(btn, lv_color_hex(0xFFF3B0), 0);
  lv_obj_set_style_outline_pad(btn, 2, 0);

  String status = "Pressed: ";
  status += name;
  status += " (#";
  status += String(gPressCount);
  status += ")";
  lv_label_set_text(gStatusLabel, status.c_str());

  Serial.println(status);
}

static void createButton(lv_obj_t *parent, const char *labelText, lv_coord_t col, lv_coord_t row, uint32_t colorHex) {
  static const lv_coord_t kStartX = 22;
  static const lv_coord_t kStartY = 122;
  static const lv_coord_t kButtonW = 134;
  static const lv_coord_t kButtonH = 64;
  static const lv_coord_t kGapX = 18;
  static const lv_coord_t kGapY = 16;

  lv_obj_t *btn = lv_btn_create(parent);
  lv_obj_set_size(btn, kButtonW, kButtonH);
  lv_obj_set_pos(btn, kStartX + col * (kButtonW + kGapX), kStartY + row * (kButtonH + kGapY));
  lv_obj_set_style_radius(btn, 16, 0);
  lv_obj_set_style_bg_color(btn, lv_color_hex(colorHex), 0);
  lv_obj_set_style_border_width(btn, 2, 0);
  lv_obj_set_style_border_color(btn, lv_color_hex(0x7F96B0), 0);
  lv_obj_set_style_shadow_width(btn, 0, 0);
  lv_obj_add_event_cb(btn, buttonEventCb, LV_EVENT_CLICKED, (void *)labelText);

  lv_obj_t *label = lv_label_create(btn);
  lv_label_set_text(label, labelText);
  lv_obj_set_style_text_font(label, &lv_font_montserrat_18, 0);
  lv_obj_set_style_text_color(label, lv_color_hex(0xFFFFFF), 0);
  lv_obj_center(label);
}

static void createUi() {
  lv_obj_t *screen = lv_scr_act();
  lv_obj_set_style_bg_color(screen, lv_color_hex(0x0B1320), 0);
  lv_obj_set_style_bg_opa(screen, LV_OPA_COVER, 0);

  lv_obj_t *title = lv_label_create(screen);
  lv_label_set_text(title, "LVGL INTERACTION TEST");
  lv_obj_set_style_text_color(title, lv_color_hex(0xFFFFFF), 0);
  lv_obj_set_style_text_font(title, &lv_font_montserrat_22, 0);
  lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 14);

  lv_obj_t *subtitle = lv_label_create(screen);
  lv_label_set_text(subtitle, "Tap buttons. Bottom label must change on every press.");
  lv_obj_set_width(subtitle, 420);
  lv_label_set_long_mode(subtitle, LV_LABEL_LONG_WRAP);
  lv_obj_set_style_text_color(subtitle, lv_color_hex(0xD5DCE5), 0);
  lv_obj_set_style_text_font(subtitle, &lv_font_montserrat_14, 0);
  lv_obj_align(subtitle, LV_ALIGN_TOP_MID, 0, 48);

  createButton(screen, "Status", 0, 0, 0x355C7D);
  createButton(screen, "Connect", 1, 0, 0x2A9D8F);
  createButton(screen, "Wallet", 2, 0, 0x457B9D);
  createButton(screen, "Requests", 0, 1, 0xE76F51);
  createButton(screen, "Settings", 1, 1, 0x8D5A97);
  createButton(screen, "Register", 2, 1, 0x6A994E);
  createButton(screen, "Approve", 0, 2, 0xBC6C25);
  createButton(screen, "Reject", 1, 2, 0xB56576);
  createButton(screen, "Back", 2, 2, 0x6C757D);

  lv_obj_t *statusPanel = lv_obj_create(screen);
  lv_obj_set_size(statusPanel, 436, 56);
  lv_obj_align(statusPanel, LV_ALIGN_BOTTOM_MID, 0, -16);
  lv_obj_set_style_radius(statusPanel, 14, 0);
  lv_obj_set_style_bg_color(statusPanel, lv_color_hex(0x162033), 0);
  lv_obj_set_style_border_width(statusPanel, 2, 0);
  lv_obj_set_style_border_color(statusPanel, lv_color_hex(0x415A77), 0);
  lv_obj_set_style_pad_all(statusPanel, 10, 0);

  gStatusLabel = lv_label_create(statusPanel);
  lv_label_set_text(gStatusLabel, "Pressed: none");
  lv_obj_set_style_text_font(gStatusLabel, &lv_font_montserrat_18, 0);
  lv_obj_set_style_text_color(gStatusLabel, lv_color_hex(0xFFFFFF), 0);
  lv_obj_center(gStatusLabel);
}

void setup() {
  Serial.begin(115200);
  Wire.begin(IIC_SDA, IIC_SCL);

  pinMode(TP_RST, OUTPUT);
  pinMode(TP_INT, INPUT);
  digitalWrite(TP_RST, LOW);
  delay(30);
  digitalWrite(TP_RST, HIGH);
  delay(50);
  delay(1000);

  gTouch.setPins(TP_RST, TP_INT);
  bool touchOk = gTouch.begin(Wire, 0x5A, IIC_SDA, IIC_SCL);
  if (!touchOk) {
    Serial.println("Touch init failed");
  } else {
    Serial.print("Touch model: ");
    Serial.println(gTouch.getModelName());
    gTouch.sleep();
    gTouch.reset();
    gTouch.setMaxCoordinates(480, 480);
    gTouch.setSwapXY(true);
    gTouch.setMirrorXY(true, false);
  }

  gfx->begin();
  gBus->writeC8D8(0x36, 0xA0);
  gfx->setBrightness(220);
  gfx->fillScreen(0x0000);

  lv_init();

  uint32_t screenWidth = gfx->width();
  uint32_t screenHeight = gfx->height();
  gBuf1 = (lv_color_t *)heap_caps_malloc(screenWidth * screenHeight / 4 * sizeof(lv_color_t), MALLOC_CAP_DMA);
  gBuf2 = (lv_color_t *)heap_caps_malloc(screenWidth * screenHeight / 4 * sizeof(lv_color_t), MALLOC_CAP_DMA);
  lv_disp_draw_buf_init(&gDrawBuf, gBuf1, gBuf2, screenWidth * screenHeight / 4);

  static lv_disp_drv_t dispDrv;
  lv_disp_drv_init(&dispDrv);
  dispDrv.hor_res = screenWidth;
  dispDrv.ver_res = screenHeight;
  dispDrv.flush_cb = lvglFlushCb;
  dispDrv.draw_buf = &gDrawBuf;
  lv_disp_drv_register(&dispDrv);

  static lv_indev_drv_t indevDrv;
  lv_indev_drv_init(&indevDrv);
  indevDrv.type = LV_INDEV_TYPE_POINTER;
  indevDrv.read_cb = lvglTouchRead;
  lv_indev_drv_register(&indevDrv);

  const esp_timer_create_args_t lvglTickTimerArgs = {
      .callback = &lvglTick,
      .name = "lvgl_tick"};
  esp_timer_handle_t lvglTickTimer = nullptr;
  esp_timer_create(&lvglTickTimerArgs, &lvglTickTimer);
  esp_timer_start_periodic(lvglTickTimer, EXAMPLE_LVGL_TICK_PERIOD_MS * 1000);

  createUi();
  Serial.println("LVGL interaction test ready");
}

void loop() {
  lv_timer_handler();
  delay(5);
}
