#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include "sensordialog.h"
#include "flowlayout.h"
#include "paginationbar.h"

#include <QComboBox>
#include <QGridLayout>
#include <QResizeEvent>
#include <QScrollArea>
#include <QMessageBox>
#include <QTimer>
#include <QStackedWidget>


#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    httpClient = new HttpClient(this);
    sensorService = new SensorService(httpClient, this);

    //sensor tab
    SetupSensorTab();
    startSensorTabRefreshTimer();

    QTreeWidgetItem *group1 = new QTreeWidgetItem(ui->treeWidget);
    group1->setText(0, "1 Группа");

    QTreeWidgetItem *group2 = new QTreeWidgetItem(ui->treeWidget);
    group2->setText(0, "2 Группа");

    QTreeWidgetItem *group3 = new QTreeWidgetItem(ui->treeWidget);
    group3->setText(0, "3 Группа");

    for (int i = 1; i <= 8; ++i) {
        QTreeWidgetItem *sensorItem = new QTreeWidgetItem(group2);
        sensorItem->setText(0, QString("%1 Датчик").arg(i));
        sensorItem->setCheckState(0, (i >= 2 && i <= 4) ? Qt::Checked : Qt::Unchecked);
    }

    for (int i = 1; i <= 3; ++i) {
        QTreeWidgetItem *sensorItem = new QTreeWidgetItem(group1);
        sensorItem->setText(0, QString("%1 Датчик").arg(i));
        sensorItem->setCheckState(0, (i >= 2 && i <= 4) ? Qt::Checked : Qt::Unchecked);
    }

    for (int i = 1; i <= 4; ++i) {
        QTreeWidgetItem *sensorItem = new QTreeWidgetItem(group3);
        sensorItem->setText(0, QString("%1 Датчик").arg(i));
        sensorItem->setCheckState(0, (i >= 2 && i <= 4) ? Qt::Checked : Qt::Unchecked);
    }

    int totalPages = 100;
    auto *paginationBar = new PaginationBar(totalPages, this);

    ui->paginationBarLayout->addStretch();
    ui->paginationBarLayout->addWidget(paginationBar);
    ui->paginationBarLayout->addStretch();

}

void MainWindow::SetupSensorTab() {
    QScrollArea *scrollArea = new QScrollArea(this);
    scrollArea->setStyleSheet(
        "QScrollArea {"
        "    background: transparent;"
        "}"
        "QScrollBar:vertical {"
        "    background: #ebebeb;"
        "    width: 10px;"
        "    border-radius: 5px;"
        "}"
        "QScrollBar::handle:vertical {"
        "    background: #6d6d6d;"
        "    border-radius: 5px;"
        "    min-height: 20px;"
        "}"
        "QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {"
        "    border: none;"
        "    background: none;"
        "    color: none;"
        "}"
        "QScrollBar::sub-line:vertical, QScrollBar::add-line:vertical {"
        "    background: transparent;"
        "    border: none;"
        "}"
        "QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {"
        "    background: transparent;"
        "}"
        );
    scrollArea->setWidgetResizable(true);
    scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    widgetContainer = new QWidget(scrollArea);
    widgetContainer->setStyleSheet("background: transparent;");
    layout = new FlowLayout(widgetContainer, 10, 10, 10);

    widgetContainer->setLayout(layout);
    scrollArea->setWidget(widgetContainer);
    ui->sensorsLayout->addWidget(scrollArea);

    connect(ui->search, &QLineEdit::textChanged, this, &MainWindow::onSearchTextChanged);
    ui->showHiddenSelect->addItems({"Да", "Нет"});
    connect(ui->groupSelect, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &MainWindow::onGroupSelected);
    connect(ui->showHiddenSelect, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &MainWindow::onShowHiddenSelected);

    loadSensorGroups();
}

void MainWindow::startSensorTabRefreshTimer() {
    QTimer *refreshTimer = new QTimer(this);

    connect(refreshTimer, &QTimer::timeout, this, [this]() {
        if (ui->tabWidget->currentWidget() == ui->sensorsTab) {
            updateDisplayedWidgets();
        }
    });

    refreshTimer->start(5000); //5 sec
}

void MainWindow::showSensorDialog(SensorWidget *sensor)
{
    SensorDialog *dialog = new SensorDialog(this, sensor, httpClient);
    dialog->setWindowModality(Qt::ApplicationModal);

    this->setStyleSheet("QMainWindow { background-color: rgba(0, 0, 0, 1); }");

    connect(dialog, &SensorDialog::resultReady, this, &MainWindow::onSensorDialogFinished);

    dialog->exec();
}

void MainWindow::onSensorDialogFinished(int result)
{
    this->setStyleSheet("");

    switch (result) {
    case SensorDialog::SaveSuccess:
        updateDisplayedWidgets();
        break;

    case SensorDialog::SaveError:
        QMessageBox::critical(nullptr, "Ошибка", "Данные не сохранены, попробуйте еще раз");
        break;

    case SensorDialog::NoSave:
        updateDisplayedWidgets();
        break;

    default:
        break;
    }
}

void MainWindow::loadSensorGroups() {
    QStringList groups = sensorService->getSensorGroups();

    if (groups.isEmpty()) {
        QTimer::singleShot(5000, this, &MainWindow::loadSensorGroups);
        return;
    }

    groups.sort(Qt::CaseInsensitive);
    ui->groupSelect->clear();
    ui->groupSelect->addItems(groups);

    if (!groups.isEmpty()) {
        loadSensors(groups.first());
    }
}

void MainWindow::loadSensors(const QString& group) {
    QList<Sensor> sensors = sensorService->getSensors(group);

    const auto &existingWidgets = widgetContainer->findChildren<SensorWidget *>();
    for (SensorWidget *widget : existingWidgets) {
        delete widget;
    }

    layout->clear();

    for (const Sensor& sensor : sensors) {
        SensorWidget* s = new SensorWidget(nullptr, sensor);
        layout->addWidget(s);

        connect(s, &SensorWidget::clicked, this, &MainWindow::showSensorDialog);
    }

    widgetContainer->update();
}

void MainWindow::updateDisplayedWidgets()
{
    QString selectedGroup = ui->groupSelect->currentText();
    QString showHidden = ui->showHiddenSelect->currentText();
    QString searchText = ui->search->text();

    // Загружаем датчики только для выбранной группы
    QList<Sensor> sensors = sensorService->getSensors(selectedGroup);

    // Храним уже добавленные виджеты
    QMap<QString, SensorWidget*> existingWidgets;

    // Сохраняем существующие виджеты и их сенсоры для последующего обновления
    const auto &widgets = widgetContainer->findChildren<SensorWidget *>();
    for (SensorWidget *widget : widgets) {
        existingWidgets[widget->getSensor().id] = widget;
    }

    layout->clear();  // Очищаем layout, но не удаляем сами виджеты

    // Проходим по новым датчикам и добавляем их в layout, если они ещё не добавлены
    for (const Sensor& sensor : sensors) {
        SensorWidget* widget = nullptr;

        // Проверяем, существует ли виджет для данного сенсора
        if (existingWidgets.contains(sensor.id)) {
            widget = existingWidgets[sensor.id];
            widget->setSensor(sensor);  // Обновляем данные существующего виджета
        } else {
            widget = new SensorWidget(nullptr, sensor);
            connect(widget, &SensorWidget::clicked, this, &MainWindow::showSensorDialog);
        }

        // Применяем фильтрацию по условиям
        bool matchesHidden = (showHidden == "Да") || !sensor.isHide;
        bool matchesSearch = sensor.name.contains(searchText, Qt::CaseInsensitive);

        if (matchesHidden && matchesSearch) {
            layout->addWidget(widget);
            widget->show();
        } else {
            widget->hide();
        }
    }

    widgetContainer->update();  // Обновляем виджеты в контейнере
}

void MainWindow::onGroupSelected(int index)
{
    Q_UNUSED(index);
    loadSensors(ui->groupSelect->currentText());
    updateDisplayedWidgets();
}

void MainWindow::onShowHiddenSelected(int index)
{
    Q_UNUSED(index);
    updateDisplayedWidgets();
}

void MainWindow::onSearchTextChanged(const QString &text)
{
    Q_UNUSED(text);
    if (text.isEmpty()) {
        ui->search->setStyleSheet(R"(
            QLineEdit {
            width: 778px;
            height: 60px;
            border: 2px solid #DCD174;
            font-family: Inter;
            font-size: 26px;
            font-weight: 400;
            line-height: 31.47px;
            text-align: left;
            background: #00000000;
            color: #a6a6a6;
            }

        )");
    } else {
        ui->search->setStyleSheet(R"(
            QLineEdit {
            width: 778px;
            height: 60px;
            border: 2px solid #DCD174;
            font-family: Inter;
            font-size: 26px;
            font-weight: 400;
            line-height: 31.47px;
            text-align: left;
            background: #00000000;
            color: #13385F;
            }
        )");
    }
    updateDisplayedWidgets();
}

MainWindow::~MainWindow()
{
    delete ui;
}
