import i18next from "i18next";
import { Modal, Notice } from "obsidian";

export interface SyncHistoryItem {
  id: string;
  action: "publish" | "update" | "pull" | "delete";
  title: string;
  timestamp: number;
  success: boolean;
}

export function openSyncHistoryModal(history: SyncHistoryItem[]): void {
  const modal = new SyncHistoryModal(history);
  modal.open();
}

class SyncHistoryModal extends Modal {
  constructor(private readonly history: SyncHistoryItem[]) {
    super(app);
  }

  async onOpen() {
    const { contentEl } = this;
    contentEl.empty();

    contentEl.createEl("h2", {
      text: i18next.t("sync_history.title"),
    });

    const stats = contentEl.createDiv("history-stats");
    const successCount = this.history.filter(h => h.success).length;
    stats.createEl("span", {
      text: i18next.t("sync_history.stats", { total: this.history.length, success: successCount })
    });

    if (this.history.length === 0) {
      contentEl.createEl("p", {
        text: i18next.t("sync_history.empty"),
        cls: "history-empty"
      });
    } else {
      const list = contentEl.createDiv("history-list");
      
      for (const item of [...this.history].reverse()) {
        const itemEl = list.createDiv("history-item");
        
        const headerEl = itemEl.createDiv("history-header");
        
        const icon = item.success ? "✅" : "❌";
        const actionText = this.getActionText(item.action);
        
        headerEl.createEl("span", {
          text: `${icon} ${actionText}`,
          cls: "history-action"
        });
        
        headerEl.createEl("span", {
          text: new Date(item.timestamp).toLocaleString(),
          cls: "history-time"
        });

        const contentEl2 = itemEl.createDiv("history-content");
        contentEl2.createEl("span", {
          text: item.title,
          cls: "history-title"
        });
      }
    }

    const actions = contentEl.createDiv("history-actions");
    actions.createEl("button", {
      text: i18next.t("common.button_close"),
      cls: "mod-warning"
    }).addEventListener("click", () => this.close());
  }

  private getActionText(action: string): string {
    const actionMap: Record<string, string> = {
      publish: i18next.t("sync_history.action_publish"),
      update: i18next.t("sync_history.action_update"),
      pull: i18next.t("sync_history.action_pull"),
      delete: i18next.t("sync_history.action_delete"),
    };
    return actionMap[action] || action;
  }

  onClose() {
    const { contentEl } = this;
    contentEl.empty();
  }
}