<script setup lang="ts">
import { reactive, computed, ref, onMounted } from 'vue'
import MasterDetailCrudPage from '../../../shared/ui/screen-types/v2/MasterDetailCrudPage.vue'
import { KsButton, KsStatusTag } from '../../../shared/ui/components'
import type { StandardScreenState } from '../../../shared/ui/contracts/screenContract'

// KBX T05 Governance Audit & Maker-Checker State
const screenState = ref<StandardScreenState>('READY')
const evidence = reactive({
  asOf: '2026-08-15T19:39:00Z',
  version: 'v60-T05-Contract',
})

// Mock Approval Requests Data
const mockRequests = [
  {
    requestId: 'APR-2026-001',
    modelId: '1',
    modelName: 'Hawkeye-Alpha v2.1',
    action: 'activate',
    metadata: { pbo: 15.2, dsr: 96.5, oos: 1.8 },
    status: 'pending',
    requesterName: 'kjh2064',
    requestedAt: '2026-08-14T10:30:00Z',
  },
  {
    requestId: 'APR-2026-002',
    modelId: '2',
    modelName: 'Falcon-Beta v1.8',
    action: 'transition-phase',
    metadata: { currentPhase: 'Review', targetPhase: 'Manual Activation', pbo: 18.3, dsr: 94.2, oos: 2.1 },
    status: 'approved',
    requesterName: 'kjh2064',
    requestedAt: '2026-08-12T14:22:00Z',
    reviewerName: 'admin',
    reviewedAt: '2026-08-13T09:15:00Z',
    reviewComment: 'Metrics acceptable for transition. Approved.',
  },
]

const requests = ref(mockRequests)
const selectedRequestId = ref(mockRequests[0].requestId)
const reviewComment = ref('')

const statusStats = computed(() => ({
  pending: requests.value.filter(r => r.status === 'pending').length,
  approved: requests.value.filter(r => r.status === 'approved').length,
  rejected: requests.value.filter(r => r.status === 'rejected').length,
}))

onMounted(() => {
  screenState.value = 'LOADING'
  setTimeout(() => {
    screenState.value = 'READY'
  }, 500)
})

const filterModel = reactive({
  status: 'pending',
  action: '',
})

const filteredRequests = computed(() => {
  return requests.value.filter(r => {
    const statusMatch = !filterModel.status || r.status === filterModel.status
    const actionMatch = !filterModel.action || r.action === filterModel.action
    return statusMatch && actionMatch
  })
})

const selectedRequest = computed(() =>
  requests.value.find(r => r.requestId === selectedRequestId.value)
)

const selectRequest = (id: string) => {
  selectedRequestId.value = id
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString('ko-KR', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}

const getActionLabel = (action: string) => {
  const labels: Record<string, string> = {
    'activate': 'Model Activation',
    'retire': 'Model Retirement',
    'transition-phase': 'Phase Transition',
  }
  return labels[action] || action
}

const canApprove = computed(() => selectedRequest.value?.status === 'pending')
const canReject = computed(() => selectedRequest.value?.status === 'pending')

const handleApprove = () => {
  if (!selectedRequest.value) return
  selectedRequest.value.status = 'approved'
  selectedRequest.value.reviewerName = 'kjh2064'
  selectedRequest.value.reviewedAt = new Date().toISOString()
  selectedRequest.value.reviewComment = reviewComment.value || 'Maker-Checker 규칙에 따라 승인됨'
  reviewComment.value = ''
}

const handleReject = () => {
  if (!selectedRequest.value) return
  selectedRequest.value.status = 'rejected'
  selectedRequest.value.reviewerName = 'kjh2064'
  selectedRequest.value.reviewedAt = new Date().toISOString()
  selectedRequest.value.reviewComment = reviewComment.value || '검증 기준 미달로 반려됨'
  reviewComment.value = ''
}

const handleRetry = () => {
  screenState.value = 'LOADING'
  setTimeout(() => {
    screenState.value = 'READY'
  }, 400)
}
</script>

<template>
  <MasterDetailCrudPage
    title="Approval Queue (Maker-Checker Governance)"
    subtitle="모델 승격, 정책 변경 및 예외 조치 요청에 대한 Maker-Checker 거버넌스 승인을 수행합니다."
    :state="screenState"
    :evidence="evidence"
    storageKey="ks_splitter_ratio_approval_queue"
    @retry="handleRetry"
  >
    <!-- Summary Stats -->
    <template #actions>
      <div class="stats">
        <div class="stat stat-pending">
          <span class="label">Pending</span>
          <span class="value ks-financial-number">{{ statusStats.pending }}</span>
        </div>
        <div class="stat stat-approved">
          <span class="label">Approved</span>
          <span class="value ks-financial-number">{{ statusStats.approved }}</span>
        </div>
        <div class="stat stat-rejected">
          <span class="label">Rejected</span>
          <span class="value ks-financial-number">{{ statusStats.rejected }}</span>
        </div>
      </div>
    </template>

    <!-- Filters -->
    <template #filters>
      <div class="filters">
        <select v-model="filterModel.status" class="input" aria-label="승인 상태 필터">
          <option value="pending">Pending</option>
          <option value="approved">Approved</option>
          <option value="rejected">Rejected</option>
          <option value="">All</option>
        </select>
        <select v-model="filterModel.action" class="input" aria-label="작업 유형 필터">
          <option value="">All Actions</option>
          <option value="activate">Activate Model</option>
          <option value="transition-phase">Phase Transition</option>
          <option value="retire">Retire Model</option>
        </select>
      </div>
    </template>

    <!-- Master List -->
    <template #master>
      <aside class="request-list" aria-label="승인 요청 목록">
        <h2>Requests ({{ filteredRequests.length }})</h2>
        <div class="items" role="list">
          <div
            v-for="req in filteredRequests"
            :key="req.requestId"
            class="request-item"
            :class="{ 'is-selected': selectedRequestId === req.requestId }"
            @click="selectRequest(req.requestId)"
            role="listitem"
            :aria-selected="selectedRequestId === req.requestId"
          >
            <div class="item-header">
              <strong>{{ req.modelName }}</strong>
              <KsStatusTag
                :value="req.status.toUpperCase()"
                :severity="req.status === 'approved' ? 'success' : req.status === 'rejected' ? 'danger' : 'warning'"
              />
            </div>
            <div class="item-action">{{ getActionLabel(req.action) }}</div>
            <div class="item-meta">
              <span>{{ req.requesterName }}</span>
              <span class="ks-financial-number">{{ formatDate(req.requestedAt) }}</span>
            </div>
          </div>
        </div>
      </aside>
    </template>

    <!-- Detail Panel (EditForm Pattern) -->
    <template #detail>
      <form v-if="selectedRequest" class="approval-form" @submit.prevent="handleApprove">
        <!-- Header: Read-only Title -->
        <div class="form-header">
          <h2>{{ selectedRequest.modelName }}</h2>
          <small class="form-meta">{{ getActionLabel(selectedRequest.action) }}</small>
        </div>

        <!-- Content: Read-only Info + Form Input -->
        <div class="form-content">
          <!-- Request Details (read-only) -->
          <fieldset class="form-section" disabled>
            <legend>Request Details</legend>
            <div class="detail-grid">
              <div class="detail-item">
                <span class="label">Request ID</span>
                <span class="value ks-financial-number">{{ selectedRequest.requestId }}</span>
              </div>
              <div class="detail-item">
                <span class="label">Action</span>
                <span class="value">{{ getActionLabel(selectedRequest.action) }}</span>
              </div>
              <div class="detail-item">
                <span class="label">Requested By</span>
                <span class="value">{{ selectedRequest.requesterName }}</span>
              </div>
              <div class="detail-item">
                <span class="label">Requested At</span>
                <span class="value ks-financial-number">{{ formatDate(selectedRequest.requestedAt) }}</span>
              </div>
            </div>
          </fieldset>

          <!-- Validation Metrics (read-only) -->
          <fieldset v-if="selectedRequest.metadata.pbo" class="form-section" disabled>
            <legend>Validation Metrics</legend>
            <div class="metric-grid">
              <div class="metric-card">
                <div class="metric-label">PBO</div>
                <div class="metric-value ks-financial-number">{{ selectedRequest.metadata.pbo?.toFixed(2) }}%</div>
              </div>
              <div class="metric-card">
                <div class="metric-label">DSR</div>
                <div class="metric-value ks-financial-number">{{ selectedRequest.metadata.dsr?.toFixed(2) }}%</div>
              </div>
              <div class="metric-card">
                <div class="metric-label">OOS</div>
                <div class="metric-value ks-financial-number">{{ selectedRequest.metadata.oos?.toFixed(2) }}%</div>
              </div>
            </div>
          </fieldset>

          <!-- Review Comment (form input) -->
          <fieldset v-if="canApprove || canReject" class="form-section">
            <legend>Review & Approval Comment</legend>
            <textarea
              v-model="reviewComment"
              placeholder="Enter your review comment for audit trail..."
              class="form-textarea"
              aria-label="승인 심사 의견"
              required
            ></textarea>
          </fieldset>

          <!-- Review History (read-only) -->
          <fieldset v-if="selectedRequest.reviewedAt" class="form-section" disabled>
            <legend>Review History</legend>
            <div class="history-item">
              <div class="history-header">
                <strong>{{ selectedRequest.reviewerName }}</strong>
                <KsStatusTag
                  :value="selectedRequest.status.toUpperCase()"
                  :severity="selectedRequest.status === 'approved' ? 'success' : 'danger'"
                />
              </div>
              <div class="history-date ks-financial-number">{{ formatDate(selectedRequest.reviewedAt) }}</div>
              <div v-if="selectedRequest.reviewComment" class="history-comment">
                {{ selectedRequest.reviewComment }}
              </div>
            </div>
          </fieldset>
        </div>

        <!-- Footer: Action Buttons -->
        <div v-if="canApprove || canReject" class="form-footer">
          <KsButton
            label="Approve [승인]"
            variant="primary"
            :disabled="!canApprove || !reviewComment.trim()"
            type="submit"
          />
          <KsButton
            label="Reject [반려]"
            variant="secondary"
            :disabled="!canReject || !reviewComment.trim()"
            @click.prevent="handleReject"
          />
        </div>
      </form>

      <!-- Empty State -->
      <div v-else class="empty-state">
        <p>Select a request from list to review and approve</p>
      </div>
    </template>
  </MasterDetailCrudPage>
</template>


<style scoped>
.approval-queue {
  padding: var(--spacing-5);
  max-width: 1400px;
  margin: 0 auto;
}

.content-skeleton {
  display: grid;
  grid-template-columns: 350px 1fr;
  gap: var(--spacing-5);
}

.error-actions {
  text-align: center;
  padding: var(--spacing-4);
}

h1 {
  margin-bottom: var(--spacing-5);
  font-size: var(--font-size-3xl);
  font-weight: var(--font-weight-bold);
  color: var(--color-text-primary);
}

h2 {
  margin: 0;
  font-size: var(--font-size-xl);
  font-weight: var(--font-weight-semibold);
  color: var(--color-text-primary);
}

h3 {
  margin: 0;
  font-size: var(--font-size-sm);
  font-weight: var(--font-weight-semibold);
  color: var(--color-text-primary);
  padding-bottom: 6px;
  border-bottom: var(--border-width-1) solid var(--color-border-secondary);
}

.stats {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: var(--spacing-4);
  margin-bottom: var(--spacing-5);
}

.stat {
  padding: var(--spacing-4);
  background: var(--color-background-secondary);
  border-radius: var(--border-radius-lg);
  border-left: var(--border-width-2) solid var(--color-border-secondary);
  transition: all var(--transition-base);
}

.stat:hover {
  box-shadow: var(--shadow-sm);
}

.stat-pending {
  border-left-color: var(--color-warning-500);
}

.stat-approved {
  border-left-color: var(--color-success-500);
}

.stat-rejected {
  border-left-color: var(--color-danger-500);
}

.stat .label {
  display: block;
  font-size: var(--font-size-xs);
  color: var(--color-text-tertiary);
  margin-bottom: var(--spacing-2);
  font-weight: var(--font-weight-medium);
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.stat .value {
  display: block;
  font-size: var(--font-size-3xl);
  font-weight: var(--font-weight-bold);
  color: var(--color-text-primary);
}

.filters {
  display: flex;
  align-items: center;
  gap: var(--ks-space-3);
  width: 100%;
}

.input:focus, .textarea:focus {
  outline: none;
  border-color: var(--ks-color-action);
  box-shadow: 0 0 0 2px var(--ks-color-action);
}

.loading {
  padding: var(--spacing-5);
  text-align: center;
  color: var(--color-text-tertiary);
  border-radius: var(--border-radius-lg);
}

.request-list {
  border: var(--border-width-1) solid var(--color-border-primary);
  border-radius: var(--border-radius-lg);
  overflow: hidden;
  background: var(--color-background-primary);
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
}

.request-list h2 {
  padding: var(--spacing-4);
  background: var(--color-background-secondary);
  border-bottom: var(--border-width-1) solid var(--color-border-secondary);
  margin: 0;
  flex-shrink: 0;
}

.items {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-1);
  padding: var(--spacing-2);
  flex: 1;
  min-height: 0;
  overflow-y: auto;
}

.request-item {
  padding: var(--spacing-3);
  background: var(--color-background-primary);
  border: var(--border-width-1) solid var(--color-border-secondary);
  border-radius: var(--border-radius-base);
  cursor: pointer;
  transition: all var(--transition-base);
}

.request-item:hover {
  background: var(--color-background-hover);
  box-shadow: var(--shadow-sm);
}

.request-item.is-selected {
  border-color: var(--color-primary-500);
  background: var(--color-primary-50);
  box-shadow: var(--shadow-sm);
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-2);
  gap: var(--spacing-2);
  font-size: var(--font-size-sm);
}

.item-header strong {
  flex: 1;
  color: var(--color-text-primary);
}

.status-badge {
  padding: var(--spacing-1) var(--spacing-2);
  border-radius: var(--border-radius-base);
  font-size: var(--font-size-xs);
  font-weight: var(--font-weight-bold);
  color: white;
  white-space: nowrap;
}

.item-action {
  font-size: var(--font-size-xs);
  color: var(--color-text-tertiary);
  margin-bottom: var(--spacing-2);
}

.item-meta {
  display: flex;
  justify-content: space-between;
  font-size: var(--font-size-xs);
  color: var(--color-text-tertiary);
}

/* Approval Form (EditForm Pattern) */
.approval-form {
  border: var(--border-width-1) solid var(--color-border-primary);
  border-radius: var(--border-radius-lg);
  background: var(--color-background-secondary);
  height: 100%;
  min-height: 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.form-header {
  padding: var(--spacing-3);
  border-bottom: var(--border-width-1) solid var(--color-border-secondary);
  flex-shrink: 0;
}

.form-header h2 {
  margin: 0 0 4px 0;
  font-size: var(--font-size-lg);
  font-weight: var(--font-weight-semibold);
  color: var(--color-text-primary);
}

.form-meta {
  font-size: var(--font-size-xs);
  color: var(--color-text-tertiary);
}

.form-content {
  flex: 1;
  min-height: 0;
  overflow-y: auto;
  padding: var(--spacing-3);
  display: flex;
  flex-direction: column;
  gap: var(--spacing-3);
}

.form-section {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-2);
  border: none;
  padding: 0;
  margin: 0;
}

.form-section:disabled {
  opacity: 1;
}

.form-section legend {
  padding: 0 0 6px 0;
  margin: 0;
  font-size: var(--font-size-sm);
  font-weight: var(--font-weight-semibold);
  color: var(--color-text-primary);
  border-bottom: var(--border-width-1) solid var(--color-border-secondary);
}

.form-textarea {
  width: 100%;
  padding: var(--spacing-2) var(--spacing-3);
  border: var(--border-width-1) solid var(--color-input-border);
  border-radius: var(--border-radius-base);
  background: var(--color-input-background);
  color: var(--color-text-primary);
  font-size: var(--font-size-sm);
  font-family: var(--font-sans);
  resize: vertical;
  min-height: 60px;
  max-height: 80px;
  transition: all var(--transition-fast);
}

.form-textarea:focus {
  outline: none;
  border-color: var(--ks-color-action);
  box-shadow: 0 0 0 2px var(--ks-color-action);
}

.form-footer {
  display: flex;
  gap: var(--spacing-2);
  padding: var(--spacing-3);
  border-top: var(--border-width-1) solid var(--color-border-secondary);
  flex-shrink: 0;
  background: var(--color-background-primary);
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: var(--spacing-8);
  text-align: center;
  color: var(--color-text-tertiary);
}

.section {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-2);
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: var(--spacing-2);
}

.detail-item {
  display: flex;
  flex-direction: column;
  gap: 2px;
  padding: var(--spacing-2) var(--spacing-3);
  background: var(--color-background-primary);
  border-radius: var(--border-radius-base);
  border: var(--border-width-1) solid var(--color-border-secondary);
}

.detail-item .label {
  font-size: var(--font-size-xs);
  color: var(--color-text-tertiary);
  font-weight: var(--font-weight-medium);
}

.detail-item .value {
  font-size: var(--font-size-sm);
  color: var(--color-text-primary);
  font-weight: var(--font-weight-semibold);
}

.metric-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: var(--spacing-2);
}

.metric-card {
  padding: var(--spacing-2) var(--spacing-2);
  background: var(--color-background-primary);
  border: var(--border-width-1) solid var(--color-border-secondary);
  border-radius: var(--border-radius-base);
  text-align: center;
}

.metric-label {
  font-size: 11px;
  color: var(--color-text-tertiary);
  font-weight: var(--font-weight-medium);
  margin-bottom: 4px;
}

.metric-value {
  font-size: var(--font-size-base);
  font-weight: var(--font-weight-bold);
  color: var(--color-primary-600);
}

.textarea {
  width: 100%;
  padding: var(--spacing-2) var(--spacing-3);
  border: var(--border-width-1) solid var(--color-input-border);
  border-radius: var(--border-radius-base);
  background: var(--color-input-background);
  color: var(--color-text-primary);
  font-size: var(--font-size-sm);
  font-family: var(--font-sans);
  resize: vertical;
  min-height: 60px;
  max-height: 80px;
  transition: all var(--transition-fast);
}

.textarea:focus {
  outline: none;
  border-color: var(--ks-color-action);
  box-shadow: 0 0 0 2px var(--ks-color-action);
}

.actions {
  display: flex;
  gap: var(--spacing-2);
}

.btn {
  flex: 1;
  padding: var(--spacing-2) var(--spacing-3);
  border: var(--border-width-1) solid var(--color-border-primary);
  border-radius: var(--border-radius-base);
  background: var(--color-background-primary);
  color: var(--color-text-primary);
  cursor: pointer;
  font-size: var(--font-size-sm);
  font-weight: var(--font-weight-medium);
  transition: all var(--transition-fast);
  font-family: var(--font-sans);
}

.btn:hover:not(:disabled) {
  background: var(--color-background-hover);
  border-color: var(--color-border-secondary);
}

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

.btn-primary {
  background: var(--color-primary-500);
  color: white;
  border-color: var(--color-primary-500);
}

.btn-primary:hover:not(:disabled) {
  background: var(--color-primary-600);
  border-color: var(--color-primary-600);
}

.btn-danger {
  background: var(--color-danger-50);
  color: var(--color-danger-700);
  border-color: var(--color-danger-200);
}

.btn-danger:hover:not(:disabled) {
  background: var(--color-danger-100);
  border-color: var(--color-danger-300);
}

.history {
  padding: var(--spacing-2) var(--spacing-3);
  background: var(--color-background-primary);
  border: var(--border-width-1) solid var(--color-border-secondary);
  border-radius: var(--border-radius-base);
}

.history-item {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-2);
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: var(--font-size-sm);
  color: var(--color-text-primary);
}

.history-date {
  font-size: var(--font-size-xs);
  color: var(--color-text-tertiary);
}

.history-comment {
  padding: var(--spacing-2) var(--spacing-3);
  background: var(--color-background-secondary);
  border-left: var(--border-width-2) solid var(--color-primary-500);
  border-radius: var(--border-radius-base);
  font-size: var(--font-size-sm);
  color: var(--color-text-primary);
  font-style: italic;
}

@media (max-width: 1000px) {
  .content {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .stats {
    grid-template-columns: 1fr;
  }

  .filters {
    grid-template-columns: 1fr;
  }

  .detail-grid {
    grid-template-columns: 1fr;
  }

  .metric-grid {
    grid-template-columns: 1fr;
  }
}
</style>
