<script setup lang="ts">
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import {
  KbxDataGrid,
  KbxListPage,
  KbxQuickFilterBar,
  KbxSearchPanel,
  KbxSummaryBar,
  useKbxPageShortcuts,
} from '@kbx/ui'
import { orderColumns, orderListScreen, orderSearchFields, type OrderSearchRow } from './order-list.definition'
import { orderApi, type OrderDetailResponse } from './orderApi'
import { orderImportApi } from '../import/orderImportApi'
import OrderDetailDrawer from './OrderDetailDrawer.vue'
import { useOrderSearch } from './useOrderSearch'
import { useKbxExperiment } from '../../../../experiments/kbxExperimentClient'

const vm = useOrderSearch()
const router = useRouter()
const grid = ref<any>(null)
const detailOpen = ref(false)
const detailSummary = ref<OrderSearchRow | null>(null)
const detail = ref<OrderDetailResponse | null>(null)
const detailLoading = ref(false)
const detailError = ref('')
const pageNotice = ref('')
let detailSequence = 0

const exceptionSummaryExperiment = useKbxExperiment(
  orderListScreen.id,
  orderListScreen.version,
  'exp.oms.order-list.exception-summary-v2',
  'information-emphasis',
)

useKbxPageShortcuts([{ key:'F3', execute:vm.executeSearch }])

async function selectQuickFilter(key:string) {
  vm.search.exceptionOnly = false
  vm.search.status = null
  if (key === 'new') vm.search.status = 'NEW'
  if (key === 'ready') vm.search.status = 'READY'
  if (key === 'exceptions') vm.search.exceptionOnly = true
  await vm.executeSearch()
}

async function openDetail(row:OrderSearchRow) {
  const sequence = ++detailSequence
  detailSummary.value = row
  detail.value = null
  detailError.value = ''
  detailLoading.value = true
  detailOpen.value = true
  try {
    const result = await orderApi.getDetail(row.id)
    if (sequence === detailSequence) detail.value = result
  } catch {
    if (sequence === detailSequence) detailError.value = '네트워크 상태를 확인한 후 다시 시도하세요.'
  } finally {
    if (sequence === detailSequence) detailLoading.value = false
  }
}

function closeDetail() {
  detailSequence += 1
  detailOpen.value = false
  detailLoading.value = false
}

async function openFullDetail(orderId:string) {
  closeDetail()
  await router.push({ name:'oms-order-edit', params:{ orderId } })
}

async function executeCommand(id:string) {
  pageNotice.value = ''
  if (id === 'excel.export') {
    const total = vm.result.value?.totalCount ?? 0
    if (total > vm.rows.value.length) {
      pageNotice.value = `전체 ${total.toLocaleString('ko-KR')}건 중 현재 로드된 ${vm.rows.value.length.toLocaleString('ko-KR')}건만 있습니다. 누락 방지를 위해 전체 조회결과 Export API가 연결될 때까지 다운로드를 차단합니다.`
      return
    }
    grid.value?.exportCsv?.()
    pageNotice.value = `${total.toLocaleString('ko-KR')}건을 CSV로 다운로드했습니다.`
    return
  }
  if (id === 'excel.template') {
    await orderImportApi.downloadTemplate()
    return
  }
  if (id === 'excel.import') return router.push({ name:'oms-order-import' })
  if (id === 'excel.paste') return router.push({ name:'oms-order-import', query:{ source:'clipboard' } })
  if (id === 'excel.history') return router.push({ name:'oms-order-import', query:{ view:'history' } })
  await vm.executeCommand(id)
}

const quickFilters = computed(() => {
  const counters = vm.result.value?.counters
  if (!counters) return []
  return [
    { key:'all', label:'전체', count:counters.all, active:!vm.search.status && !vm.search.exceptionOnly },
    { key:'new', label:'신규', count:counters.new, active:vm.search.status === 'NEW' },
    { key:'ready', label:'출고대기', count:counters.readyToShip, active:vm.search.status === 'READY' },
    { key:'exceptions', label:'오류', count:counters.exceptions, active:vm.search.exceptionOnly, tone:'danger' as const },
  ]
})

const pageContext = computed(() => vm.result.value ? {
  label:`${vm.appliedSearch.value.from} ~ ${vm.appliedSearch.value.to}`,
  hint:vm.appliedSearch.value.exceptionOnly ? '예외 주문만 조회 중' : '현재 적용된 조회조건 기준',
  metrics:[
    { key:'result', label:'조회', value:vm.result.value.totalCount },
    { key:'selected', label:'선택', value:vm.selectionCount.value },
    { key:'exceptions', label:'오류', value:vm.result.value.counters.exceptions, tone:'danger' as const, emphasis:vm.result.value.counters.exceptions > 0 },
  ],
} : null)

const summaryItems = computed(() => vm.result.value ? [
  { key:'rows', label:'조회', value:`${vm.result.value.totalCount.toLocaleString('ko-KR')}건` },
  { key:'selected', label:'선택', value:`${vm.selectionCount.value.toLocaleString('ko-KR')}건` },
  { key:'qty', label:'수량', value:vm.result.value.totalQty },
  { key:'amount', label:'금액', value:`₩${vm.result.value.totalAmount.toLocaleString('ko-KR')}`, emphasis:true },
] : [])
</script>

<template>
  <KbxListPage
    :screen="orderListScreen"
    :selection-count="vm.selectionCount.value"
    :context="pageContext"
    :content-state="vm.error.value ? 'error' : vm.loading.value && !vm.result.value ? 'loading' : !vm.result.value ?'idle' : vm.result.value.totalCount === 0 ? 'empty' : 'ready'"
    :refreshing="vm.loading.value && Boolean(vm.result.value)"
    :problem="vm.problem.value"
    empty-action-label="조회조건 초기화"
    breadcrumb="OMS > 주문"
    @command="executeCommand"
    @empty-action="vm.resetAndSearch"
    @retry-problem="vm.retryProblem"
    @dismiss-problem="vm.dismissProblem"
  >
    <template #notice><div v-if="pageNotice || vm.preferenceNotice.value" class="page-notice" role="status">{{pageNotice || vm.preferenceNotice.value}}</div></template>
    <template #search>
      <KbxSearchPanel
        :model-value="vm.search"
        :fields="orderSearchFields"
        remember
        saved-search
        :remember-checked="vm.rememberSearch.value"
        @update:model-value="value => Object.assign(vm.search, value)"
        @update:remember-checked="vm.setRememberSearch"
        @saved-search-requested="vm.saveCurrentSearchDefaults"
        @search="vm.executeSearch"
      />
    </template>

    <template #quick-filter>
      <div v-if="vm.result.value && exceptionSummaryExperiment.is('exception-summary')" class="experiment-summary">
        <strong>확인 필요</strong> · 오류 {{vm.result.value.counters.exceptions.toLocaleString()}}건 — 기존 조회·처리 문법은 그대로 유지됩니다.
      </div>
      <KbxQuickFilterBar v-if="quickFilters.length" :items="quickFilters" @select="selectQuickFilter" />
    </template>

    <template #content>
      <KbxDataGrid
        ref="grid"
        :rows="vm.rows.value"
        :columns="orderColumns"
        row-key="id"
        aria-label="주문 조회 결과"
        selection="multiple"
        :loading="vm.loading.value"
        :total-count="vm.result.value?.totalCount ?? 0"
        :selection-state="vm.selectionState.value"
        allow-all-filtered-selection
        export-file-name="orders-current-page.csv"
        @selection-state-changed="value => vm.selectionState.value = value"
        @drill-down-requested="openDetail"
        @row-double-clicked="openDetail"
      />
    </template>

    <template #summary>
      <KbxSummaryBar v-if="summaryItems.length" :items="summaryItems" />
    </template>

    <template #detail>
      <OrderDetailDrawer
        :open="detailOpen"
        :summary="detailSummary"
        :detail="detail"
        :loading="detailLoading"
        :error="detailError"
        @update:open="value => value ? detailOpen = true : closeDetail()"
        @retry="detailSummary && openDetail(detailSummary)"
        @full-detail="openFullDetail"
      />
    </template>
  </KbxListPage>
</template>

<style scoped>
.page-notice{padding:var(--kbx-space-2) var(--kbx-space-3);border:var(--kbx-border-width) solid var(--kbx-color-warning-border);background:var(--kbx-color-warning-surface);font-size:var(--kbx-font-sm)}
.experiment-summary {
  margin-bottom:var(--kbx-space-1);
  padding:var(--kbx-space-2);
  border:var(--kbx-border-width) solid var(--kbx-color-border);
  background:var(--kbx-color-surface-muted);
}
</style>
