<script setup lang="ts">
import { Input, Empty, Spin, Tooltip } from 'ant-design-vue';

defineProps<{
  tableList: any[];
  loading: boolean;
  selectedTable: string;
  searchKeyword: string;
}>();

const emit = defineEmits<{
  'update:searchKeyword': [value: string];
  'select-table': [tableName: string];
}>();

// 根据表名生成一个固定的装饰色，让界面不那么单调
const getIconColor = (name: string) => {
  const colors = ['text-blue-500', 'text-green-500', 'text-purple-500', 'text-orange-500', 'text-pink-500', 'text-cyan-500'];
  let hash = 0;
  for (let i = 0; i < name.length; i++) {
    hash = name.charCodeAt(i) + ((hash << 5) - hash);
  }
  return colors[Math.abs(hash) % colors.length];
};

// 格式化文件大小
const formatSize = (bytes: number) => {
  if (!bytes && bytes !== 0) return '-';
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
};

// 格式化日期，只显示年月日
const formatDate = (dateStr: string) => {
  if (!dateStr) return '';
  return dateStr.split(' ')[0];
};
</script>

<template>
  <div class="h-full flex flex-col bg-white dark:bg-gray-900 rounded-lg shadow-sm">
    <!-- 头部区域：标题与搜索 -->
    <div class="p-5 border-b border-gray-100 dark:border-gray-800 flex flex-col sm:flex-row justify-between items-center gap-4">
      <div class="flex items-center gap-3 self-start sm:self-center">
        <div class="w-10 h-10 bg-primary/10 rounded-xl flex items-center justify-center">
          <!-- 替换原有 fa-database 图标 -->
          <span class="icon-[material-symbols--database] text-primary text-xl"></span>
        </div>
        <div>
          <h2 class="text-lg font-bold m-0 leading-tight text-gray-800 dark:text-gray-100">数据库表管理</h2>
          <p class="text-xs text-gray-500 dark:text-gray-400 m-0 mt-1">共 {{ tableList.length }} 张数据表</p>
        </div>
      </div>

      <div class="w-full sm:w-80">
        <Input
          :value="searchKeyword"
          placeholder="搜索表名、注释..."
          allow-clear
          size="large"
          class="!rounded-lg"
          @update:value="(val) => emit('update:searchKeyword', val)"
        >
          <template #prefix>
            <i class="fa-solid fa-search text-gray-400 mr-1"></i>
          </template>
        </Input>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="flex-1 overflow-hidden relative bg-gray-50/50 dark:bg-gray-900">
      <!-- 加载中 -->
      <div v-if="loading" class="absolute inset-0 z-10 flex justify-center items-center bg-white/60 dark:bg-gray-900/60 backdrop-blur-sm">
        <div class="text-center">
          <Spin size="large" />
          <p class="mt-4 text-gray-500">正在加载数据表...</p>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else-if="tableList.length === 0" class="h-full flex flex-col justify-center items-center text-gray-400">
        <Empty :image="Empty.PRESENTED_IMAGE_SIMPLE" description="未找到匹配的数据表" />
      </div>

      <!-- 卡片网格列表 -->
      <div v-else class="h-full overflow-y-auto p-4 sm:p-6">
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5 gap-5">
          <div
            v-for="table in tableList"
            :key="table.name"
            class="group relative flex flex-col bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl p-4 cursor-pointer transition-all duration-300 hover:shadow-lg hover:-translate-y-1 hover:border-primary/30"
            @click="emit('select-table', table.name)"
          >
            <!-- 卡片顶部：图标与名称 -->
            <div class="flex items-start justify-between mb-3">
              <div class="flex items-center gap-3 overflow-hidden flex-1">
                <div class="w-10 h-10 rounded-lg bg-gray-50 dark:bg-gray-700 flex items-center justify-center flex-shrink-0 group-hover:bg-primary/5 transition-colors">
                  <span class="icon-[material-symbols--database] text-primary text-xl"></span>
                </div>
                <div class="overflow-hidden flex-1">
                  <h3 class="font-bold text-gray-800 dark:text-gray-100 truncate text-base mb-0.5" :title="table.name">
                    {{ table.name }}
                  </h3>
                  <!-- 标签行：显示引擎和字符集 -->
                  <div class="flex items-center gap-2 overflow-hidden">
                    <Tooltip :title="`存储引擎: ${table.engine}`">
                      <span class="text-[10px] px-1.5 py-0.5 rounded bg-gray-100 dark:bg-gray-700 text-gray-500 font-mono whitespace-nowrap">
                        {{ table.engine || 'InnoDB' }}
                      </span>
                    </Tooltip>
                    <Tooltip v-if="table.collation" :title="`字符集: ${table.collation}`">
                      <span class="text-[10px] px-1.5 py-0.5 rounded bg-gray-100 dark:bg-gray-700 text-gray-500 font-mono truncate max-w-[80px]">
                        {{ table.collation.split('_')[0] }}
                      </span>
                    </Tooltip>
                  </div>
                </div>
              </div>
            </div>

            <!-- 卡片中间：注释 -->
            <div class="flex-1 mb-4 min-h-[2.5rem]">
              <p class="text-sm text-gray-500 dark:text-gray-400 line-clamp-2 m-0 leading-relaxed" :title="table.comment">
                {{ table.comment || '暂无表注释信息...' }}
              </p>
            </div>

            <!-- 卡片底部：统计与操作 -->
            <div class="pt-3 border-t border-gray-100 dark:border-gray-700 flex items-center justify-between text-xs text-gray-400">
              <div class="flex items-center gap-3">
                <!-- 行数 -->
                <Tooltip title="数据行数">
                  <div class="flex items-center gap-1.5 hover:text-gray-600 dark:hover:text-gray-300">
                    <i class="fa-solid fa-list-ol"></i>
                    <span>{{ (table.rows || 0).toLocaleString() }}</span>
                  </div>
                </Tooltip>

                <!-- 大小 (数据+索引) -->
                <Tooltip title="数据+索引大小">
                  <div class="flex items-center gap-1.5 hover:text-gray-600 dark:hover:text-gray-300">
                    <i class="fa-solid fa-hard-drive"></i>
                    <span>{{ formatSize((table.data_length || 0) + (table.index_length || 0)) }}</span>
                  </div>
                </Tooltip>
              </div>

              <!-- 右下角：默认显示时间，Hover显示管理按钮 -->
              <div class="relative">
                <Tooltip :title="`创建时间: ${table.create_time || '-'}`">
                  <div class="group-hover:opacity-0 transition-opacity duration-300 flex items-center gap-1">
                    <i class="fa-regular fa-clock"></i>
                    <span>{{ formatDate(table.create_time) }}</span>
                  </div>
                </Tooltip>

                <div class="absolute right-0 top-0 flex items-center gap-1 text-primary opacity-0 group-hover:opacity-100 transform translate-x-2 group-hover:translate-x-0 transition-all duration-300 font-medium whitespace-nowrap bg-white dark:bg-gray-800 pl-2">
                  <span>管理</span>
                  <i class="fa-solid fa-arrow-right"></i>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 优化滚动条样式 */
.overflow-y-auto {
  scrollbar-width: thin;
  scrollbar-color: rgba(0, 0, 0, 0.1) transparent;
}
.overflow-y-auto::-webkit-scrollbar {
  width: 6px;
}
.overflow-y-auto::-webkit-scrollbar-track {
  background: transparent;
}
.overflow-y-auto::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 3px;
}
</style>
