<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { configApi } from '../../services/configApi'
import { useUiStore } from '../../stores/ui'
import type { StatusStage } from '../../types'

const ui = useUiStore()

const stages = ref<StatusStage[]>([])
const loading = ref(false)

// Form
const docType = ref('sales_order')
const sourceSystem = ref('sap_ecc')
const newStageKey = ref('')
const newStageLabel = ref('')
const saving = ref(false)

const DOC_TYPES = [
  { value: 'sales_order', label: 'Sales Order' },
  { value: 'purchase_order', label: 'Purchase Order' },
  { value: 'delivery', label: 'Delivery' },
  { value: 'invoice', label: 'Invoice' },
  { value: 'goods_receipt', label: 'Goods Receipt' },
]

const SOURCE_SYSTEMS = [
  { value: 'sap_ecc', label: 'SAP ECC' },
  { value: 'sap_b1', label: 'SAP B1' },
  { value: 'infor', label: 'Infor' },
]

const filteredStages = computed(() =>
  stages.value
    .filter(s => s.doc_type === docType.value && s.source_system === sourceSystem.value)
    .sort((a, b) => a.stage_order - b.stage_order)
)

const nextOrder = computed(() => {
  if (!filteredStages.value.length) return 1
  return Math.max(...filteredStages.value.map(s => s.stage_order)) + 1
})

async function load() {
  loading.value = true
  try {
    const { data } = await configApi.listStages()
    stages.value = data.stages
  } catch {
    ui.showToast('Failed to load stages', 'error')
  } finally {
    loading.value = false
  }
}

async function addStage() {
  if (!newStageKey.value.trim() || !newStageLabel.value.trim()) return
  saving.value = true
  try {
    await configApi.createStage({
      doc_type: docType.value,
      source_system: sourceSystem.value,
      stage_order: nextOrder.value,
      stage_key: newStageKey.value.trim(),
      stage_label: newStageLabel.value.trim(),
    })
    newStageKey.value = ''
    newStageLabel.value = ''
    await load()
    ui.showToast('Stage added', 'success')
  } catch {
    ui.showToast('Failed to add stage', 'error')
  } finally {
    saving.value = false
  }
}

async function deleteStage(id: string) {
  try {
    await configApi.deleteStage(id)
    await load()
    ui.showToast('Stage deleted', 'success')
  } catch {
    ui.showToast('Failed to delete stage', 'error')
  }
}

async function moveStage(stage: StatusStage, direction: -1 | 1) {
  const list = filteredStages.value
  const idx = list.findIndex(s => s.id === stage.id)
  const swapIdx = idx + direction
  if (swapIdx < 0 || swapIdx >= list.length) return

  const other = list[swapIdx]
  // Swap stage_order values by re-creating both
  saving.value = true
  try {
    await Promise.all([
      configApi.createStage({
        doc_type: stage.doc_type,
        source_system: stage.source_system,
        stage_order: other.stage_order,
        stage_key: stage.stage_key,
        stage_label: stage.stage_label,
      }),
      configApi.createStage({
        doc_type: other.doc_type,
        source_system: other.source_system,
        stage_order: stage.stage_order,
        stage_key: other.stage_key,
        stage_label: other.stage_label,
      }),
    ])
    await load()
  } catch {
    ui.showToast('Failed to reorder', 'error')
  } finally {
    saving.value = false
  }
}

onMounted(load)
</script>

<template>
  <div class="space-y-4">
    <div class="card">
      <h3 class="font-semibold text-sm mb-3">Stage Definitions</h3>
      <p class="text-xs text-dark-400 mb-4">Define the ordered stages a document goes through in each system. These stages power the status timeline and stage-filtered subscriptions.</p>

      <!-- Filters -->
      <div class="grid grid-cols-2 gap-3 mb-4">
        <div>
          <label class="text-xs text-dark-400 mb-1 block">Document Type</label>
          <select v-model="docType" class="input-field w-full">
            <option v-for="dt in DOC_TYPES" :key="dt.value" :value="dt.value">{{ dt.label }}</option>
          </select>
        </div>
        <div>
          <label class="text-xs text-dark-400 mb-1 block">Source System</label>
          <select v-model="sourceSystem" class="input-field w-full">
            <option v-for="ss in SOURCE_SYSTEMS" :key="ss.value" :value="ss.value">{{ ss.label }}</option>
          </select>
        </div>
      </div>

      <!-- Stage list -->
      <div v-if="loading" class="text-dark-500 text-sm text-center py-4">Loading...</div>

      <div v-else-if="filteredStages.length" class="space-y-1 mb-4">
        <div class="flex items-center gap-2 px-2 py-1 text-xs text-dark-500 border-b border-dark-700">
          <span class="w-10 shrink-0 text-center">#</span>
          <span class="w-32 shrink-0">Stage Key</span>
          <span class="flex-1">Label</span>
          <span class="w-20 shrink-0 text-center">Order</span>
          <span class="w-20 shrink-0"></span>
        </div>
        <div
          v-for="(stage, i) in filteredStages"
          :key="stage.id"
          class="flex items-center gap-2 px-2 py-2 rounded bg-dark-900/50 hover:bg-dark-900"
        >
          <span class="w-10 shrink-0 text-center text-xs text-dark-500">{{ i + 1 }}</span>
          <span class="w-32 shrink-0 text-xs font-mono text-primary-400">{{ stage.stage_key }}</span>
          <span class="flex-1 text-sm text-dark-200">{{ stage.stage_label }}</span>
          <div class="w-20 shrink-0 flex justify-center gap-1">
            <button
              @click="moveStage(stage, -1)"
              :disabled="i === 0 || saving"
              class="text-xs text-dark-400 hover:text-dark-200 disabled:opacity-30 px-1"
              title="Move up"
            >&#9650;</button>
            <button
              @click="moveStage(stage, 1)"
              :disabled="i === filteredStages.length - 1 || saving"
              class="text-xs text-dark-400 hover:text-dark-200 disabled:opacity-30 px-1"
              title="Move down"
            >&#9660;</button>
          </div>
          <button
            @click="deleteStage(stage.id)"
            class="w-20 shrink-0 text-xs text-red-400 hover:text-red-300"
          >Delete</button>
        </div>
      </div>

      <p v-else class="text-dark-500 text-sm text-center py-4 mb-4">
        No stages defined for {{ DOC_TYPES.find(d => d.value === docType)?.label }} / {{ SOURCE_SYSTEMS.find(s => s.value === sourceSystem)?.label }}.
      </p>

      <!-- Add stage form -->
      <div class="border-t border-dark-700 pt-3">
        <h4 class="text-xs font-semibold text-dark-400 mb-2">Add Stage</h4>
        <form @submit.prevent="addStage" class="flex items-end gap-3">
          <div class="flex-1">
            <label class="text-xs text-dark-400 mb-1 block">Stage Key</label>
            <input v-model="newStageKey" placeholder="e.g. confirmed" class="input-field w-full" />
          </div>
          <div class="flex-1">
            <label class="text-xs text-dark-400 mb-1 block">Stage Label</label>
            <input v-model="newStageLabel" placeholder="e.g. Order Confirmed" class="input-field w-full" />
          </div>
          <button type="submit" :disabled="saving || !newStageKey || !newStageLabel" class="btn-primary text-xs shrink-0">
            {{ saving ? 'Adding...' : 'Add Stage' }}
          </button>
        </form>
      </div>
    </div>
  </div>
</template>
