<script setup lang="ts">
import { ref } from 'vue'
import { RouterLink } from 'vue-router'
import {
  PageLayout,
  QueryStateBoundary,
  KArtsellMetricCard,
  KsButton,
  KsSelect,
  KsTextField,
  KsDateField,
  KsStatusTag,
} from '../../../shared/ui'


// KBX v60 Exception-Driven Work Queue Metrics (§2.4 Exception Driven)
const workQueueSummary = [
  { label: '전체 모델 수', count: 42, status: 'info' as const, filter: 'all', trend: 'neutral' as const },
  { label: 'Shadow Run 실시간', count: 6, status: 'success' as const, filter: 'running', trend: 'up' as const },
  { label: '승인 대기 (Maker-Checker)', count: 8, status: 'warning' as const, filter: 'approval', trend: 'neutral' as const },
  { label: 'PBO/DSR 검증 경고', count: 3, status: 'danger' as const, filter: 'warning', trend: 'down' as const },
  { label: '데이터 수집 예외', count: 2, status: 'danger' as const, filter: 'exception', trend: 'down' as const }
]

// KBX v60 Exception Items (처리 대상 13건 노출)
const exceptionItems = ref([
  { id: 'EX-2026-001', type: 'DSR/PBO 미달', model: 'Aegis-Core-Alpha-v1.4', module: '매도 의사결정', status: '경고', severity: 'warning' as const, time: '10분 전', route: '/governance/approvals' },
  { id: 'EX-2026-002', type: 'Maker-Checker 승인대기', model: 'K-Trend-Sell-v2.1', module: '포트폴리오 리밸런싱', status: '대기', severity: 'warning' as const, time: '25분 전', route: '/governance/approvals' },
  { id: 'EX-2026-003', type: 'KIS API 수집 오류', model: 'MarketData-KRX-Realtime', module: '시장 데이터 수집', status: '오류', severity: 'danger' as const, time: '1시간 전', route: '/ops/market-data-history' },
  { id: 'EX-2026-004', type: 'Shadow Run 타임아웃', model: 'Shadow-Batch-Job-8492', module: 'Shadow Run', status: '오류', severity: 'danger' as const, time: '2시간 전', route: '/model-ops/shadow-run-jobs' },
])

// KBX Quick System Rules (§2.1 Familiar First)
const operationalGuides = [
  { title: '단축키 가이드', desc: '조회 [F3], 저장 [F8], 메뉴 검색 [Ctrl+K] 키로 업무를 고속 수행합니다.' },
  { title: '감사 추적 보존', desc: '모든 데이터 및 모델 승인 변경은 수정/삭제 없이 Correction Event로 영구 보존됩니다.' },
  { title: '자동주문 차단', desc: '현재 KIS 실제 주문 제출 기능은 OFF 상태이며 오직 Shadow 평가 모드만 동작합니다.' },
]

// Filter & Search states
const activeFilter = ref('all')
const selectedModule = ref('all')
const searchKeyword = ref('')
const searchDate = ref('2026-08-08 ~ 2026-08-15')
const isLoading = ref(false)

const moduleOptions = [
  { label: '전체 모듈', value: 'all' },
  { label: 'Research / 매도', value: 'research' },
  { label: 'ModelOps', value: 'model' },
  { label: 'Governance', value: 'governance' }
]

const handleFilter = (filterKey: string) => {
  activeFilter.value = filterKey
}

const handleSearch = () => {
  isLoading.value = true
  setTimeout(() => {
    isLoading.value = false
  }, 300)
}
</script>

<template>
  <PageLayout
    title="업무 워크스페이스 (Work Queue & Reconcile)"
    subtitle="Exception Driven 업무 큐 및 시스템 헬스 관제 센터"
  >
    <!-- Top-Right Actions Slot -->
    <template #actions>
      <KsStatusTag value="KBX v60 Standard" severity="info" />
      <KsStatusTag value="자동주문/KIS OFF" severity="warning" />
    </template>

    <!-- Standard Command Bar Slot -->
    <template #commandBar>
      <KsButton label="조회 [F3]" variant="primary" size="sm" @click="handleSearch" />
      <KsButton label="예외건만 보기" variant="secondary" size="sm" @click="handleFilter('exception')" />
      <RouterLink to="/model-ops/shadow-run-jobs">
        <KsButton label="Shadow Run 실행" variant="secondary" size="sm" />
      </RouterLink>
      <RouterLink to="/governance/approvals">
        <KsButton label="승인 큐 이동" variant="secondary" size="sm" />
      </RouterLink>
    </template>

    <!-- KPI / Summary Slot -->
    <template #summary>
      <KArtsellMetricCard
        v-for="item in workQueueSummary"
        :key="item.filter"
        :title="item.label"
        :value="item.count"
        :status="item.status"
        :trend="item.trend"
        class="ks-metric-clickable"
        :class="{ 'ks-metric-active': activeFilter === item.filter }"
        @click="handleFilter(item.filter)"
      />
    </template>

    <!-- Filters Slot (Auto-Context Provider + Standard Set Widths) -->
    <template #filters>
      <div class="ks-filter-group">
        <KsDateField
          v-model="searchDate"
          label="조회기간"
          type="range"
          inline
          class="ks-set-md"
        />

        <KsSelect
          v-model="selectedModule"
          label="업무모듈"
          :options="moduleOptions"
          inline
          class="ks-set-md"
        />
        <KsTextField
          v-model="searchKeyword"
          label="통합검색"
          placeholder="모델ID / 예외코드 / 담당자"
          inline
          class="ks-set-md"
        />

        <KsButton label="검색" variant="primary" size="md" class="ks-filter-btn" @click="handleSearch" />
      </div>
    </template>






    <!-- Main Content Workspace with Standard Query State Boundary -->
    <QueryStateBoundary
      :loading="isLoading"
      :empty="exceptionItems.length === 0"
      skeleton-type="table"
      :skeleton-rows="4"
    >
      <div class="ks-home-body">
        <!-- Exception Work Queue Grid -->
        <section class="ks-section-card">
          <div class="ks-section-header">
            <h2 class="ks-section-title">⚡ 긴급 처리 필요 예외 건 (Exception Driven Work Queue)</h2>
            <span class="ks-section-count">총 {{ exceptionItems.length }}건 처리 필요</span>
          </div>

          <div class="ks-table-container">
            <table class="ks-grid-table">
              <thead>
                <tr>
                  <th style="width: 40px;"><input type="checkbox" aria-label="전체 선택" /></th>
                  <th style="width: 120px;">예외ID</th>
                  <th style="width: 160px;">예외 유형</th>
                  <th>대상 모델</th>
                  <th style="width: 140px;">업무 모듈</th>
                  <th style="width: 100px;">상태</th>
                  <th style="width: 100px;">발생 시간</th>
                  <th style="width: 100px;">조치</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="ex in exceptionItems" :key="ex.id" class="ks-grid-row">
                  <td><input type="checkbox" :aria-label="`${ex.id} 선택`" /></td>
                  <td class="ks-financial-number">{{ ex.id }}</td>
                  <td>
                    <KsStatusTag :value="ex.type" :severity="ex.severity" />
                  </td>
                  <td class="ks-model-name"><strong>{{ ex.model }}</strong></td>
                  <td>{{ ex.module }}</td>
                  <td>
                    <KsStatusTag :value="ex.status" :severity="ex.severity" />
                  </td>
                  <td class="ks-financial-number">{{ ex.time }}</td>
                  <td>
                    <RouterLink :to="ex.route">
                      <KsButton label="조치하기 →" variant="secondary" size="xs" />
                    </RouterLink>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </section>

        <!-- System Operational Rules Grid -->
        <section class="ks-guide-grid">
          <div v-for="guide in operationalGuides" :key="guide.title" class="ks-guide-card">
            <h3 class="ks-guide-title">📌 {{ guide.title }}</h3>
            <p class="ks-guide-desc">{{ guide.desc }}</p>
          </div>
        </section>
      </div>
    </QueryStateBoundary>
  </PageLayout>
</template>

<style scoped>
.ks-home-body {
  display: flex;
  flex-direction: column;
  gap: var(--ks-space-4);
  flex: 1;
  min-height: 0;
  overflow-y: auto;
}

.ks-filter-group {
  display: flex;
  align-items: center;
  gap: var(--ks-space-4);
  width: 100%;
  flex-wrap: nowrap;
}

.ks-filter-btn {
  flex-shrink: 0;
}




.ks-metric-clickable {
  cursor: pointer;
  transition: border-color 0.15s ease, transform 0.15s ease;
}

.ks-metric-active {
  border-color: var(--ks-color-action);
  box-shadow: 0 0 0 1px var(--ks-color-action);
}

.ks-section-card {
  background: var(--ks-color-surface);
  border: 1px solid var(--ks-color-border);
  border-radius: var(--ks-radius-md);
  padding: var(--ks-space-4);
}

.ks-section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: var(--ks-space-3);
}

.ks-section-title {
  font-size: var(--ks-font-section);
  font-weight: 600;
  margin: 0;
  color: var(--ks-color-text);
}

.ks-section-count {
  font-size: var(--ks-font-caption);
  color: var(--ks-color-text-muted);
}

.ks-table-container {
  overflow-x: auto;
}

.ks-grid-table {
  width: 100%;
  border-collapse: collapse;
  font-size: var(--ks-font-grid);
}

.ks-grid-table th {
  height: var(--ks-grid-header-height, 36px);
  background: var(--ks-color-neutral-100);
  border-bottom: 2px solid var(--ks-color-border-strong);
  padding: 0 var(--ks-space-3);
  text-align: left;
  font-weight: 700;
  color: var(--ks-color-text);
}

.ks-grid-table td {
  height: var(--ks-grid-row-height, 36px);
  border-bottom: 1px solid var(--ks-color-border);
  padding: 0 var(--ks-space-3);
  color: var(--ks-color-text);
}

.ks-grid-row:hover {
  background: var(--ks-color-neutral-50);
}

.ks-guide-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: var(--ks-space-3);
}

.ks-guide-card {
  background: var(--ks-color-surface);
  border: 1px solid var(--ks-color-border);
  border-radius: var(--ks-radius-sm);
  padding: var(--ks-space-3);
}

.ks-guide-title {
  font-size: var(--ks-font-body);
  font-weight: 600;
  margin: 0 0 var(--ks-space-1) 0;
  color: var(--ks-color-text);
}

.ks-guide-desc {
  font-size: var(--ks-font-caption);
  color: var(--ks-color-text-muted);
  margin: 0;
  line-height: 1.4;
}
</style>
