#include "mainwindow.h"
#include <QApplication>
#include <QScreen>
#include <QResizeEvent>
#include <QFileInfo>
#include <QMessageBox>
#include <stdexcept>

// Define the static constant for the default database path
const QString MainWindow::DEFAULT_DB_PATH = "/home/master/screenshot_ocr.db";

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , m_dbManager(new DatabaseManager(this))
    , m_searchDelayTimer(new QTimer(this))
    , m_hasValidDatabase(false)
{
    // Set window title and size
    setWindowTitle(tr("Screenshot OCR Gallery"));
    resize(DEFAULT_WINDOW_WIDTH, DEFAULT_WINDOW_HEIGHT);
    
    // Remove fixed minimum size to allow for single column layout at any width
    // setMinimumSize(640, 480);
    
    // Center window on screen
    QScreen *screen = QGuiApplication::primaryScreen();
    if (screen) {
        const QRect availableGeometry = screen->availableGeometry();
        const QSize size = geometry().size();
        move((availableGeometry.width() - size.width()) / 2,
             (availableGeometry.height() - size.height()) / 2);
    }
    
    // Set up UI
    createLayout();
    
    // Initialize timer for delayed search
    m_searchDelayTimer->setSingleShot(true);
    m_searchDelayTimer->setInterval(SEARCH_DELAY_MS);
    connect(m_searchDelayTimer, &QTimer::timeout, this, &MainWindow::performSearch);
    
    // Initialize database and display images
    initializeDatabase();
    displayAllImages();
    
    // Set focus to search bar
    m_searchBar->setFocus();
    
    // Set status bar
    statusBar()->showMessage(tr("Ready"));
    updateStatusBar();
}

MainWindow::~MainWindow()
{
    // All QObjects will be automatically deleted via parent-child relationship
}

void MainWindow::createLayout()
{
    // Create central widget
    m_centralWidget = new QWidget(this);
    setCentralWidget(m_centralWidget);
    
    // Create main layout
    m_mainLayout = new QVBoxLayout(m_centralWidget);
    m_mainLayout->setSpacing(5);  // Reduce spacing between elements
    m_mainLayout->setContentsMargins(5, 5, 5, 5);  // Reduce margins
    
    // Create title label
    m_titleLabel = new QLabel(tr("Screenshot OCR Gallery"), this);
    QFont titleFont = m_titleLabel->font();
    titleFont.setPointSize(16);
    titleFont.setBold(true);
    m_titleLabel->setFont(titleFont);
    m_titleLabel->setAlignment(Qt::AlignCenter);
    
    // Create search bar
    m_searchBar = new QLineEdit(this);
    m_searchBar->setPlaceholderText(tr("Search OCR text..."));
    m_searchBar->setClearButtonEnabled(true);
    
    // Create gallery widget
    m_imageGallery = new ImageGallery(this);
    m_imageGallery->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    
    // Add widgets to layout
    m_mainLayout->addWidget(m_titleLabel);
    m_mainLayout->addWidget(m_searchBar);
    m_mainLayout->addWidget(m_imageGallery, 1);
    
    // Connect signals
    connect(m_searchBar, &QLineEdit::textChanged, this, &MainWindow::handleSearchTextChanged);
}

void MainWindow::initializeDatabase()
{
    // Check if database file exists
    QFileInfo dbFileInfo(DEFAULT_DB_PATH);
    if (!dbFileInfo.exists() || !dbFileInfo.isFile()) {
        QString errorMsg = tr("Database file not found: %1").arg(DEFAULT_DB_PATH);
        statusBar()->showMessage(errorMsg, 10000);
        QMessageBox::critical(this, tr("Database Error"), errorMsg);
        qDebug() << "Database file not found:" << DEFAULT_DB_PATH;
        m_hasValidDatabase = false;
        return;
    }
    
    // Try to initialize database
    if (!m_dbManager->initialize(DEFAULT_DB_PATH)) {
        QString errorMsg = tr("Failed to connect to database");
        statusBar()->showMessage(errorMsg, 10000);
        QMessageBox::warning(this, tr("Database Error"), 
                             tr("Failed to connect to database: %1\nThe application will continue with limited functionality.")
                             .arg(DEFAULT_DB_PATH));
        qDebug() << "Failed to initialize database";
        m_hasValidDatabase = false;
    } else {
        statusBar()->showMessage(tr("Connected to database"), 3000);
        m_imageGallery->setDatabaseManager(m_dbManager);
        m_hasValidDatabase = true;
    }
}

void MainWindow::displayAllImages()
{
    if (!m_hasValidDatabase) {
        m_imageGallery->clearGallery();
        statusBar()->showMessage(tr("No database connection available. Cannot display images."), 5000);
        return;
    }
    
    QList<DatabaseManager::ImageItem> allImages = m_dbManager->getAllImages();
    if (allImages.isEmpty()) {
        statusBar()->showMessage(tr("No images found in database"), 5000);
    }
    
    m_imageGallery->displayImages(allImages);
    updateStatusBar();
}

void MainWindow::handleSearchTextChanged()
{
    if (!m_hasValidDatabase) {
        statusBar()->showMessage(tr("Database not available for search"), 3000);
        return;
    }
    
    // If search bar is cleared, immediately show all images
    if (m_searchBar->text().isEmpty()) {
        m_lastSearchText.clear();
        m_searchDelayTimer->stop();
        displayAllImages(); // Show all images immediately
        return; // Skip the timer since we've already updated
    }
    
    // For non-empty searches, restart the timer each time the user types
    m_searchDelayTimer->start();
}

void MainWindow::performSearch()
{
    if (!m_hasValidDatabase) {
        statusBar()->showMessage(tr("Cannot perform search: No database connection"), 3000);
        return;
    }
    
    QString currentText = m_searchBar->text();
    
    // Only perform search if text has changed
    if (currentText != m_lastSearchText) {
        m_lastSearchText = currentText;
        
        try {
            m_imageGallery->handleSearchTextChanged(currentText);
            updateStatusBar();
        } catch (const std::exception &e) {
            QString errorMsg = tr("Search error: %1").arg(e.what());
            statusBar()->showMessage(errorMsg, 5000);
            qDebug() << errorMsg;
        }
    }
}

void MainWindow::updateStatusBar()
{
    if (!m_hasValidDatabase) {
        statusBar()->showMessage(tr("Database not connected"));
        return;
    }
    
    try {
        int imageCount = m_dbManager->searchImages(m_lastSearchText).count();
        int totalImages = m_dbManager->getAllImages().count();
        
        if (m_lastSearchText.isEmpty()) {
            statusBar()->showMessage(tr("Displaying all %1 images").arg(totalImages));
        } else {
            statusBar()->showMessage(tr("Found %1 of %2 images matching \"%3\"")
                                    .arg(imageCount)
                                    .arg(totalImages)
                                    .arg(m_lastSearchText));
        }
    } catch (const std::exception &e) {
        statusBar()->showMessage(tr("Error updating status: %1").arg(e.what()), 5000);
    }
}

void MainWindow::resizeEvent(QResizeEvent *event)
{
    QMainWindow::resizeEvent(event);
    
    // Notify the image gallery of the resize event
    if (m_imageGallery) {
        // The gallery will handle its own layout updates through its resize event
        // Just make sure it's visible and has the correct size policy
        m_imageGallery->setVisible(true);
    }
    
    // Update status bar to show current window dimensions
    // This helps with debugging layout issues
    if (statusBar() && statusBar()->isVisible()) {
        QString sizeInfo = QString("Window size: %1×%2").arg(width()).arg(height());
        statusBar()->showMessage(sizeInfo, 1000);
    }
}