<template>
  <div class="page">
    <div class="page-header">
      <div class="header-left">
        <h2>{{ t('AI Agents') }}</h2>
        <p class="page-description">{{ t('Manage and configure your AI agents workflows') }}</p>
      </div>
      <div class="header-right">
        <div class="filters">
          <n-input
            v-model:value="searchQuery"
            :placeholder="t('Search agents...')"
            clearable
            style="width: 200px"
          />
          <n-select
            v-model:value="statusFilter"
            :options="statusOptions"
            :placeholder="t('Status')"
            style="width: 120px"
          />
        </div>
        <div class="view-toggle">
          <button 
            class="toggle-btn" 
            :class="{ active: viewMode === 'list' }"
            @click="viewMode = 'list'"
            :title="t('List View')"
          >
            <i class="fa fa-list"></i>
          </button>
          <button 
            class="toggle-btn" 
            :class="{ active: viewMode === 'card' }"
            @click="viewMode = 'card'"
            :title="t('Card View')"
          >
            <i class="fa fa-th-large"></i>
          </button>
        </div>
        <button class="refresh-btn" @click="reload" :disabled="loading">
          <i :class="loading ? 'fa fa-spinner fa-spin' : 'fa fa-refresh'"></i>
        </button>
        <button 
          v-if="selectedAgents.length === 0"
          class="create-btn" 
          @click="createAgent"
          :disabled="creating || loading"
        >
          <i class="fa fa-plus"></i>
          {{ t('Create Agent') }}
        </button>
        <button 
          v-else
          class="delete-btn" 
          @click="handleDeleteSelected" 
          :disabled="deleting || loading"
        >
          <i class="fa fa-trash"></i>
          {{ t('Delete Selected') }} ({{ selectedAgents.length }})
        </button>
      </div>
    </div>

    <div class="page-content">
      <div v-if="loading" class="loading">
        <i class="fa fa-spinner fa-spin"></i> {{ t('Loading...') }}
      </div>
      <div v-else>
        <!-- 卡片视图 -->
        <div v-if="viewMode === 'card'" class="agent-grid">
          <div 
            v-for="agent in agents" 
            :key="agent.name" 
            class="agent-card" 
            :class="{ selected: selectedAgents.includes(agent.name) }"
            @click="toggleAgentSelection(agent.name)"
          >
            <div class="card-checkbox">
              <input 
                type="checkbox" 
                :checked="selectedAgents.includes(agent.name)"
                @click.stop="toggleAgentSelection(agent.name)"
              />
            </div>
            <div class="card-content" @click.stop="openDetail(agent.name)">
              <div class="info">
                <div class="title">{{ agent.agent_name || agent.name }}</div>
                <div class="desc">{{ agent.name }}</div>
                <div class="meta">
                  <span v-if="agent.enabled" class="enabled-badge enabled">{{ t('Enabled') }}</span>
                  <span v-else class="enabled-badge disabled">{{ t('Disabled') }}</span>
                  <span v-if="agent.trigger_mode" class="badge">{{ t(agent.trigger_mode) }}</span>
                  <span v-if="agent.status" class="status-badge" :class="agent.status">{{ t(agent.status) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 卡片视图分页 -->
        <div v-if="viewMode === 'card'" class="list-pagination">
          <n-pagination v-model:page="page" :page-count="pageCount" size="small" />
        </div>

        <!-- 列表视图 -->
        <div v-else class="agent-list">
          <div class="list-header">
            <div class="col-checkbox">
              <input 
                type="checkbox" 
                :checked="selectedAgents.length === agents.length && agents.length > 0"
                :indeterminate="selectedAgents.length > 0 && selectedAgents.length < agents.length"
                @change="toggleSelectAll"
              />
            </div>
            <div class="col-name">{{ t('Name') }}</div>
            <div class="col-enabled">{{ t('Enabled') }}</div>
            <div class="col-trigger">{{ t('Trigger Mode') }}</div>
            <div class="col-status">{{ t('Status') }}</div>
            <div class="col-actions">{{ t('Actions') }}</div>
          </div>
          <div class="list-body">
            <div 
              v-for="agent in agents" 
              :key="agent.name" 
              class="list-item" 
              :class="{ selected: selectedAgents.includes(agent.name) }"
              @click="openDetail(agent.name)"
            >
              <div class="col-checkbox">
                <input 
                  type="checkbox" 
                  :checked="selectedAgents.includes(agent.name)"
                  @click.stop="toggleAgentSelection(agent.name)"
                />
              </div>
              <div class="col-name" @click.stop="openDetail(agent.name)">
                <div class="name">{{ agent.agent_name || agent.name }}</div>
                <div class="description">{{ agent.name }}</div>
              </div>
              <div class="col-enabled" @click.stop="openDetail(agent.name)">
                <span v-if="agent.enabled" class="enabled-badge enabled">{{ t('Enabled') }}</span>
                <span v-else class="enabled-badge disabled">{{ t('Disabled') }}</span>
              </div>
              <div class="col-trigger" @click.stop="openDetail(agent.name)">
                <span class="badge">{{ t(agent.trigger_mode || '—') }}</span>
              </div>
              <div class="col-status" @click.stop="openDetail(agent.name)">
                <span class="status-badge" :class="agent.status">{{ t(agent.status) }}</span>
              </div>
              <div class="col-actions">
                <button class="action-btn" @click.stop="executeAgent(agent.name)" :title="t('Execute')">
                  <i class="fa fa-play"></i>
                </button>
                <button class="action-btn" @click.stop="editAgent(agent)" :title="t('Edit')">
                  <i class="fa fa-edit"></i>
                </button>
                <button class="action-btn" @click.stop="deleteAgent(agent.name)" :title="t('Delete')">
                  <i class="fa fa-trash"></i>
                </button>
              </div>
            </div>
          </div>
          <!-- 分页 -->
          <div class="list-pagination">
            <n-pagination v-model:page="page" :page-count="pageCount" size="small" />
          </div>
        </div>
      </div>
    </div>


    <n-modal v-model:show="showEditModal" preset="dialog" :title="t('Edit Agent')">
      <n-form :model="editForm" :rules="editRules" ref="editFormRef">
        <n-form-item :label="t('Name')" path="name">
          <n-input
            v-model:value="editForm.name"
            :placeholder="t('Enter agent name')"
          />
        </n-form-item>
        <n-form-item :label="t('Description')" path="description">
          <n-input
            v-model:value="editForm.description"
            type="textarea"
            :placeholder="t('Enter agent description')"
            :rows="3"
          />
        </n-form-item>
        <n-form-item :label="t('Status')" path="status">
          <n-select
            v-model:value="editForm.status"
            :options="statusOptions"
            :placeholder="t('Select status')"
          />
        </n-form-item>
      </n-form>
      <template #action>
        <n-button @click="showEditModal = false">{{ t('Cancel') }}</n-button>
        <n-button type="primary" @click="handleUpdate">{{ t('Update') }}</n-button>
      </template>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { t } from '../../shared/i18n'
import { NInput, NSelect, NPagination, NModal, NForm, NFormItem, NButton, useMessage, useDialog } from 'naive-ui'
import { useAgentStore } from '../../shared/stores/agent'
import { type AIAgent } from '../../shared/types/agent'

const router = useRouter()
const message = useMessage()
const dialog = useDialog()
const agentStore = useAgentStore()

// 响应式数据
const loading = ref(false)
const creating = ref(false)
const deleting = ref(false)
const agents = ref<AIAgent[]>([])
const allAgents = ref<AIAgent[]>([]) // 保存所有原始数据
const total = ref(0)
const selectedAgents = ref<string[]>([])
const viewMode = ref<'card' | 'list'>(
  (localStorage.getItem('agentListViewMode') as 'card' | 'list') || 'list'
)
const searchQuery = ref('')
const statusFilter = ref('all')
const page = ref(1)
const pageSize = ref(parseInt(localStorage.getItem('itemsPerPage') || '10'))
const showEditModal = ref(false)
const currentAgent = ref<AIAgent | null>(null)

// 表单数据
const editForm = reactive({
  name: '',
  description: '',
  status: 'draft'
})

// 表单验证规则

const editRules = {
  name: [{ required: true, message: t('Please enter agent name'), trigger: 'blur' }],
  description: [{ required: true, message: t('Please enter agent description'), trigger: 'blur' }]
}

// 状态选项
const statusOptions = computed(() => [
  { label: t('All'), value: 'all' },
  { label: t('Draft'), value: 'Draft' },
  { label: t('Active'), value: 'Active' },
  { label: t('Pending'), value: 'Pending' },
  { label: t('Failed'), value: 'Failed' },
  { label: t('Completed'), value: 'Completed' }
])

const pageCount = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))

// 获取智能体列表
async function fetchAgents() {
  loading.value = true
  try {
    const params = new URLSearchParams({
      page: page.value.toString(),
      page_size: pageSize.value.toString()
    })
    
    const res = await fetch(`/api/action/jingrow.ai.utils.jlocal.get_local_ai_agents_list?${params}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      credentials: 'include',
      body: JSON.stringify({
        page: page.value,
        page_size: pageSize.value,
        fields: ['name', 'agent_name', 'status', 'enabled', 'trigger_mode', 'progress', 'ai_repeat', 'creation', 'modified', 'modified_by', 'description'],
        order_by: 'modified desc'
      })
    })
    
    const data = await res.json()
    
    const result = data.message
    allAgents.value = (result.items || []).map((a: any) => ({
      name: a.name,
      agent_name: a.agent_name,
      status: a.status,
      enabled: a.enabled,
      trigger_mode: a.trigger_mode,
      progress: a.progress,
      ai_repeat: a.ai_repeat,
      creation: a.creation,
      modified: a.modified,
      modified_by: a.modified_by
    }))
    
    // 处理数据（搜索和过滤）
    processAgents()
    total.value = result.total || 0
  } catch (error) {
    console.error('获取智能体列表失败:', error)
    agents.value = []
    allAgents.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

function processAgents() {
  let filteredAgents = [...allAgents.value]
  
  // 前端搜索和过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filteredAgents = filteredAgents.filter(agent => 
      agent.agent_name?.toLowerCase().includes(query) ||
      agent.name?.toLowerCase().includes(query)
    )
  }
  
  if (statusFilter.value !== 'all') {
    filteredAgents = filteredAgents.filter(agent => agent.status === statusFilter.value)
  }
  
  agents.value = filteredAgents
}

function reload() {
  fetchAgents()
}

// 选择相关函数
function toggleAgentSelection(agentName: string) {
  const index = selectedAgents.value.indexOf(agentName)
  if (index > -1) {
    selectedAgents.value.splice(index, 1)
  } else {
    selectedAgents.value.push(agentName)
  }
}

function toggleSelectAll() {
  if (selectedAgents.value.length === agents.value.length) {
    selectedAgents.value = []
  } else {
    selectedAgents.value = agents.value.map(agent => agent.name)
  }
}

async function handleDeleteSelected() {
  if (selectedAgents.value.length === 0) return
  
  dialog.error({
    title: t('Confirm Delete'),
    content: t('Are you sure you want to delete the selected agents? This action cannot be undone.'),
    positiveText: t('Delete'),
    negativeText: t('Cancel'),
    onPositiveClick: async () => {
      deleting.value = true
      try {
        const { deleteAgents } = await import('@/shared/api/agents')
        const result = await deleteAgents(selectedAgents.value)
        
        if (result.success) {
          // 删除成功，重新加载数据
          selectedAgents.value = []
          await fetchAgents()
        } else {
          alert(t('Delete failed') + ': ' + (result.message || t('Unknown error')))
        }
      } catch (error) {
        console.error('Delete error:', error)
        alert(t('Delete failed') + ': ' + t('Network error'))
      } finally {
        deleting.value = false
      }
    }
  })
}

// 监听搜索和筛选变化
watch([searchQuery, statusFilter], () => {
  page.value = 1 // 重置到第一页
  // 重新处理数据，不需要重新请求API
  processAgents()
}, { deep: true })

// 监听分页变化
watch([page], () => {
  fetchAgents()
})

// 监听每页数量变化（从系统设置）
watch(() => localStorage.getItem('itemsPerPage'), (newValue) => {
  if (newValue) {
    pageSize.value = parseInt(newValue)
    page.value = 1 // 重置到第一页
    fetchAgents()
  }
})

watch(viewMode, (m) => {
  localStorage.setItem('agentListViewMode', m)
})

function openDetail(name: string) {
  router.push({ name: 'AgentDetail', params: { id: name } })
}

function createAgent() {
  // 仅跳转到新建模式，由详情页保存时再创建后端记录
  router.push({ name: 'AgentDetail', params: { id: 'new' } })
}

function editAgent(agent: AIAgent) {
  currentAgent.value = agent
  editForm.name = agent.name
  editForm.description = ''
  editForm.status = agent.status || 'draft'
  showEditModal.value = true
}

async function executeAgent(name: string) {
  try {
    const result = await agentStore.executeAgent(name)
    if (result.success) {
      message.success(t('Agent executed successfully'))
      fetchAgents()
    } else {
      message.error(result.error || t('Execution failed'))
    }
  } catch (error) {
    message.error(t('Execution failed'))
  }
}

async function deleteAgent(_name: string) {
  try {
    // 这里需要实现删除API
    message.success(t('Agent deleted successfully'))
    fetchAgents()
  } catch (error) {
    message.error(t('Delete failed'))
  }
}


async function handleUpdate() {
  try {
    // 这里需要实现更新API
    message.success(t('Agent updated successfully'))
    showEditModal.value = false
    fetchAgents()
  } catch (error) {
    message.error(t('Update failed'))
  }
}

onMounted(() => {
  fetchAgents()
})
</script>

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

.page-header {
  display: flex;
  align-items: flex-start; 
  justify-content: space-between;
  margin-bottom: 24px;
}

.header-left h2 {
  font-size: 28px;
  font-weight: 700;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.page-description {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

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

.filters { 
  display: flex; 
  gap: 8px; 
  align-items: center; 
}

.view-toggle {
  display: flex;
  background: #f8fafc;
  border-radius: 8px;
  padding: 2px;
  border: 1px solid #e2e8f0;
}

.toggle-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: transparent;
  color: #64748b;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.toggle-btn:hover {
  background: #e2e8f0;
  color: #475569;
}

.toggle-btn.active {
  background: #2563eb;
  color: white;
}

/* 现代化刷新按钮 */
.refresh-btn {
  width: 36px;
  height: 36px;
  border: none;
  border-radius: 8px;
  background: #f8fafc;
  color: #64748b;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.refresh-btn:hover {
  background: #e2e8f0;
  color: #475569;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.refresh-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.refresh-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.refresh-btn:disabled:hover {
  background: #f8fafc;
  color: #64748b;
  transform: none;
  box-shadow: none;
}

/* 新建按钮 */
.create-btn {
  height: 36px;
  padding: 0 16px;
  border: none;
  border-radius: 8px;
  background: #2563eb;
  color: white;
  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;
}

.create-btn:hover {
  background: #1d4ed8;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(37, 99, 235, 0.3);
}

.create-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(37, 99, 235, 0.3);
}

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

.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #6b7280;
  font-size: 16px;
}

.loading i {
  margin-right: 8px;
}

/* 卡片视图 */
.agent-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.agent-card {
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.agent-card:hover {
  border-color: #2563eb;
  box-shadow: 0 4px 12px rgba(37, 99, 235, 0.1);
  transform: translateY(-2px);
}


.agent-card .title {
  font-size: 16px;
  font-weight: 600;
  color: #111827;
  margin-bottom: 8px;
  line-height: 1.4;
}

.agent-card .desc {
  font-size: 14px;
  color: #6b7280;
  line-height: 1.5;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.agent-card .meta {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.badge {
  background: #f3f4f6;
  color: #374151;
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.Draft {
  background: #fef3c7;
  color: #92400e;
}

.status-badge.Active {
  background: #d1fae5;
  color: #065f46;
}

.status-badge.Pending {
  background: #dbeafe;
  color: #1e40af;
}

.status-badge.Failed {
  background: #fee2e2;
  color: #dc2626;
}

.status-badge.Completed {
  background: #d1fae5;
  color: #065f46;
}

.enabled-badge {
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
}

.enabled-badge.enabled {
  background: #d1fae5;
  color: #065f46;
}

.enabled-badge.disabled {
  background: #fee2e2;
  color: #dc2626;
}

/* 列表视图 */
.agent-list {
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  overflow: hidden;
}

.list-header {
  display: grid;
  grid-template-columns: 40px 1fr 100px 120px 100px 120px;
  gap: 16px;
  padding: 16px 20px;
  background: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
  font-size: 14px;
  font-weight: 600;
  color: #374151;
}

.list-body {
  max-height: 600px;
  overflow-y: auto;
}

.list-item {
  display: grid;
  grid-template-columns: 40px 1fr 100px 120px 100px 120px;
  gap: 16px;
  padding: 16px 20px;
  border-bottom: 1px solid #f3f4f6;
  cursor: pointer;
  transition: background-color 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.list-item:hover {
  background: #f9fafb;
}

.list-item:last-child {
  border-bottom: none;
}

.col-enabled {
  display: flex;
  align-items: center;
}

.col-name {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.col-name .name {
  font-weight: 600;
  color: #111827;
  font-size: 14px;
  margin-bottom: 2px;
}

.col-name .description {
  color: #6b7280;
  font-size: 12px;
  line-height: 1.3;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.col-trigger {
  display: flex;
  align-items: center;
  color: #6b7280;
  font-size: 13px;
}

.col-status {
  display: flex;
  align-items: center;
}


.col-actions {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.action-btn {
  width: 28px;
  height: 28px;
  border: none;
  background: #f3f4f6;
  color: #6b7280;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.action-btn:hover {
  background: #3b82f6;
  color: white;
}

.list-pagination {
  padding: 16px 20px;
  border-top: 1px solid #e5e7eb;
  background: #f9fafb;
  display: flex;
  justify-content: center;
}

/* 选择相关样式 */
.col-checkbox {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
}

.card-checkbox {
  position: absolute;
  top: 12px;
  right: 12px;
  z-index: 10;
}

.card-checkbox input[type="checkbox"] {
  cursor: pointer;
  accent-color: #3b82f6;
}

.agent-card {
  position: relative;
}

.agent-card.selected {
  border-color: #3b82f6;
  background: #f0f9ff;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.list-item.selected {
  background: #f0f9ff;
  border-color: #3b82f6;
}

.delete-btn {
  background: #ef4444;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.delete-btn:hover {
  background: #dc2626;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);
}

.delete-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(239, 68, 68, 0.3);
}

.delete-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.delete-btn i {
  font-size: 12px;
}
</style>