<script lang="ts" setup>
import { ref } from 'vue';

import {
  Button,
  Drawer,
  Empty,
  Space,
  Tag,
  Tooltip,
} from 'ant-design-vue';

import MIcon from '#/components/icon/icon.vue';

import { listLocalHistory } from '../history/localHistoryStore';
import { listRemoteHistory } from '../history/remoteHistoryApi';
import type { SpreadsheetHistoryEntry, SpreadsheetTableConfig } from '../types';

import SpreadsheetFormulaLibraryModal from './SpreadsheetFormulaLibraryModal.vue';

const props = defineProps<{
  tableConfig: SpreadsheetTableConfig;
  canUndo: boolean;
  canRedo: boolean;
  isDark?: boolean;
  refreshing?: boolean;
  showConfigButton?: boolean;
  showFormulaLibrary?: boolean;
  workbookName?: string;
}>();

const emit = defineEmits<{
  undo: [];
  redo: [];
  refresh: [];
  openConfig: [];
  rollback: [entry: SpreadsheetHistoryEntry];
  formulaLibraryUpdated: [];
}>();

const historyOpen = ref(false);
const historyItems = ref<SpreadsheetHistoryEntry[]>([]);
const loadingHistory = ref(false);
const formulaLibraryRef = ref<InstanceType<
  typeof SpreadsheetFormulaLibraryModal
> | null>(null);
let historyLoadToken = 0;

function invalidateHistoryLoad() {
  historyLoadToken += 1;
  loadingHistory.value = false;
}

async function openHistory() {
  historyOpen.value = true;
  const token = ++historyLoadToken;
  loadingHistory.value = true;
  try {
    const local = await listLocalHistory(
      props.tableConfig.tableName,
      props.tableConfig.sheetKey,
    );
    if (token !== historyLoadToken) return;
    try {
      const remote = await listRemoteHistory({
        table_name: props.tableConfig.tableName,
        sheet_key: props.tableConfig.sheetKey,
        pageSize: 50,
      });
      if (token !== historyLoadToken) return;
      const merged = [...local];
      for (const r of remote.items ?? []) {
        if (!merged.some((m) => m.id === r.client_entry_id)) {
          merged.push({
            id: r.client_entry_id ?? String(r.id),
            tableName: r.table_name,
            sheetKey: r.sheet_key,
            userId: r.admin_user_id,
            userName: r.admin_user_name,
            action: r.action as SpreadsheetHistoryEntry['action'],
            rowKey: r.row_key,
            fieldId: r.field_id,
            beforeSnapshot: r.before_snapshot,
            afterSnapshot: r.after_snapshot,
            createdAt: r.created_at,
            synced: true,
          });
        }
      }
      merged.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
      historyItems.value = merged.slice(0, 100);
    } catch {
      if (token !== historyLoadToken) return;
      historyItems.value = local;
    }
  } finally {
    if (token === historyLoadToken) {
      loadingHistory.value = false;
    }
  }
}

async function handleRollback(entry: SpreadsheetHistoryEntry) {
  emit('rollback', entry);
  historyOpen.value = false;
}

function openFormulaLibrary() {
  formulaLibraryRef.value?.open();
}
</script>

<template>
  <div class="spreadsheet-toolbar" :class="{ 'is-dark': isDark }">
    <div class="toolbar-row toolbar-main">
      <Tag v-if="workbookName" class="workbook-tag" color="processing">
        {{ workbookName }}
      </Tag>
      <span v-else class="workbook-tag plain">{{ tableConfig.tableName }}</span>

      <span class="toolbar-divider" />

      <Space :size="4">
        <Tooltip title="撤回 (Ctrl+Z)">
          <Button size="small" :disabled="!canUndo" @click="emit('undo')">
            <MIcon icon="ant-design:undo-outlined" />
          </Button>
        </Tooltip>
        <Tooltip title="重做 (Ctrl+Y)">
          <Button size="small" :disabled="!canRedo" @click="emit('redo')">
            <MIcon icon="ant-design:redo-outlined" />
          </Button>
        </Tooltip>
        <Tooltip title="刷新">
          <Button
            size="small"
            :disabled="refreshing"
            :loading="refreshing"
            @click="emit('refresh')"
          >
            <MIcon icon="ant-design:reload-outlined" />
          </Button>
        </Tooltip>
        <Button
          v-if="tableConfig.enableHistory !== false"
          size="small"
          @click="openHistory"
        >
          <MIcon icon="ant-design:history-outlined" />
          历史
        </Button>
      </Space>

      <span class="toolbar-divider" />

      <Space :size="4">
        <Button
          v-if="showConfigButton"
          size="small"
          @click="emit('openConfig')"
        >
          <MIcon icon="mdi:table-cog" />
          Excel 配置
        </Button>
        <Button
          v-if="showFormulaLibrary"
          size="small"
          @click="openFormulaLibrary"
        >
          <MIcon icon="mdi:function-variant" />
          公式库
        </Button>
      </Space>
    </div>

    <slot name="formula-bar" />

    <SpreadsheetFormulaLibraryModal
      ref="formulaLibraryRef"
      @updated="emit('formulaLibraryUpdated')"
    />

    <Drawer
      v-model:open="historyOpen"
      :title="`${workbookName || tableConfig.tableName} - 编辑历史`"
      width="480"
      @after-open-change="(open: boolean) => { if (!open) invalidateHistoryLoad(); }"
    >
      <div v-if="loadingHistory" class="history-loading">加载中...</div>
      <Empty v-else-if="!historyItems.length" description="暂无历史记录" />
      <div v-else class="history-list">
        <div v-for="item in historyItems" :key="item.id" class="history-item">
          <div class="history-meta">
            <strong>{{ item.userName }}</strong>
            <span>{{ item.createdAt }}</span>
            <Tag size="small">{{ item.action }}</Tag>
          </div>
          <div class="history-diff">
            行 {{ item.rowKey }} · {{ item.fieldId }}
            <br />
            {{ item.beforeSnapshot }} → {{ item.afterSnapshot }}
          </div>
          <Button size="small" type="link" @click="handleRollback(item)">
            回滚到此版本
          </Button>
        </div>
      </div>
    </Drawer>
  </div>
</template>

<style scoped lang="scss">
.spreadsheet-toolbar {
  display: flex;
  flex-direction: column;
  background: #fff;
}

.toolbar-row {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
  padding: 8px 10px;
}

.toolbar-main {
  border-bottom: 1px solid #e5e6eb;
}

.workbook-tag {
  font-weight: 600;
  margin: 0;

  &.plain {
    font-size: 13px;
    color: #1d2129;
  }
}

.toolbar-divider {
  width: 1px;
  height: 20px;
  background: #e5e6eb;
  margin: 0 4px;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.history-item {
  padding: 12px;
  border: 1px solid #e5e6eb;
  border-radius: 8px;
}

.history-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 6px;
  font-size: 12px;
  color: #86909c;
}

.history-diff {
  font-size: 13px;
  margin-bottom: 4px;
}

.history-loading {
  text-align: center;
  padding: 24px;
  color: #86909c;
}

.spreadsheet-toolbar.is-dark {
  background: #141414;

  .toolbar-main {
    border-bottom-color: #424242;
  }

  .workbook-tag.plain {
    color: rgba(255, 255, 255, 0.85);
  }

  .toolbar-divider {
    background: #424242;
  }

  .history-item {
    border-color: #424242;
  }

  .history-meta,
  .history-loading {
    color: rgba(255, 255, 255, 0.45);
  }
}
</style>
