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

interface Script {
  id: number
  name: string
  type: string
  description: string
  status: 'running' | 'stopped'
  createdAt: string
}

// 模拟脚本数据
const scripts = ref<Script[]>([
  { id: 1, name: 'Data Processing', type: 'Python', description: 'Process and transform data', status: 'running', createdAt: '2025-04-10' },
  { id: 2, name: 'Report Generator', type: 'Python', description: 'Generate weekly reports', status: 'stopped', createdAt: '2025-04-08' },
  { id: 3, name: 'Backup Script', type: 'Shell', description: 'Database backup automation', status: 'running', createdAt: '2025-04-05' },
  { id: 4, name: 'Data Sync', type: 'Python', description: 'Sync data between systems', status: 'stopped', createdAt: '2025-04-12' },
])

const searchQuery = ref('')
const filterStatus = ref('all')
const isCreating = ref(false)
const isEditing = ref(false)
const editingScript = ref<Script | null>(null)

const newScriptForm = ref({
  name: '',
  type: 'Python',
  description: '',
})

// 过滤后的脚本
const filteredScripts = computed(() => {
  return scripts.value.filter(script => {
    const matchSearch = script.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      script.description.toLowerCase().includes(searchQuery.value.toLowerCase())
    const matchStatus = filterStatus.value === 'all' || script.status === filterStatus.value
    return matchSearch && matchStatus
  })
})

// 状态样式
const statusClass = (status: string) => {
  switch (status) {
    case 'running': return 'bg-primary-success'
    case 'stopped': return 'bg-gray-500'
    default: return 'bg-gray-500'
  }
}

// 切换状态
const toggleStatus = (script: Script) => {
  script.status = script.status === 'running' ? 'stopped' : 'running'
}

// 删除脚本
const deleteScript = (id: number) => {
  scripts.value = scripts.value.filter(s => s.id !== id)
}

// 编辑脚本
const openEdit = (script: Script) => {
  editingScript.value = { ...script }
  isEditing.value = true
}

const saveEdit = () => {
  if (editingScript.value) {
    const index = scripts.value.findIndex(s => s.id === editingScript.value!.id)
    if (index !== -1) {
      scripts.value[index] = { ...editingScript.value }
    }
  }
  isEditing.value = false
}

const cancelEdit = () => {
  isEditing.value = false
  editingScript.value = null
}

// 新建脚本
const openCreate = () => {
  newScriptForm.value = {
    name: '',
    type: 'Python',
    description: '',
  }
  isCreating.value = true
}

const closeCreate = () => {
  isCreating.value = false
}

const saveNewScript = () => {
  const newId = Math.max(...scripts.value.map(s => s.id), 0) + 1
  scripts.value.push({
    id: newId,
    name: newScriptForm.value.name || 'Untitled Script',
    type: newScriptForm.value.type,
    description: newScriptForm.value.description,
    status: 'stopped',
    createdAt: new Date().toISOString().split('T')[0],
  })
  isCreating.value = false
}
</script>

<template>
  <div class="p-6 min-h-screen">
    <!-- 顶部导航 -->
    <div class="flex justify-between items-center mb-6">
      <div class="flex items-center gap-2">
        <i class="fa-solid fa-code text-orange-500"></i>
        <span class="font-medium">Scripts</span>
      </div>
      <button @click="openCreate" class="bg-gradient-to-r from-primary-orange to-red-500 hover:from-orange-500 hover:to-red-600 text-white px-4 py-2 rounded-lg font-medium flex items-center gap-2 transition-all">
        <i class="fa-solid fa-plus"></i>
        New Script
      </button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="flex gap-4 mb-6">
      <div class="flex-1 relative">
        <i class="fa-solid fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
        <input
          v-model="searchQuery"
          type="text"
          placeholder="Search scripts..."
          class="w-full bg-dark-600 border border-dark-500 rounded-lg py-2 pl-10 pr-4 text-white placeholder-gray-500 focus:outline-none focus:border-primary-orange"
        >
      </div>
      <el-select v-model="filterStatus" placeholder="Select" class="w-40" size="large" popper-class="dark-select-dropdown">
        <el-option label="All Status" value="all" />
        <el-option label="Running" value="running" />
        <el-option label="Stopped" value="stopped" />
      </el-select>
    </div>

    <!-- 脚本列表 -->
    <div class="bg-dark-700 rounded-xl overflow-hidden">
      <table class="w-full">
        <thead class="bg-dark-600">
          <tr>
            <th class="text-left px-5 py-3 text-sm font-medium text-gray-400">Script Name</th>
            <th class="text-left px-5 py-3 text-sm font-medium text-gray-400">Type</th>
            <th class="text-left px-5 py-3 text-sm font-medium text-gray-400">Status</th>
            <th class="text-left px-5 py-3 text-sm font-medium text-gray-400">Created</th>
            <th class="text-right px-5 py-3 text-sm font-medium text-gray-400">Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="script in filteredScripts" :key="script.id" class="border-t border-dark-600 hover:bg-dark-600/50 transition-colors">
            <td class="px-5 py-4">
              <div class="font-medium">{{ script.name }}</div>
              <div class="text-sm text-gray-500">{{ script.description }}</div>
            </td>
            <td class="px-5 py-4">
              <span class="bg-dark-500 px-2 py-1 rounded text-sm">{{ script.type }}</span>
            </td>
            <td class="px-5 py-4">
              <div class="flex items-center gap-2">
                <span class="w-2 h-2 rounded-full" :class="statusClass(script.status)"></span>
                <span class="capitalize text-sm">{{ script.status }}</span>
              </div>
            </td>
            <td class="px-5 py-4 text-gray-400 text-sm">{{ script.createdAt }}</td>
            <td class="px-5 py-4">
              <div class="flex items-center justify-end gap-2">
                <button
                  @click="toggleStatus(script)"
                  class="p-2 rounded-lg hover:bg-dark-500 transition-colors"
                  :title="script.status === 'running' ? 'Stop' : 'Start'"
                >
                  <i :class="['fa-solid', script.status === 'running' ? 'fa-stop' : 'fa-play', 'text-gray-400 hover:text-white']"></i>
                </button>
                <button
                  @click="openEdit(script)"
                  class="p-2 rounded-lg hover:bg-dark-500 transition-colors"
                  title="Edit"
                >
                  <i class="fa-solid fa-pen text-gray-400 hover:text-white"></i>
                </button>
                <button
                  @click="deleteScript(script.id)"
                  class="p-2 rounded-lg hover:bg-dark-500 transition-colors"
                  title="Delete"
                >
                  <i class="fa-solid fa-trash text-gray-400 hover:text-red-400"></i>
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>

      <!-- 空状态 -->
      <div v-if="filteredScripts.length === 0" class="py-12 text-center text-gray-500">
        <i class="fa-solid fa-code text-4xl mb-3"></i>
        <p>No scripts found</p>
      </div>
    </div>

    <!-- 新建脚本弹窗 -->
    <Teleport to="body">
      <div v-if="isCreating" class="fixed inset-0 bg-black/60 flex items-center justify-center z-50">
        <div class="bg-dark-700 rounded-2xl w-full max-w-lg border border-dark-500 shadow-2xl">
          <div class="flex items-center justify-between p-5 border-b border-dark-500">
            <h3 class="text-lg font-semibold">New Script</h3>
            <button @click="closeCreate" class="text-gray-400 hover:text-white transition-colors">
              <i class="fa-solid fa-xmark text-xl"></i>
            </button>
          </div>

          <div class="p-5 space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-300 mb-2">Script Name</label>
              <input
                v-model="newScriptForm.name"
                type="text"
                placeholder="Enter script name..."
                class="w-full bg-dark-600 border border-dark-500 rounded-lg px-4 py-2.5 text-white placeholder-gray-500 focus:outline-none focus:border-primary-orange"
              >
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-300 mb-2">Type</label>
              <el-select v-model="newScriptForm.type" placeholder="Select" class="w-full" size="large" popper-class="dark-select-dropdown">
                <el-option label="Python" value="Python" />
                <el-option label="Shell" value="Shell" />
                <el-option label="JavaScript" value="JavaScript" />
                <el-option label="Go" value="Go" />
              </el-select>
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-300 mb-2">Description</label>
              <textarea
                v-model="newScriptForm.description"
                rows="3"
                placeholder="Describe your script..."
                class="w-full bg-dark-600 border border-dark-500 rounded-lg px-4 py-2.5 text-white placeholder-gray-500 focus:outline-none focus:border-primary-orange resize-none"
              ></textarea>
            </div>
          </div>

          <div class="flex items-center justify-end gap-3 p-5 border-t border-dark-500">
            <button
              @click="closeCreate"
              class="px-4 py-2 rounded-lg bg-dark-600 text-gray-300 hover:bg-dark-500 transition-colors"
            >
              Cancel
            </button>
            <button
              @click="saveNewScript"
              class="px-4 py-2 rounded-lg bg-gradient-to-r from-primary-orange to-red-500 text-white hover:from-orange-500 hover:to-red-600 transition-all"
            >
              Create Script
            </button>
          </div>
        </div>
      </div>
    </Teleport>

    <!-- 编辑脚本弹窗 -->
    <Teleport to="body">
      <div v-if="isEditing" class="fixed inset-0 bg-black/60 flex items-center justify-center z-50">
        <div class="bg-dark-700 rounded-2xl w-full max-w-lg border border-dark-500 shadow-2xl">
          <div class="flex items-center justify-between p-5 border-b border-dark-500">
            <h3 class="text-lg font-semibold">Edit Script</h3>
            <button @click="cancelEdit" class="text-gray-400 hover:text-white transition-colors">
              <i class="fa-solid fa-xmark text-xl"></i>
            </button>
          </div>

          <div class="p-5 space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-300 mb-2">Script Name</label>
              <input
                v-model="editingScript!.name"
                type="text"
                class="w-full bg-dark-600 border border-dark-500 rounded-lg px-4 py-2.5 text-white focus:outline-none focus:border-primary-orange"
              >
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-300 mb-2">Type</label>
              <el-select v-model="editingScript!.type" placeholder="Select" class="w-full" size="large" popper-class="dark-select-dropdown">
                <el-option label="Python" value="Python" />
                <el-option label="Shell" value="Shell" />
                <el-option label="JavaScript" value="JavaScript" />
                <el-option label="Go" value="Go" />
              </el-select>
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-300 mb-2">Description</label>
              <textarea
                v-model="editingScript!.description"
                rows="3"
                class="w-full bg-dark-600 border border-dark-500 rounded-lg px-4 py-2.5 text-white focus:outline-none focus:border-primary-orange resize-none"
              ></textarea>
            </div>
          </div>

          <div class="flex items-center justify-end gap-3 p-5 border-t border-dark-500">
            <button
              @click="cancelEdit"
              class="px-4 py-2 rounded-lg bg-dark-600 text-gray-300 hover:bg-dark-500 transition-colors"
            >
              Cancel
            </button>
            <button
              @click="saveEdit"
              class="px-4 py-2 rounded-lg bg-gradient-to-r from-primary-orange to-red-500 text-white hover:from-orange-500 hover:to-red-600 transition-all"
            >
              Save Changes
            </button>
          </div>
        </div>
      </div>
    </Teleport>
  </div>
</template>
