<template>
  <div class="job-detail-page">
    <div class="page-header">
      <n-space justify="space-between" align="center">
        <div>
          <h1 class="page-title">{{ job?.method || t('Scheduled Job Detail') }}</h1>
        </div>
        <n-space :size="8">
          <n-button 
            v-if="job" 
            type="default"
            size="medium"
            :disabled="loading" 
            @click="toggleJobStatus"
            :class="['toolbar-btn', job.stopped ? 'execute-btn' : 'stop-btn']"
          >
            <template #icon>
              <n-icon>
                <Icon icon="tabler:play" v-if="job.stopped" />
                <Icon icon="tabler:pause" v-else />
              </n-icon>
            </template>
            {{ job.stopped ? t('Start Job') : t('Stop Job') }}
          </n-button>
          <n-button type="default" size="medium" @click="goBack">
            <template #icon>
              <n-icon><Icon icon="tabler:arrow-left" /></n-icon>
            </template>
            {{ t('Back') }}
          </n-button>
        </n-space>
      </n-space>
    </div>

    <div v-if="loading" class="loading">
      <i class="fa fa-spinner fa-spin"></i> {{ t('Loading...') }}
    </div>

    <div v-else-if="job" class="job-content">
      <!-- 基本信息 -->
      <n-card :title="t('Basic Information')">
        <div class="properties-grid">
          <div class="property-group">
            <div class="property-item">
              <label>{{ t('Method') }}</label>
              <input type="text" v-model="job.method" readonly />
            </div>
            <div class="property-item">
              <label>{{ t('Frequency') }}</label>
              <input type="text" v-model="job.frequency" readonly />
            </div>
            <div class="property-item">
              <label>{{ t('Status') }}</label>
              <div class="status-display">
                <n-checkbox v-model:checked="job.stopped" @update:checked="handleStatusChange">
                </n-checkbox>
                <span :class="['status-badge', job.stopped ? 'stopped' : 'running']">
                  {{ job.stopped ? t('Stopped') : t('Running') }}
                </span>
              </div>
            </div>
            <div class="property-item">
              <label>{{ t('Create Log') }}</label>
              <div class="status-display">
                <span v-if="job.create_log" class="status-badge enabled">{{ t('Enabled') }}</span>
                <span v-else class="status-badge disabled">{{ t('Disabled') }}</span>
              </div>
            </div>
          </div>
          <div class="property-group">
            <div class="property-item">
              <label>{{ t('Server Script') }}</label>
              <input type="text" v-model="job.server_script" readonly />
            </div>
            <div class="property-item">
              <label>{{ t('Scheduler Event') }}</label>
              <input type="text" v-model="job.scheduler_event" readonly />
            </div>
            <div class="property-item">
              <label>{{ t('Created At') }}</label>
              <input type="text" v-model="job.creation" readonly />
            </div>
            <div class="property-item">
              <label>{{ t('Updated At') }}</label>
              <input type="text" v-model="job.modified" readonly />
            </div>
          </div>
        </div>
      </n-card>

      <!-- Cron 格式信息 -->
      <n-card v-if="job.frequency === 'Cron' && job.cron_format" :title="t('Cron Format')">
        <div class="cron-section">
          <div class="cron-display">
            <code class="cron-code">{{ job.cron_format }}</code>
          </div>
          <div class="cron-description">
            <h4>{{ t('Cron Format Description') }}</h4>
            <pre class="cron-help">{{ cronHelpText }}</pre>
          </div>
        </div>
      </n-card>

      <!-- 执行历史 -->
      <n-card :title="t('Execution History')">
        <div class="execution-section">
          <div class="execution-item">
            <label>{{ t('Last Execution') }}</label>
            <div class="execution-value">
              <span v-if="job.last_execution" class="datetime-text">{{ formatDateTime(job.last_execution) }}</span>
              <span v-else class="text-muted">{{ t('Never executed') }}</span>
            </div>
          </div>
          <div class="execution-item">
            <label>{{ t('Next Execution') }}</label>
            <div class="execution-value">
              <span v-if="nextExecutionTime" class="datetime-text next-execution">{{ formatDateTime(nextExecutionTime) }}</span>
              <span v-else-if="job.stopped" class="text-muted">{{ t('Job is stopped') }}</span>
              <span v-else class="text-muted">{{ t('Unable to calculate') }}</span>
            </div>
          </div>
        </div>
      </n-card>
    </div>

    <div v-else class="error">
      <i class="fa fa-exclamation-triangle"></i> {{ t('Job not found') }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  NSpace,
  NButton,
  NIcon,
  NCard,
  NCheckbox,
  useMessage
} from 'naive-ui'
import { Icon } from '@iconify/vue'
import { t } from '@/shared/i18n'
import { 
  getScheduledJobDetail, 
  toggleScheduledJobStatus
} from '@/shared/api/scheduledJobs'

const route = useRoute()
const router = useRouter()
const message = useMessage()

// 响应式数据
const job = ref<any>(null)
const loading = ref(false)

// Cron 帮助文本
const cronHelpText = `*  *  *  *  *
┬  ┬  ┬  ┬  ┬
│  │  │  │  │
│  │  │  │  └ day of week (0 - 6) (0 is Sunday)
│  │  │  └───── month (1 - 12)
│  │  └────────── day of month (1 - 31)
│  └─────────────── hour (0 - 23)
└──────────────────── minute (0 - 59)

---

* - Any value
/ - Step values`

// 计算属性
const jobId = computed(() => route.params.id as string)

// 下次执行时间
const nextExecutionTime = ref<string | null>(null)

// 获取任务详情
const fetchJob = async () => {
  if (!jobId.value) return
  
  loading.value = true
  try {
    const jobData = await getScheduledJobDetail(jobId.value)
    // 转换 stopped 字段为布尔类型
    jobData.stopped = Boolean(jobData.stopped)
    job.value = jobData
    
    // 直接使用 next_execution 字段
    if (!jobData.stopped && jobData.next_execution) {
      nextExecutionTime.value = jobData.next_execution
    } else {
      nextExecutionTime.value = null
    }
  } catch (error) {
    console.error('获取任务详情失败:', error)
    message.error(t('Failed to load job detail'))
    job.value = null
  } finally {
    loading.value = false
  }
}

// 处理状态变化
const handleStatusChange = async (checked: boolean) => {
  if (!job.value) return
  
  try {
    const result = await toggleScheduledJobStatus(jobId.value)
    
    if (result.success) {
      message.success(result.message || t('Job status updated successfully'))
      // 状态已经在 v-model 中自动更新了
    } else {
      message.error(result.message || t('Failed to update job status'))
      // 如果保存失败，恢复原状态
      job.value.stopped = !checked
    }
  } catch (error) {
    console.error('Toggle job status error:', error)
    message.error(t('Failed to update job status'))
    // 如果保存失败，恢复原状态
    job.value.stopped = !checked
  }
}

// 切换任务状态
const toggleJobStatus = async () => {
  if (!job.value) return
  
  try {
    const result = await toggleScheduledJobStatus(jobId.value)
    
    if (result.success) {
      message.success(result.message || t('Job status updated successfully'))
      
      // 更新本地状态
      job.value.stopped = !job.value.stopped
    } else {
      message.error(result.message || t('Failed to update job status'))
    }
  } catch (error) {
    console.error('Toggle job status error:', error)
    message.error(t('Failed to update job status'))
  }
}

// 返回列表页
const goBack = () => {
  router.push({ name: 'ScheduledJobList' })
}

// 格式化日期时间
const formatDateTime = (dateTimeStr: string) => {
  if (!dateTimeStr) return '—'
  try {
    const date = new Date(dateTimeStr)
    return date.toLocaleString()
  } catch (error) {
    return dateTimeStr
  }
}

// 生命周期
onMounted(() => {
  fetchJob()
})
</script>

<style scoped>
.job-detail-page {
  width: 100%;
  padding: 16px;
}

.page-header { 
  margin-bottom: 24px; 
}

.page-title { 
  font-size: 28px; 
  font-weight: 700; 
  color: #1f2937; 
  margin: 0 0 8px 0; 
}


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

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

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

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

.job-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 表单样式 */
.properties-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
}

.property-group {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.property-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.property-item label {
  font-weight: 500;
  color: #374151;
  font-size: 14px;
}

.property-item input {
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  background-color: #f9fafb;
  color: #6b7280;
}

.status-display {
  padding: 8px 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 将checkbox选中状态（已停止）的背景改为红色 */
.status-display :deep(.n-checkbox--checked .n-checkbox-box) {
  background-color: #ef4444 !important;
  border-color: #ef4444 !important;
}

.status-display :deep(.n-checkbox--checked .n-checkbox-box:hover) {
  background-color: #dc2626 !important;
  border-color: #dc2626 !important;
}

.status-display :deep(.n-checkbox--checked .n-checkbox-box__border) {
  border-color: #ef4444 !important;
}

.status-badge {
  padding: 4px 10px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  display: inline-block;
  white-space: nowrap;
}

.status-badge.running {
  background: #dcfce7;
  color: #166534;
  border: 1px solid rgba(34, 197, 94, 0.2);
}

.status-badge.stopped {
  background: #fee2e2;
  color: #dc2626;
  border: 1px solid rgba(239, 68, 68, 0.2);
}

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

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

/* Cron 格式样式 */
.cron-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.cron-display {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 16px;
}

.cron-code {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 16px;
  font-weight: 600;
  color: #2563eb;
  background: white;
  padding: 8px 12px;
  border-radius: 4px;
  border: 1px solid #e5e7eb;
  display: inline-block;
}

.cron-description h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: #374151;
}

.cron-help {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  line-height: 1.5;
  color: #6b7280;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 12px;
  margin: 0;
  white-space: pre-wrap;
}

/* 执行历史样式 */
.execution-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.execution-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.execution-item label {
  font-weight: 500;
  color: #374151;
  font-size: 14px;
}

.execution-value {
  padding: 8px 0;
}

.datetime-text {
  color: #374151;
  font-size: 14px;
}

.next-execution {
  color: #dc2626;
  font-weight: 600;
  font-size: 16px;
}

.text-muted {
  color: #9ca3af;
  font-size: 14px;
}

/* 工具栏按钮基础样式 - 与Local Ai Agent工具栏一致 */
.toolbar-btn {
  background: #f3f4f6 !important;
  color: #374151 !important;
  border: 1px solid rgba(0, 0, 0, 0.08) !important;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 清除 Naive UI 按钮内部的边框元素，避免双重边框 */
.toolbar-btn :deep(.n-button__border),
.toolbar-btn :deep(.n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}

.toolbar-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.toolbar-btn:hover:not(:disabled) :deep(.n-button__border),
.toolbar-btn:hover:not(:disabled) :deep(.n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}

/* 执行按钮 - 绿色系（与Local Ai Agent执行按钮配色一致） */
.execute-btn {
  background: #dcfce7 !important;
  color: #166534 !important;
  border-color: rgba(34, 197, 94, 0.2) !important;
}

.execute-btn:hover:not(:disabled) {
  background: #bbf7d0 !important;
  color: #15803d !important;
  border-color: rgba(34, 197, 94, 0.3) !important;
  box-shadow: 0 2px 8px rgba(34, 197, 94, 0.15);
}

/* 停止按钮 - 红色系 */
.toolbar-btn.stop-btn {
  background: #fee2e2 !important;
  color: #dc2626 !important;
  border-color: rgba(239, 68, 68, 0.2) !important;
}

.toolbar-btn.stop-btn :deep(.n-button__border),
.toolbar-btn.stop-btn :deep(.n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}

.toolbar-btn.stop-btn:hover:not(:disabled) {
  background: #fecaca !important;
  color: #b91c1c !important;
  border-color: rgba(239, 68, 68, 0.3) !important;
  box-shadow: 0 2px 8px rgba(239, 68, 68, 0.15);
}

.toolbar-btn.stop-btn:hover:not(:disabled) :deep(.n-button__border),
.toolbar-btn.stop-btn:hover:not(:disabled) :deep(.n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}

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

.toolbar-btn:disabled :deep(.n-button__border),
.toolbar-btn:disabled :deep(.n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .properties-grid {
    grid-template-columns: 1fr;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
}
</style>
