<script setup lang="ts">
import { computed } from 'vue'
import {
  KbxBarcodeCapture,
  KbxWmsActionButton,
  KbxWmsMobilePage,
} from '@kbx/ui'
import PickingExceptionSheet from './PickingExceptionSheet.vue'
import PickingQuantitySheet from './PickingQuantitySheet.vue'
import { useWmsPicking } from './useWmsPicking'
import { pickingScreen } from './picking.definition'

const props = defineProps<{ taskId: string }>()
const vm = useWmsPicking(props.taskId)

const progress = computed(() => vm.task.value
  ? `${vm.task.value.completedLines} / ${vm.task.value.totalLines}`
  : undefined)

const current = computed(() => vm.task.value?.currentLine ?? null)
const taskContext = computed(() => vm.task.value
  ? `${vm.task.value.taskNo} · ${vm.task.value.completedLines}/${vm.task.value.totalLines} 라인 · 총 ${vm.task.value.totalQty}개`
  : undefined)
const stageTitle = computed(() => {
  switch (vm.task.value?.stage) {
    case 'ready': return '작업을 시작하세요.'
    case 'await-location': return '작업 위치를 확인하고 스캔하세요.'
    case 'await-item': return '표시된 상품을 스캔하세요.'
    case 'processing': return '스캔 결과를 서버에서 확인하고 있습니다.'
    case 'completed': return '피킹을 완료했습니다.'
    case 'blocked': return '관리자 확인이 필요합니다.'
    default: return '작업을 불러오는 중입니다.'
  }
})
const noticeText = computed(() => {
  if (!vm.online.value && vm.pendingCommands.value > 0) return `오프라인입니다. 전송 대기 ${vm.pendingCommands.value}건은 연결되면 같은 작업키로 안전하게 재전송합니다.`
  if (!vm.online.value) return '오프라인입니다. 서버 확인이 필요한 스캔은 입력할 수 없습니다.'
  if (vm.syncing.value) return `전송 대기 ${vm.pendingCommands.value}건을 순서대로 동기화하고 있습니다.`
  return vm.message.value
})
const noticeTone = computed(() => {
  if (vm.task.value?.stage === 'blocked') return 'danger'
  if (!vm.online.value || vm.pendingCommands.value > 0) return 'warning'
  if (vm.task.value?.stage === 'completed') return 'success'
  return 'info'
})
const noticeLabel = computed(() => ({danger:'확인 필요',warning:'연결 상태',success:'완료',info:'작업 안내'}[noticeTone.value]))
const scanReadiness = computed(() => {
  if (!vm.online.value) return '입력 차단 · 온라인 확인 필요'
  if (vm.syncing.value || vm.pendingCommands.value > 0) return `재전송 확인 중 · ${vm.pendingCommands.value}건 대기`
  if (vm.scanning.value || vm.task.value?.stage === 'processing') return '서버 확인 중 · 중복 스캔 금지'
  if (vm.task.value && ['await-location','await-item'].includes(vm.task.value.stage)) return '스캔 가능'
  if (vm.task.value?.stage === 'completed') return '작업 완료'
  if (vm.task.value?.stage === 'blocked') return '입력 차단 · 관리자 확인'
  return '스캔 대기'
})
const scanReadinessTone = computed(() => !vm.online.value || vm.task.value?.stage === 'blocked'
  ? 'danger'
  : vm.syncing.value || vm.pendingCommands.value > 0 || vm.scanning.value
    ? 'warning'
    : vm.task.value?.stage === 'completed'
      ? 'success'
      : 'ready')
const lastConfirmedText = computed(() => {
  const last = vm.lastConfirmedScan.value
  if (!last) return ''
  const time = new Date(last.confirmedAt).toLocaleTimeString('ko-KR', { hour:'2-digit', minute:'2-digit', second:'2-digit' })
  return `${last.barcode} · ${time}`
})
</script>

<template>
  <KbxWmsMobilePage
    :screen="pickingScreen"
    :progress="progress"
    :task-context="taskContext"
    :instruction="stageTitle"
    :online="vm.online.value"
    :pending-commands="vm.pendingCommands.value"
    :syncing="vm.syncing.value"
    :content-state="vm.contentState.value"
    retry-label="작업 다시 불러오기"
    @retry="vm.reload"
  >
    <template #notice>
      <div v-if="noticeText" class="work-notice" :data-tone="noticeTone" role="status" aria-live="polite">
        <strong>{{ noticeLabel }}</strong><span>{{ noticeText }}</span>
      </div>
    </template>

    <section v-if="vm.task.value" class="instruction" :data-stage="vm.task.value.stage">
      <template v-if="current">
        <div class="location" aria-label="현재 피킹 위치">
          <span>LOCATION</span>
          <strong>{{ current.locationCode }}</strong>
          <small v-if="vm.task.value.stage === 'await-location'">이 위치와 일치하는 라벨을 먼저 스캔하세요.</small>
        </div>

        <div class="item" aria-label="현재 피킹 상품">
          <span>상품</span>
          <strong>{{ current.itemName }}</strong>
          <small>{{ current.itemCode }}<template v-if="current.itemOption"> · {{ current.itemOption }}</template></small>
          <small>바코드 {{ current.barcode }}</small>
        </div>

        <div class="qty" aria-label="피킹 수량">
          <div><span>필요</span><strong>{{ current.requiredQty }}</strong></div>
          <div><span>피킹</span><strong>{{ current.pickedQty }}</strong></div>
          <div><span>남음</span><strong>{{ current.remainingQty }}</strong></div>
        </div>

        <p class="next-action">
          <template v-if="vm.task.value.stage === 'await-location'">다음 행동 · 위치 {{ current.locationCode }} 스캔</template>
          <template v-else-if="vm.task.value.stage === 'await-item'">다음 행동 · 상품 {{ current.itemCode }} 스캔</template>
          <template v-else-if="vm.task.value.stage === 'processing'">중복 스캔하지 말고 서버 확인을 기다리세요.</template>
        </p>
      </template>

      <KbxWmsActionButton
        v-if="current && vm.task.value.stage === 'await-item' && current.pickedQty > 0 && current.remainingQty > 0"
        class="quantity-action"
        label="수량 직접 입력"
        variant="secondary"
        :disabled="!vm.online.value || vm.pendingCommands.value > 0 || vm.scanning.value"
        @click="vm.openQuantity"
      />

      <div v-else-if="vm.task.value.stage === 'ready'" class="ready">
        <strong>{{ vm.task.value.taskNo }}</strong>
        <span>총 {{ vm.task.value.totalLines }}개 라인 · {{ vm.task.value.totalQty }}개</span>
        <small>작업 시작 후 위치 → 상품 순서로 스캔합니다.</small>
      </div>
    </section>

    <section v-if="vm.task.value && vm.task.value.stage !== 'ready'" class="scan-truth" :data-tone="scanReadinessTone" aria-live="polite" data-kbx-surface="scan-truth">
      <div><span>스캔 상태</span><strong>{{ scanReadiness }}</strong></div>
      <div v-if="lastConfirmedText"><span>최근 서버 확인</span><strong>{{ lastConfirmedText }}</strong></div>
      <div v-else><span>최근 서버 확인</span><strong>아직 확인된 스캔 없음</strong></div>
    </section>

    <KbxBarcodeCapture
      v-if="vm.task.value && !['ready','completed','blocked'].includes(vm.task.value.stage)"
      :enabled="vm.scanEnabled.value"
      :label="vm.scanLabel.value"
      @scan="vm.handleScan"
    />

    <template #actions>
      <KbxWmsActionButton
        v-if="vm.task.value?.stage === 'ready'"
        label="작업 시작"
        :busy="vm.starting.value"
        :disabled="!vm.online.value"
        @click="vm.start"
      />

      <KbxWmsActionButton
        v-else-if="vm.task.value && ['await-location','await-item'].includes(vm.task.value.stage)"
        label="문제 신고"
        variant="secondary"
        :disabled="!vm.online.value || vm.pendingCommands.value > 0"
        @click="vm.openException"
      />

      <KbxWmsActionButton
        v-else-if="vm.task.value?.stage === 'completed'"
        label="작업 목록으로"
        @click="$router.push('/wms/picking')"
      />
    </template>
  </KbxWmsMobilePage>

  <PickingQuantitySheet
    v-if="vm.quantityOpen.value && current"
    :current="current.pickedQty"
    :required="current.requiredQty"
    :busy="vm.settingQuantity.value"
    @close="vm.closeQuantity"
    @submit="vm.setQuantity"
  />

  <PickingExceptionSheet
    v-if="vm.exceptionOpen.value"
    :busy="vm.reportingException.value"
    @close="vm.closeException"
    @submit="(type, memo) => vm.reportException(type, memo)"
  />
</template>

<style scoped>
.work-notice{display:grid;grid-template-columns:auto minmax(0,1fr);align-items:start;gap:var(--kbx-space-2);padding:var(--kbx-space-2) var(--kbx-space-3);border:var(--kbx-border-width) solid var(--kbx-color-info-border);border-radius:var(--kbx-radius-md);background:var(--kbx-color-info-surface);font-size:var(--kbx-font-sm)}
.work-notice strong{white-space:nowrap}.work-notice[data-tone="warning"]{border-color:var(--kbx-color-warning-border);background:var(--kbx-color-warning-surface)}.work-notice[data-tone="danger"]{border-color:var(--kbx-color-danger-border);background:var(--kbx-color-danger-surface)}.work-notice[data-tone="success"]{border-color:var(--kbx-color-success-border);background:var(--kbx-color-success-surface)}
.instruction{text-align:center}.location{padding:var(--kbx-space-4);background:var(--kbx-color-surface-muted);border:var(--kbx-border-width) solid var(--kbx-color-border);border-radius:var(--kbx-radius-lg)}
.location span,.item span{display:block;color:var(--kbx-color-text-muted);font-size:var(--kbx-font-xs);font-weight:600}.location strong{display:block;margin-top:var(--kbx-space-1);font-size:calc(var(--kbx-font-2xl) + var(--kbx-space-3));letter-spacing:.03em}.location small{display:block;margin-top:var(--kbx-space-2);color:var(--kbx-color-text-muted);font-size:var(--kbx-font-xs)}
.item{padding:var(--kbx-space-5) var(--kbx-space-1) var(--kbx-space-2)}.item strong{display:block;margin-top:var(--kbx-space-1);font-size:calc(var(--kbx-font-xl) + var(--kbx-space-1))}.item small{display:block;margin-top:var(--kbx-space-1);color:var(--kbx-color-text-muted);font-size:var(--kbx-font-sm)}
.qty{display:grid;grid-template-columns:repeat(3,1fr);gap:var(--kbx-space-2);margin-top:var(--kbx-space-3)}.qty div{border:var(--kbx-border-width) solid var(--kbx-color-border);border-radius:var(--kbx-radius-lg);padding:var(--kbx-space-3) var(--kbx-space-1)}.qty span{display:block;font-size:var(--kbx-font-sm);color:var(--kbx-color-text-muted)}.qty strong{display:block;margin-top:var(--kbx-space-1);font-size:calc(var(--kbx-font-2xl) + var(--kbx-space-2))}
.next-action{margin:var(--kbx-space-3) 0 0;padding:var(--kbx-space-2);border-top:var(--kbx-border-width) solid var(--kbx-color-border);color:var(--kbx-color-text-muted);font-size:var(--kbx-font-sm);font-weight:600}.quantity-action{margin-top:var(--kbx-space-3)}.ready{min-height:calc(var(--kbx-control-touch) * 5);display:flex;flex-direction:column;justify-content:center;gap:var(--kbx-space-2)}.ready strong{font-size:calc(var(--kbx-font-2xl) + var(--kbx-space-2))}.ready span,.ready small{color:var(--kbx-color-text-muted)}
.scan-truth{display:grid;gap:var(--kbx-space-2);margin:0 0 var(--kbx-space-3);padding:var(--kbx-space-2) var(--kbx-space-3);border:var(--kbx-border-width) solid var(--kbx-color-border);border-left:var(--kbx-accent-border-width) solid var(--kbx-color-success-border);background:var(--kbx-color-surface-muted);font-size:var(--kbx-font-xs)}.scan-truth>div{display:grid;grid-template-columns:minmax(0,auto) minmax(0,1fr);gap:var(--kbx-space-2);align-items:start}.scan-truth span{color:var(--kbx-color-text-muted)}.scan-truth strong{text-align:right;overflow-wrap:anywhere}.scan-truth[data-tone="warning"]{border-left-color:var(--kbx-color-warning-border);background:var(--kbx-color-warning-surface)}.scan-truth[data-tone="danger"]{border-left-color:var(--kbx-color-danger-border);background:var(--kbx-color-danger-surface)}
@media(forced-colors:active){.scan-truth{border-color:CanvasText}.scan-truth[data-tone="warning"],.scan-truth[data-tone="danger"]{border-left-color:Highlight}}
</style>
