<template>
  <div class="tools-page">
    <div class="page-header">
      <h2>{{ t('Tools') }}</h2>
      <div class="header-actions">
        <button class="marketplace-btn" @click="handleOpenMarketplace">
          <i class="fa fa-store"></i>
          {{ t('Tool Marketplace') }}
        </button>
        <button class="add-tool-btn" @click="handleAddTool">
          <i class="fa fa-plus"></i>
          {{ t('Add Tool') }}
        </button>
      </div>
    </div>

    <div class="page-content">
      <!-- 空状态 -->
      <div v-if="!loading && displayTools.length === 0" class="empty-state">
        <div class="empty-icon">
          <i class="fa fa-toolbox"></i>
        </div>
        <h3>{{ t('No Tools Yet') }}</h3>
        <p>{{ t('Get started by adding your first tool service') }}</p>
        <button class="empty-action-btn" @click="handleAddTool">
          <i class="fa fa-plus"></i>
          {{ t('Add Your First Tool') }}
        </button>
      </div>

      <!-- 工具网格 -->
      <div v-else class="tools-grid">
        <div
          v-for="(tool, index) in displayTools"
          :key="tool.id"
          class="tool-card"
          :class="{ 'dragging': draggedTool?.id === tool.id, 'drag-over': dropIndex === index }"
          :draggable="true"
          @dragstart="handleDragStart($event, tool, index)"
          @dragover.prevent="handleDragOver($event, index)"
          @dragleave="handleDragLeave"
          @drop="handleDrop($event, index)"
          @dragend="handleDragEnd"
        >
          <div class="tool-card-content" @click="handleOpenTool(tool)">
            <div 
              class="tool-icon" 
              :class="{ 'default-tool-icon': tool.isDefault || !tool.color || tool.color === '' }"
              :style="(tool.isDefault || !tool.color || tool.color === '')
                ? { borderColor: tool.color || '#e5e7eb' } 
                : { backgroundColor: tool.color }"
            >
              <DynamicIcon :name="tool.icon || 'tool'" :size="32" :color="(tool.isDefault || !tool.color || tool.color === '') ? '#64748b' : 'white'" />
            </div>
            <div class="tool-name" :class="{ 'default-tool-name': tool.isDefault || !tool.color || tool.color === '' }">{{ tool.name }}</div>
          </div>
          <n-dropdown
            trigger="click"
            :options="getToolMenuOptions(tool)"
            @select="handleMenuSelect($event, tool)"
          >
            <div class="tool-menu-trigger" @click.stop>
              <i class="fa fa-ellipsis-h"></i>
            </div>
          </n-dropdown>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <i class="fa fa-spinner fa-spin"></i>
        <span>{{ t('Loading tools...') }}</span>
      </div>
    </div>

    <!-- 添加/编辑工具对话框 -->
    <n-modal v-model:show="showToolModal" preset="dialog" :title="editingTool ? t('Edit Tool') : t('Add Tool')">
      <n-form :model="toolForm" :rules="toolFormRules" label-width="100" ref="toolFormRef">
        <n-form-item :label="t('Title')" path="name">
          <n-input v-model:value="toolForm.name" :placeholder="t('Enter tool title')" />
        </n-form-item>
        <n-form-item :label="t('Description')" path="description">
          <n-input
            v-model:value="toolForm.description"
            type="textarea"
            :placeholder="t('Enter tool description')"
            :rows="3"
          />
        </n-form-item>
        <n-form-item :label="t('Category')" path="category">
          <n-input v-model:value="toolForm.category" :placeholder="t('Enter category')" />
        </n-form-item>
        <n-form-item :label="t('Icon')" path="icon">
          <IconPicker v-model="toolForm.icon" />
        </n-form-item>
        <n-form-item :label="t('Color')" path="color">
          <n-color-picker v-model:value="toolForm.color" />
        </n-form-item>
        <!-- 路由名 -->
        <n-form-item :label="t('Route Name')" path="routeName">
          <n-auto-complete
            v-model:value="toolForm.routeName"
            :options="routeNameOptions"
            :placeholder="t('Enter or select route name, e.g.: Dashboard, Tools')"
            filterable
            clearable
          />
          <template #feedback>
            <n-text depth="3" style="font-size: 12px;">
              {{ t('Use route name for internal navigation (recommended)') }}
            </n-text>
          </template>
        </n-form-item>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="showToolModal = false">{{ t('Cancel') }}</n-button>
          <n-button type="primary" @click="handleSaveTool">{{ t('Save') }}</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, h } from 'vue'
import { useRouter } from 'vue-router'
import { NModal, NForm, NFormItem, NInput, NAutoComplete, NColorPicker, NButton, NSpace, NText, NDropdown, useDialog, useMessage, type FormInst, type FormRules, type DropdownOption } from 'naive-ui'
import { t } from '@/shared/i18n'
import DynamicIcon from '@/core/components/DynamicIcon.vue'
import IconPicker from '@/core/components/IconPicker.vue'
import { useToolsStore, type Tool } from '@/shared/stores/tools'
import { ensureToolRoutes } from '@/shared/utils/dynamicRoutes'

// 生成 UUID（兼容所有环境）
function generateUUID(): string {
  // 优先使用 crypto.randomUUID（如果可用）
  if (typeof crypto !== 'undefined' && crypto.randomUUID) {
    return crypto.randomUUID()
  }
  
  // 降级方案：使用时间戳 + 随机数
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0
    const v = c === 'x' ? r : (r & 0x3 | 0x8)
    return v.toString(16)
  })
}

const router = useRouter()
const toolsStore = useToolsStore()
const loading = ref(false)
const showToolModal = ref(false)
const editingTool = ref<Tool | null>(null)
const toolFormRef = ref<FormInst | null>(null)
const dialog = useDialog()
const message = useMessage()

// 拖拽相关
const draggedTool = ref<Tool | null>(null)
const draggedIndex = ref<number>(-1)
const dropIndex = ref<number>(-1)

const toolForm = ref<Partial<Tool>>({
  name: '',
  description: '',
  category: '',
  icon: 'tool',
  color: '#1fc76f',
  routeName: ''
})

const toolFormRules: FormRules = {
  name: [{ required: true, message: t('Please enter tool title') }],
  routeName: [
    { 
      required: true, 
      message: t('Please enter route name'),
      trigger: ['input', 'blur']
    }
  ]
}

// 获取所有可用的路由名（从路由配置中提取）
const routeNameOptions = computed(() => {
  const routes = router.getRoutes()
  return routes
    .filter(route => route.name && route.meta?.requiresAuth !== false)
    .map(route => ({
      label: String(route.name),
      value: String(route.name)
    }))
    .sort((a, b) => a.label.localeCompare(b.label))
})

// 使用 store 中的工具列表
const displayTools = computed(() => toolsStore.allTools)

onMounted(() => {
  loading.value = false
  
  // 监听全局事件，当工具安装后刷新列表
  window.addEventListener('installedToolsUpdated', () => {
    // store 会自动更新，computed 属性会自动响应
  })
})

// 拖拽处理
function handleDragStart(event: DragEvent, tool: Tool, index: number) {
  draggedTool.value = tool
  draggedIndex.value = index
  event.dataTransfer!.effectAllowed = 'move'
  event.dataTransfer!.dropEffect = 'move'
}

function handleDragOver(event: DragEvent, index: number) {
  event.preventDefault()
  if (draggedTool.value && dropIndex.value !== index) {
    dropIndex.value = index
  }
}

function handleDragLeave() {
  // 延迟清除，避免快速移动时闪烁
  setTimeout(() => {
    if (!draggedTool.value) {
      dropIndex.value = -1
    }
  }, 50)
}

function handleDrop(event: DragEvent, dropIndexValue: number) {
  event.preventDefault()
  if (!draggedTool.value || draggedIndex.value === -1) return

  const dragged = draggedTool.value
  
  // 默认工具不能拖拽排序
  if (dragged.isDefault) {
    resetDragState()
    return
  }

  // 只对用户工具进行排序
  const newUserTools = [...toolsStore.userTools]
  const draggedIndexInUser = newUserTools.findIndex(t => t.id === dragged.id)
  
  if (draggedIndexInUser < 0) {
    resetDragState()
    return
  }

  // 计算在用户工具中的新位置
  const defaultToolsCount = toolsStore.getDefaultTools().length
  const newIndexInUser = Math.max(0, dropIndexValue - defaultToolsCount)
  
  const draggedToolItem = newUserTools.splice(draggedIndexInUser, 1)[0]
  newUserTools.splice(newIndexInUser, 0, draggedToolItem)

  // 更新顺序
  toolsStore.updateUserToolsOrder(newUserTools)
  
  resetDragState()
}

function handleDragEnd() {
  resetDragState()
}

function resetDragState() {
  draggedTool.value = null
  draggedIndex.value = -1
  dropIndex.value = -1
}

// 工具操作
function handleAddTool() {
  editingTool.value = null
  toolForm.value = {
    name: '',
    description: '',
    category: '',
    icon: 'tool',
    color: '#1fc76f',
    routeName: ''
  }
  showToolModal.value = true
}

function handleEditTool(tool: Tool) {
  editingTool.value = tool
  toolForm.value = { ...tool }
  showToolModal.value = true
}

function handleSaveTool() {
  // 先手动验证必填字段
  if (!toolForm.value.name || !toolForm.value.name.trim()) {
    message.error(t('Please enter tool title'))
    return
  }
  
  if (!toolForm.value.routeName || !toolForm.value.routeName.trim()) {
    message.error(t('Please enter route name'))
    return
  }

  // 表单验证
  toolFormRef.value?.validate((errors) => {
    if (errors) {
      // 验证失败，错误信息已由表单组件显示
      return
    }

    if (editingTool.value) {
      // 更新（只能更新用户工具，默认工具不能编辑）
      if (editingTool.value.isDefault) {
        message.warning(t('Default tools cannot be edited'))
        return
      }
      
      const updates: Partial<Tool> = {
        ...toolForm.value,
        type: 'route', // 默认类型为 route
        routeName: toolForm.value.routeName
      }
      
      toolsStore.updateUserTool(editingTool.value.id, updates)
      message.success(t('Tool updated successfully'))
    } else {
      // 新增用户工具
      const newTool: Tool = {
        id: generateUUID(),
        name: toolForm.value.name!,
        description: toolForm.value.description,
        category: toolForm.value.category,
        icon: toolForm.value.icon || 'tool',
        color: toolForm.value.color || '#1fc76f',
        type: 'route', // 默认类型为 route
        routeName: toolForm.value.routeName,
        isDefault: false
      }
      
      // 添加工具并注册路由
      toolsStore.addUserTool(newTool, router)
      message.success(t('Tool added successfully'))
    }

    showToolModal.value = false
  })
}

function handleDeleteTool(tool: Tool) {
  // 删除工具（支持用户工具和默认工具）
  dialog.warning({
    title: t('Confirm Delete'),
    content: `${t('Are you sure you want to delete tool')} "${tool.name}"?`,
    positiveText: t('Delete'),
    negativeText: t('Cancel'),
    onPositiveClick: async () => {
      try {
        // 删除工具并移除路由（如果是市场工具或默认工具，会同时删除文件）
        await toolsStore.deleteUserTool(tool.id, router)
        message.success(t('Tool deleted successfully'))
      } catch (error) {
        console.error('Delete tool error:', error)
        message.error(t('Failed to delete tool'))
      }
    }
  })
}

function handleOpenMarketplace() {
  router.push({ name: 'ToolMarketplace' })
}

function handleOpenTool(tool: Tool) {
  // 确保工具具有 routeName（如果缺失则自动生成）
  const toolWithRoutes = ensureToolRoutes({ ...tool })
  if (toolWithRoutes.routeName) {
    // 使用路由名导航
    try {
      router.push({ name: toolWithRoutes.routeName })
    } catch (error) {
      message.error(t('Route not found: ') + toolWithRoutes.routeName)
    }
  }
}

// 获取工具菜单选项
function getToolMenuOptions(tool: Tool): DropdownOption[] {
  const options: DropdownOption[] = []
  
  if (tool.isDefault) {
    // 默认工具：只显示"删除"选项
    options.push({
      label: t('Delete'),
      key: 'delete',
      icon: () => h('i', { class: 'fa fa-trash' })
    })
  } else {
    // 用户工具：显示"编辑"和"删除"选项
    options.push(
      {
        label: t('Edit'),
        key: 'edit',
        icon: () => h('i', { class: 'fa fa-edit' })
      },
      {
        label: t('Delete'),
        key: 'delete',
        icon: () => h('i', { class: 'fa fa-trash' })
      }
    )
  }
  
  return options
}

// 处理菜单选择
function handleMenuSelect(key: string, tool: Tool) {
  if (key === 'edit') {
    handleEditTool(tool)
  } else if (key === 'delete') {
    handleDeleteTool(tool)
  }
}
</script>

<style scoped>
.tools-page {
  width: 100%;
  padding: 16px;
  min-height: 100vh;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 0;
}

.page-header h2 {
  font-size: 24px;
  font-weight: 700;
  color: #1f2937;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.marketplace-btn {
  height: 36px;
  padding: 0 16px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  background: white;
  color: #64748b;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.marketplace-btn:hover {
  background: #f9fafb;
  border-color: #cbd5e1;
  color: #475569;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.add-tool-btn {
  height: 36px;
  padding: 0 16px;
  border: 1px solid #1fc76f;
  border-radius: 8px;
  background: #e6f8f0;
  color: #0d684b;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.add-tool-btn:hover {
  background: #dcfce7;
  border-color: #1fc76f;
  color: #166534;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(31, 199, 111, 0.15);
}

.add-tool-btn:active {
  background: #1fc76f;
  border-color: #1fc76f;
  color: white;
  transform: translateY(0);
  box-shadow: 0 1px 4px rgba(31, 199, 111, 0.2);
}

.add-tool-btn:disabled {
  background: #f1f5f9;
  border-color: #e2e8f0;
  color: #94a3b8;
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.add-tool-btn:disabled:hover {
  background: #f1f5f9;
  border-color: #e2e8f0;
  color: #94a3b8;
  transform: none;
  box-shadow: none;
}

.add-tool-btn i {
  font-size: 12px;
}

/* 页面内容 */
.page-content {
  position: relative;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 80px 24px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.empty-icon {
  width: 120px;
  height: 120px;
  margin: 0 auto 24px;
  background: #e6f8f0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-icon i {
  font-size: 48px;
  color: #1fc76f;
}

.empty-state h3 {
  font-size: 24px;
  font-weight: 600;
  color: #0f172a;
  margin: 0 0 12px 0;
}

.empty-state p {
  font-size: 16px;
  color: #64748b;
  margin: 0 0 32px 0;
}

.empty-action-btn {
  height: 36px;
  padding: 0 16px;
  border: 1px solid #1fc76f;
  border-radius: 8px;
  background: #e6f8f0;
  color: #0d684b;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.empty-action-btn:hover {
  background: #dcfce7;
  border-color: #1fc76f;
  color: #166534;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(31, 199, 111, 0.15);
}

.empty-action-btn:active {
  background: #1fc76f;
  border-color: #1fc76f;
  color: white;
  transform: translateY(0);
  box-shadow: 0 1px 4px rgba(31, 199, 111, 0.2);
}

/* 工具网格 */
.tools-grid {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
  gap: 16px;
  padding: 0;
}

/* 工具卡片 */
.tool-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: grab;
  position: relative;
  overflow: hidden;
  border: none;
  aspect-ratio: 1;
  display: flex;
  flex-direction: column;
}

.tool-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.tool-card.dragging {
  opacity: 0.5;
  transform: scale(0.95);
  cursor: grabbing;
}

.tool-card.drag-over {
  box-shadow: 0 0 0 2px rgba(31, 199, 111, 0.1);
}

.tool-card-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  gap: 12px;
}

.tool-icon {
  width: 64px;
  height: 64px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition: transform 0.2s;
}

.tool-icon.default-tool-icon {
  background-color: transparent;
  border: 1.5px solid;
  box-shadow: none;
}

.tool-card:hover .tool-icon {
  transform: scale(1.05);
}

.tool-name {
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
  text-align: center;
  line-height: 1.4;
  word-break: break-word;
}

.tool-name.default-tool-name {
  color: #64748b;
}

.tool-menu-trigger {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  color: #9ca3af;
  cursor: pointer;
  transition: all 0.2s;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(4px);
  opacity: 0;
  pointer-events: none;
}

.tool-card:hover .tool-menu-trigger {
  opacity: 1;
  pointer-events: auto;
}

.tool-menu-trigger:hover {
  color: #1f2937;
  background: #f8fafc;
}

.tool-menu-trigger i {
  font-size: 14px;
}

/* 加载状态 */
.loading-state {
  text-align: center;
  padding: 80px 24px;
  background: white;
  border-radius: 16px;
  color: #64748b;
}

.loading-state i {
  font-size: 32px;
  margin-right: 12px;
}

/* 响应式设计 */
@media (max-width: 1920px) {
  .tools-grid {
    grid-template-columns: repeat(10, 1fr);
  }
}

@media (max-width: 1600px) {
  .tools-grid {
    grid-template-columns: repeat(8, 1fr);
  }
}

@media (max-width: 1280px) {
  .tools-grid {
    grid-template-columns: repeat(6, 1fr);
  }
}

@media (max-width: 960px) {
  .tools-grid {
    grid-template-columns: repeat(4, 1fr);
  }
}

@media (max-width: 640px) {
  .tools-grid {
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
  }

  .tool-card {
    padding: 16px;
  }

  .tool-icon {
    width: 48px;
    height: 48px;
    font-size: 24px;
  }

  .tool-name {
    font-size: 12px;
  }
}

@media (max-width: 480px) {
  .tools-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
  }

  .page-header h2 {
    font-size: 20px;
  }
}
</style>

