#pragma once
#include "completion-model.hpp"
#include "list-view-host.hpp"
#include "search-files-model.hpp"
#include "services/files-service/abstract-file-indexer.hpp"
#include <QStringList>
#include <QTimer>
#include <qfuturewatcher.h>
#include <qmimedatabase.h>

class SearchFilesViewHost : public ListViewHost {
  Q_OBJECT
  Q_PROPERTY(bool hasDetail READ hasDetail NOTIFY detailChanged)
  Q_PROPERTY(QString detailName READ detailName NOTIFY detailChanged)
  Q_PROPERTY(QString detailPath READ detailPath NOTIFY detailChanged)
  Q_PROPERTY(QString detailMimeType READ detailMimeType NOTIFY detailChanged)
  Q_PROPERTY(QString detailLastModified READ detailLastModified NOTIFY detailChanged)
  Q_PROPERTY(QString detailImageSource READ detailImageSource NOTIFY detailChanged)
  Q_PROPERTY(QString detailTextContent READ detailTextContent NOTIFY detailChanged)
  Q_PROPERTY(CompletionModel *categoryFilterModel READ categoryFilterModel CONSTANT)
  Q_PROPERTY(int currentCategoryFilter READ currentCategoryFilter NOTIFY currentCategoryFilterChanged)

signals:
  void detailChanged();
  void currentCategoryFilterChanged();

public:
  QUrl qmlComponentUrl() const override;
  QUrl qmlSearchAccessoryUrl() const override;
  QVariantMap qmlProperties() override;
  void initialize() override;
  void loadInitialData() override;
  void textChanged(const QString &text) override;

  bool hasDetail() const { return m_hasDetail; }
  QString detailName() const { return m_detailName; }
  QString detailPath() const { return m_detailPath; }
  QString detailMimeType() const { return m_detailMimeType; }
  QString detailLastModified() const { return m_detailLastModified; }
  QString detailImageSource() const { return m_detailImageSource; }
  QString detailTextContent() const { return m_detailTextContent; }
  CompletionModel *categoryFilterModel() { return &m_categoryFilterModel; }
  int currentCategoryFilter() const { return m_currentCategoryFilter; }

  Q_INVOKABLE void setCategoryFilter(int index);

private:
  QStringList categoryFilterOptions() const;
  void renderRecentFiles();
  void handleDebounce();
  void handleSearchResults();
  void loadDetail(const std::filesystem::path &path);
  void clearDetail();
  void restoreCategoryFilter();
  std::optional<vicinae::FileCategory> selectedCategory() const;

  enum class ResultMode { Recent, DirectPath, IndexedSearch };

  using Watcher = QFutureWatcher<std::vector<IndexerFileResult>>;

  SearchFilesSection m_section;
  QTimer m_debounce;
  Watcher m_pendingResults;
  QString m_lastSearchText;
  QMimeDatabase m_mimeDb;
  ResultMode m_resultMode = ResultMode::Recent;

  bool m_hasDetail = false;
  QString m_detailName;
  QString m_detailPath;
  QString m_detailMimeType;
  QString m_detailLastModified;
  QString m_detailImageSource;
  QString m_detailTextContent;
  CompletionModel m_categoryFilterModel{this};
  int m_currentCategoryFilter = 0;
};
