// Copyright (C) 2026 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

#include "daypage.h"

#include "calendardemo.h"
#include <QtWidgets>
#include <QtOrganizer/qorganizer.h>

QTORGANIZER_USE_NAMESPACE

Q_DECLARE_METATYPE(QOrganizerItem)

DayPage::DayPage(QWidget *parent)
    :QWidget(parent),
    m_manager(0),
    m_dateLabel(0),
    m_itemList(0),
    m_menuBar(0)
{
    QVBoxLayout *mainLayout = new QVBoxLayout();

    QHBoxLayout *dateLayout = new QHBoxLayout();
    m_dateLabel = new QLabel(this);
    m_dateLabel->setAlignment(Qt::AlignCenter);
    dateLayout->addWidget(m_dateLabel);
    dateLayout->addStretch();

    QPushButton* backButton = new QPushButton("View Month",this);
    connect(backButton,SIGNAL(clicked()),this,SLOT(viewMonthClicked()));
    dateLayout->addWidget(backButton);
    mainLayout->addLayout(dateLayout);

    m_itemList = new QListWidget(this);
    mainLayout->addWidget(m_itemList);
    connect(m_itemList, SIGNAL(itemDoubleClicked(QListWidgetItem *)), this, SLOT(itemDoubleClicked(QListWidgetItem *)));

    QHBoxLayout* hbLayout = new QHBoxLayout();
    QPushButton* editEventButton = new QPushButton("Edit",this);
    connect(editEventButton,SIGNAL(clicked()),this,SLOT(editItem()));
    hbLayout->addWidget(editEventButton);
    QPushButton* removeEventButton = new QPushButton("Remove",this);
    connect(removeEventButton,SIGNAL(clicked()),this,SLOT(removeItem()));
    hbLayout->addWidget(removeEventButton);
    mainLayout->addLayout(hbLayout);
    setLayout(mainLayout);
}

DayPage::~DayPage()
{
}

void DayPage::refresh()
{

    m_dateLabel->setText(m_day.toString());
    m_itemList->clear();

    // Today's item
    QList<QOrganizerItem> items = m_manager->items(m_day.startOfDay(), QDateTime(m_day, QTime(23, 59, 59)));

    foreach (const QOrganizerItem &item, items)
    {
        QOrganizerEventTime eventTime = item.detail(QOrganizerItemDetail::TypeEventTime);
        if (!eventTime.isEmpty()) {
            QString time = eventTime.startDateTime().time().toString("hh:mm");
            QListWidgetItem* listItem = new QListWidgetItem();
            if (item.type() == QOrganizerItemType::TypeEventOccurrence)
                listItem->setText(QString("Event occurrence:%1-%2").arg(time).arg(item.displayLabel()));
            else
                listItem->setText(QString("Event:%1-%2").arg(time).arg(item.displayLabel()));
            QVariant data = QVariant::fromValue<QOrganizerItem>(item);
            listItem->setData(ORGANIZER_ITEM_ROLE, data);
            m_itemList->addItem(listItem);
        }

        QOrganizerTodoTime todoTime = item.detail(QOrganizerItemDetail::TypeTodoTime);
        if (!todoTime.isEmpty()) {
            QString time = todoTime.startDateTime().time().toString("hh:mm");
            QListWidgetItem* listItem = new QListWidgetItem();
            listItem->setText(QString("Todo:%1-%2").arg(time).arg(item.displayLabel()));
            QVariant data = QVariant::fromValue<QOrganizerItem>(item);
            listItem->setData(ORGANIZER_ITEM_ROLE, data);
            m_itemList->addItem(listItem);
        }

        QOrganizerJournalTime journalTime = item.detail(QOrganizerItemDetail::TypeJournalTime);
        if (!journalTime.isEmpty()) {
            QString time = journalTime.entryDateTime().time().toString("hh:mm");
            QListWidgetItem* listItem = new QListWidgetItem();
            listItem->setText(QString("Journal:%1-%2").arg(time).arg(item.displayLabel()));
            QVariant data = QVariant::fromValue<QOrganizerItem>(item);
            listItem->setData(ORGANIZER_ITEM_ROLE, data);
            m_itemList->addItem(listItem);
        }

        // TODO: other item types
    }

    if (m_itemList->count() == 0)
        m_itemList->addItem("(no entries)");
}

void DayPage::changeManager(QOrganizerManager *manager)
{
    m_manager = manager;
}

void DayPage::dayChanged(QDate date)
{
    m_day = date;
}

void DayPage::itemDoubleClicked(QListWidgetItem *listItem)
{
    if (!listItem)
        return;

    QOrganizerItem organizerItem = listItem->data(ORGANIZER_ITEM_ROLE).value<QOrganizerItem>();
    if (!organizerItem.isEmpty())
        emit showEditPage(organizerItem);
}

void DayPage::viewMonthClicked()
{
    emit showMonthPage();
}

void DayPage::editItem()
{
    QListWidgetItem *listItem = m_itemList->currentItem();
    if (!listItem)
        return;

    QOrganizerItem organizerItem = listItem->data(ORGANIZER_ITEM_ROLE).value<QOrganizerItem>();
    if (!organizerItem.isEmpty())
        emit showEditPage(organizerItem);
}

void DayPage::removeItem()
{
    QListWidgetItem *listItem = m_itemList->currentItem();
    if (!listItem)
        return;

    QOrganizerItem organizerItem = listItem->data(ORGANIZER_ITEM_ROLE).value<QOrganizerItem>();
    if (organizerItem.isEmpty())
        return;

    if (organizerItem.type() == QOrganizerItemType::TypeEventOccurrence
        || organizerItem.type() == QOrganizerItemType::TypeTodoOccurrence) {
        // Here we could ask if the user wishes to remove only the occurrence (meaning we would
        // add an exception date to the parent item), or the parent item. The current
        // implementation is to remove the parent (including all the occurrences).
        m_manager->removeItem(organizerItem.detail(QOrganizerItemDetail::TypeParent).value<QOrganizerItemId>(QOrganizerItemParent::FieldParentId));
    } else {
        m_manager->removeItem(organizerItem.id());
    }

    if (m_manager->error())
        QMessageBox::information(this, "Failed!", QString("Failed to remove item!\n(error code %1)").arg(m_manager->error()));
    else
        delete m_itemList->takeItem(m_itemList->currentRow());

    if (m_itemList->count() == 0)
        m_itemList->addItem("(no entries)");
}

void DayPage::showEvent(QShowEvent *event)
{
    window()->setWindowTitle(m_day.toString("dddd"));
    QWidget::showEvent(event);
}

