<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { isKbxProblem } from '@kbx/contracts'
import { KbxButton, KbxDataGrid, KbxQueuePage, KbxSearchPanel } from '@kbx/ui'
import { routeForWmsTask, searchWmsWork, type WmsWorkSearchSummary } from './workApi'
import { wmsWorkColumns, wmsWorkScreen, wmsWorkSearchFields, type WmsWorkRow } from './work.definition'

const router=useRouter()
const search=ref({taskType:'',status:'',owner:'mine',keyword:''})
const rows=ref<WmsWorkRow[]>([])
const selection=ref<WmsWorkRow[]>([])
const summary=ref<WmsWorkSearchSummary>({totalCount:0,readyCount:0,inProgressCount:0,blockedCount:0})
const resultCount=ref(0)
const loading=ref(false)
const searched=ref(false)
const error=ref<unknown>(null)
const activeExceptionKey=ref<string|null>(null)

const queryProblem=computed(()=>isKbxProblem(error.value)?error.value:null)
const contentState=computed(()=>error.value?'error':loading.value&&!searched.value?'loading':!searched.value?'idle':rows.value.length===0?'empty':'ready')
const selectedTask=computed(()=>selection.value.length===1?selection.value[0]:null)
const canOpenTask=computed(()=>Boolean(selectedTask.value))
const selectedTaskActionLabel=computed(()=>selectedTask.value?.status==='IN_PROGRESS'?'선택 작업 계속':'선택 작업 시작')
const selectedBlocked=computed(()=>selectedTask.value?.status==='BLOCKED')

async function executeSearch(){
  loading.value=true;error.value=null;selection.value=[]
  try{
    const result=await searchWmsWork(search.value)
    rows.value=result.items;resultCount.value=result.totalCount;summary.value=result.summary;searched.value=true
  }catch(cause){error.value=cause;searched.value=true}
  finally{loading.value=false}
}
function executeCommand(id:string){
  if(id==='search')return executeSearch()
  if(id==='start'&&selectedTask.value&&!selectedBlocked.value)return router.push(routeForWmsTask(selectedTask.value))
}
const summaryItems=computed(()=>[
  {key:'total',label:'업무 대상',value:summary.value.totalCount},
  {key:'ready',label:'대기',value:summary.value.readyCount},
  {key:'progress',label:'진행',value:summary.value.inProgressCount},
  {key:'blocked',label:'예외',value:summary.value.blockedCount,emphasis:summary.value.blockedCount>0},
])
const exceptionCounters=computed(()=>summary.value.blockedCount>0?[{key:'blocked',label:'확인 필요한 작업',count:summary.value.blockedCount,severity:'warning' as const}]:[])
async function filterException(key:string|null){activeExceptionKey.value=key;search.value={...search.value,status:key==='blocked'?'BLOCKED':''};await executeSearch()}
async function resetSearch(){search.value={taskType:'',status:'',owner:'mine',keyword:''};activeExceptionKey.value=null;await executeSearch()}
onMounted(()=>void executeSearch())
</script>

<template>
  <KbxQueuePage
    :screen="wmsWorkScreen"
    :selection-count="selection.length"
    :content-state="contentState"
    :refreshing="loading&&searched&&!error"
    :summary-items="summaryItems"
    :exception-counters="exceptionCounters"
    :active-exception-key="activeExceptionKey"
    queue-title="현재 작업 Queue"
    queue-description="작업유형·작업자 기준 전체 업무를 먼저 보여주고, 상태 필터는 사용자가 좁혀 봅니다."
    :queue-count="resultCount"
    breadcrumb="WMS > 작업관리"
    empty-title="조건에 맞는 물류 작업이 없습니다."
    empty-detail="작업유형·상태·작업자 조건을 변경하거나 기본조건으로 다시 조회하세요."
    empty-action-label="기본조건으로 조회"
    :error-title="queryProblem?.title || '물류 작업을 조회하지 못했습니다.'"
    :error-detail="queryProblem?.detail || '네트워크 상태를 확인한 후 다시 조회하세요.'"
    :error-retryable="queryProblem?.retryable !== false"
    retry-label="다시 조회"
    @command="executeCommand"
    @exception-filter="filterException"
    @empty-action="resetSearch"
  >
    <template #search><KbxSearchPanel v-model="search" :fields="wmsWorkSearchFields" @search="executeSearch"/></template>
    <template #queue-actions>
      <div class="wms-work-actions">
        <span v-if="selectedBlocked" role="status">예외 작업은 행을 열어 원인을 먼저 확인하세요.</span>
        <KbxButton :label="selectedTaskActionLabel" variant="primary" :disabled="!canOpenTask||selectedBlocked" @click="executeCommand('start')"/>
      </div>
    </template>
    <template #content>
      <KbxDataGrid
        :rows="rows"
        :columns="wmsWorkColumns"
        row-key="taskId"
        selection="single"
        :loading="loading"
        @selection-changed="selection=$event"
        @row-double-clicked="row=>router.push(routeForWmsTask(row))"
      />
    </template>
  </KbxQueuePage>
</template>

<style scoped>
.wms-work-actions{display:flex;align-items:center;gap:var(--kbx-space-2)}
.wms-work-actions span{font-size:var(--kbx-font-xs);color:var(--kbx-color-warning-text)}
</style>
