<template>
  <div class="bitable-file-list-view">
    <!-- Top bar -->
    <div class="bitable-file-list-view__topbar">
      <div class="bitable-file-list-view__topbar-left">
        <a-button type="text" :icon="h(ArrowLeftOutlined)" @click="goBack" />
        <span class="bitable-file-list-view__title">多维表格</span>
      </div>
      <div class="bitable-file-list-view__topbar-right">
        <a-button type="primary" :icon="h(PlusOutlined)" @click="createOpen = true">
          新建文件
        </a-button>
      </div>
    </div>

    <!-- Body: file grid -->
    <div class="bitable-file-list-view__body">
      <a-spin :spinning="store.isLoading">
        <div v-if="store.files.length > 0" class="bitable-file-list-view__grid">
          <FileCard
            v-for="file in store.files"
            :key="file.id"
            :file="file"
            @open="handleOpen"
            @rename="handleRename"
            @delete="handleDelete"
          />
        </div>

        <a-empty
          v-else-if="!store.isLoading"
          description="还没有多维表格文件，点击右上角新建"
          class="bitable-file-list-view__empty"
        />
      </a-spin>
    </div>

    <!-- Create file modal -->
    <FileCreateModal
      :open="createOpen"
      @success="handleCreated"
      @cancel="createOpen = false"
    />

    <!-- Rename modal -->
    <a-modal
      :open="renameOpen"
      title="重命名文件"
      :confirm-loading="renaming"
      @ok="handleRenameOk"
      @cancel="renameOpen = false"
    >
      <a-form layout="vertical">
        <a-form-item label="图标">
          <a-select v-model:value="renameForm.icon" :options="iconOptions" />
        </a-form-item>
        <a-form-item label="文件名">
          <a-input v-model:value="renameForm.name" :maxlength="100" />
        </a-form-item>
        <a-form-item label="描述">
          <a-textarea v-model:value="renameForm.description" :rows="2" :maxlength="500" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, h, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Modal as AModal } from 'ant-design-vue'
import { ArrowLeftOutlined, PlusOutlined } from '@ant-design/icons-vue'
import { useBitableStore } from '@/stores/bitable'
import type { IBitableFile } from '@/api/bitable'
import FileCard from '@/components/bitable/FileCard.vue'
import FileCreateModal from '@/components/bitable/FileCreateModal.vue'

const router = useRouter()
const store = useBitableStore()

const createOpen = ref(false)
const renameOpen = ref(false)
const renaming = ref(false)

const renameForm = reactive({
  id: '',
  icon: '📋',
  name: '',
  description: '',
})

const iconOptions = [
  { label: '📋 表格', value: '📋' },
  { label: '📊 仪表盘', value: '📊' },
  { label: '📝 笔记', value: '📝' },
  { label: '🗂️ 项目', value: '🗂️' },
  { label: '📅 日程', value: '📅' },
  { label: '💼 工作', value: '💼' },
  { label: '🎯 目标', value: '🎯' },
  { label: '📚 知识库', value: '📚' },
]

onMounted(() => {
  store.loadFiles()
})

function goBack(): void {
  router.push('/agent/chat')
}

function handleOpen(fileId: string): void {
  router.push(`/bitable/${fileId}`)
}

function handleCreated(fileId: string): void {
  createOpen.value = false
  router.push(`/bitable/${fileId}`)
}

function handleRename(file: IBitableFile): void {
  renameForm.id = file.id
  renameForm.icon = file.icon
  renameForm.name = file.name
  renameForm.description = file.description
  renameOpen.value = true
}

async function handleRenameOk(): Promise<void> {
  if (!renameForm.name.trim()) return
  renaming.value = true
  try {
    await store.updateFile(renameForm.id, {
      name: renameForm.name.trim(),
      icon: renameForm.icon,
      description: renameForm.description.trim(),
    })
    renameOpen.value = false
  } finally {
    renaming.value = false
  }
}

function handleDelete(file: IBitableFile): void {
  AModal.confirm({
    title: '删除文件',
    content: `确定删除「${file.name}」吗？该文件下的所有数据表都将被删除，此操作不可恢复。`,
    okText: '删除',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      await store.deleteFile(file.id)
    },
  })
}
</script>

<style scoped>
.bitable-file-list-view {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  background: var(--bg-secondary, #fafafa);
}

.bitable-file-list-view__topbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 16px;
  background: var(--bg-primary, #fff);
  border-bottom: 1px solid var(--border-color, #f0f0f0);
  flex-shrink: 0;
}

.bitable-file-list-view__topbar-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.bitable-file-list-view__topbar-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.bitable-file-list-view__title {
  font-weight: 600;
  font-size: 16px;
}

.bitable-file-list-view__body {
  flex: 1;
  overflow: auto;
  padding: 24px;
}

.bitable-file-list-view__grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  max-width: 1400px;
  margin: 0 auto;
}

.bitable-file-list-view__empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 0;
}
</style>
