<template>
  <div class="page">
    <!-- 二级操作栏 -->
    <div class="secondary-bar">
      <div class="left-actions">
        <button class="btn btn-outline" @click="goBack">
          <i class="fa fa-arrow-left"></i> {{ t('Back') }}
        </button>
        <button 
          v-if="job && (job.status === 'started' || job.status === 'queued')"
          class="btn btn-warning" 
          @click="stopJob"
          :disabled="stopping"
        >
          <i :class="stopping ? 'fa fa-spinner fa-spin' : 'fa fa-stop'"></i> {{ t('Stop Job') }}
        </button>
        <button 
          v-if="job"
          class="btn btn-danger" 
          @click="deleteJob"
          :disabled="deleting"
        >
          <i :class="deleting ? 'fa fa-spinner fa-spin' : 'fa fa-trash'"></i> {{ t('Delete Job') }}
        </button>
      </div>
      <div class="right-actions">
        <button class="btn btn-primary" @click="refresh" :disabled="loading">
          <i :class="loading ? 'fa fa-spinner fa-spin' : 'fa fa-refresh'"></i> {{ t('Refresh') }}
        </button>
      </div>
    </div>

    <div class="main-layout">
      <!-- 主内容区域 -->
      <div class="main-content">
        <div v-if="loading" class="loading">
          <i class="fa fa-spinner fa-spin"></i> {{ t('Loading...') }}
        </div>
        <div v-else-if="!job" class="error">
          <i class="fa fa-exclamation-triangle"></i> {{ t('Job not found') }}
        </div>
        <div v-else class="content-grid">
          <!-- 基本信息卡片 -->
          <div class="info-card">
            <h4>{{ t('Job Details') }}</h4>
            <div class="info-grid">
              <div class="info-item">
                <label>{{ t('Job ID') }}</label>
                <div class="value">{{ job.job_id }}</div>
              </div>
              <div class="info-item">
                <label>{{ t('Job Name') }}</label>
                <div class="value">{{ job.job_name || '—' }}</div>
              </div>
              <div class="info-item">
                <label>{{ t('Queue') }}</label>
                <div class="value">
                  <span class="queue-badge">{{ t(job.queue) }}</span>
                </div>
              </div>
              <div class="info-item">
                <label>{{ t('Job Status') }}</label>
                <div class="value">
                  <span class="status-badge" :class="job.status">{{ t(job.status) }}</span>
                </div>
              </div>
              <div class="info-item">
                <label>{{ t('Creation') }}</label>
                <div class="value">{{ formatDateTime(job.creation) }}</div>
              </div>
              <div class="info-item">
                <label>{{ t('Modified') }}</label>
                <div class="value">{{ formatDateTime(job.modified) }}</div>
              </div>
              <div class="info-item">
                <label>{{ t('Owner') }}</label>
                <div class="value">{{ job.owner || '—' }}</div>
              </div>
              <div class="info-item">
                <label>{{ t('Modified By') }}</label>
                <div class="value">{{ job.modified_by || '—' }}</div>
              </div>
            </div>
          </div>

          <!-- 执行时间卡片 -->
          <div class="time-card">
            <h4>{{ t('Execution Time') }}</h4>
            <div class="time-grid">
              <div class="time-item">
                <label>{{ t('Started At') }}</label>
                <div class="value">{{ formatDateTime(job.started_at) }}</div>
              </div>
              <div class="time-item">
                <label>{{ t('Ended At') }}</label>
                <div class="value">{{ formatDateTime(job.ended_at) }}</div>
              </div>
              <div class="time-item">
                <label>{{ t('Time Taken') }}</label>
                <div class="value">{{ formatDuration(job.time_taken) }}</div>
              </div>
              <div class="time-item">
                <label>{{ t('Timeout') }}</label>
                <div class="value">{{ job.timeout || '—' }}</div>
              </div>
            </div>
          </div>

          <!-- 任务参数卡片 -->
          <div class="arguments-card">
            <h4>{{ t('Job Arguments') }}</h4>
            <div class="arguments-container">
              <pre v-if="job.arguments">{{ formatArguments(job.arguments) }}</pre>
              <div v-else class="no-data">{{ t('No arguments') }}</div>
            </div>
          </div>

          <!-- 异常信息卡片 -->
          <div v-if="job.exc_info" class="exception-card">
            <h4>{{ t('Exception Info') }}</h4>
            <div class="exception-container">
              <pre>{{ job.exc_info }}</pre>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { t } from '@/shared/i18n'
import { useDialog, useMessage } from 'naive-ui'
import { getLocalJobDetail, deleteLocalJob, stopLocalJob } from '@/shared/api/localJobs'

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

const loading = ref(true)
const stopping = ref(false)
const deleting = ref(false)
const job = ref<any>(null)

async function fetchJobDetail() {
  loading.value = true
  try {
    const jobId = route.params.id as string
    const result = await getLocalJobDetail(jobId)
    
    if (result.success) {
      job.value = result.data
    } else {
      job.value = null
      message.error(t('Failed to load job detail'))
    }
  } catch (error) {
    console.error('Fetch job detail error:', error)
    job.value = null
    message.error(t('Failed to load job detail'))
  } finally {
    loading.value = false
  }
}

async function stopJob() {
  if (!job.value) return
  
  dialog.warning({
    title: t('Confirm Stop'),
    content: t('Are you sure you want to stop this job?'),
    positiveText: t('Stop'),
    negativeText: t('Cancel'),
    onPositiveClick: async () => {
      stopping.value = true
      try {
        const result = await stopLocalJob(job.value.job_id)
        
        if (result.success) {
          message.success(t('Job stopped successfully'))
          await fetchJobDetail()
        } else {
          message.error(t('Failed to stop job'))
        }
      } catch (error) {
        console.error('Stop error:', error)
        message.error(t('Failed to stop job'))
      } finally {
        stopping.value = false
      }
    }
  })
}

async function deleteJob() {
  if (!job.value) return
  
  dialog.error({
    title: t('Confirm Delete'),
    content: t('Are you sure you want to delete this job?'),
    positiveText: t('Delete'),
    negativeText: t('Cancel'),
    onPositiveClick: async () => {
      deleting.value = true
      try {
        const result = await deleteLocalJob(job.value.job_id)
        
        if (result.success) {
          message.success(t('Job deleted successfully'))
          goBack()
        } else {
          message.error(t('Failed to delete job'))
        }
      } catch (error) {
        console.error('Delete error:', error)
        message.error(t('Failed to delete job'))
      } finally {
        deleting.value = false
      }
    }
  })
}

function refresh() {
  fetchJobDetail()
}

function goBack() {
  router.push({ name: 'LocalJobList' })
}

function formatDateTime(dateStr: string) {
  if (!dateStr) return '—'
  try {
    return new Date(dateStr).toLocaleString()
  } catch {
    return dateStr
  }
}

function formatDuration(duration: string | number) {
  if (!duration) return '—'
  if (typeof duration === 'number') {
    return `${duration}s`
  }
  return duration
}

function formatArguments(argumentsStr: string) {
  try {
    const parsed = JSON.parse(argumentsStr)
    return JSON.stringify(parsed, null, 2)
  } catch {
    return argumentsStr
  }
}

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

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

.secondary-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 12px 0;
  border-bottom: 1px solid #e5e7eb;
}

.left-actions, .right-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.btn {
  height: 36px;
  padding: 0 16px;
  border: none;
  border-radius: 8px;
  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);
}

.btn-outline {
  background: #f8fafc;
  color: #64748b;
  border: 1px solid #e2e8f0;
}

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

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

.btn-primary:hover {
  background: #2563eb;
}

.btn-warning {
  background: #f59e0b;
  color: white;
}

.btn-warning:hover {
  background: #d97706;
}

.btn-danger {
  background: #ef4444;
  color: white;
}

.btn-danger:hover {
  background: #dc2626;
}

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

.main-layout {
  width: 100%;
}

.main-content {
  width: 100%;
}

.content-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  width: 100%;
}

.info-card, .time-card, .arguments-card, .exception-card {
  background: #fff;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.info-card h4, .time-card h4, .arguments-card h4, .exception-card h4 {
  margin: 0 0 16px 0;
  font-size: 18px;
  font-weight: 600;
  color: #111827;
}

.info-grid, .time-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.info-item, .time-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-item label, .time-item label {
  font-size: 12px;
  font-weight: 500;
  color: #6b7280;
  text-transform: uppercase;
  letter-spacing: 0.05em;
}

.info-item .value, .time-item .value {
  font-size: 14px;
  color: #111827;
  font-weight: 500;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 11px;
  font-weight: 500;
  display: inline-block;
}

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

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

.status-badge.finished {
  background: #dcfce7;
  color: #166534;
}

.status-badge.failed {
  background: #fee2e2;
  color: #991b1b;
}

.status-badge.deferred {
  background: #f3e8ff;
  color: #7c3aed;
}

.status-badge.scheduled {
  background: #e0f2fe;
  color: #0369a1;
}

.status-badge.canceled {
  background: #f1f5f9;
  color: #475569;
}

.queue-badge {
  background: #eef2ff;
  color: #334155;
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 11px;
  font-weight: 500;
  display: inline-block;
}

.arguments-container, .exception-container {
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  padding: 16px;
  max-height: 300px;
  overflow-y: auto;
}

.arguments-container pre, .exception-container pre {
  margin: 0;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  line-height: 1.5;
  color: #374151;
  white-space: pre-wrap;
  word-break: break-word;
}

.no-data {
  color: #6b7280;
  font-style: italic;
  text-align: center;
  padding: 20px;
}

.loading, .error {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 40px;
  color: #6b7280;
  font-size: 16px;
}

.error {
  color: #ef4444;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .content-grid {
    grid-template-columns: 1fr;
  }
  
  .info-grid, .time-grid {
    grid-template-columns: 1fr;
  }
}
</style>
