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

const ui = useUiStore()
const emit = defineEmits<{ created: [docNumber: string] }>()

const email = ref('')
const docNumber = ref('')
const sourceSystem = ref('')
const docType = ref('')
const submitting = ref(false)

// Stage filter
const availableStages = ref<StatusStage[]>([])
const selectedStages = ref<string[]>([])
const loadingStages = ref(false)

async function loadStages() {
  if (!docType.value || !sourceSystem.value) {
    availableStages.value = []
    selectedStages.value = []
    return
  }
  loadingStages.value = true
  try {
    const { data } = await configApi.listStages({ doc_type: docType.value, source_system: sourceSystem.value })
    availableStages.value = data.stages
  } catch {
    availableStages.value = []
  } finally {
    loadingStages.value = false
  }
}

// Reload stages when doc_type or source_system changes
watch([docType, sourceSystem], () => {
  selectedStages.value = []
  loadStages()
})

function toggleStage(key: string) {
  const idx = selectedStages.value.indexOf(key)
  if (idx >= 0) {
    selectedStages.value.splice(idx, 1)
  } else {
    selectedStages.value.push(key)
  }
}

async function submit() {
  if (!email.value.trim() || !docNumber.value.trim()) return
  submitting.value = true
  try {
    await configApi.createSubscription({
      email: email.value.trim(),
      doc_number: docNumber.value.trim(),
      source_system: sourceSystem.value || undefined,
      doc_type: docType.value || undefined,
      notify_on_stages: selectedStages.value.length ? selectedStages.value : undefined,
    })
    ui.showToast(`Subscribed ${email.value} to ${docNumber.value}`, 'success')
    const createdDoc = docNumber.value.trim()
    email.value = ''
    docNumber.value = ''
    sourceSystem.value = ''
    docType.value = ''
    selectedStages.value = []
    availableStages.value = []
    emit('created', createdDoc)
  } catch {
    ui.showToast('Failed to create subscription', 'error')
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <form @submit.prevent="submit" class="card space-y-3">
    <h3 class="font-semibold text-sm">Subscribe to Document Updates</h3>
    <p class="text-xs text-dark-400">Enter a Belegnummer and email to get notified when the order status changes.</p>
    <div class="grid grid-cols-2 gap-3">
      <div>
        <label class="text-xs text-dark-400 mb-1 block">Belegnummer *</label>
        <input v-model="docNumber" placeholder="e.g. 4500012345" class="input-field w-full" required />
      </div>
      <div>
        <label class="text-xs text-dark-400 mb-1 block">Email *</label>
        <input v-model="email" type="email" placeholder="user@company.com" class="input-field w-full" required />
      </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 value="">All systems</option>
          <option value="sap_ecc">SAP ECC</option>
          <option value="sap_b1">SAP B1</option>
          <option value="infor">Infor</option>
        </select>
      </div>
      <div>
        <label class="text-xs text-dark-400 mb-1 block">Document Type</label>
        <select v-model="docType" class="input-field w-full">
          <option value="">All types</option>
          <option value="sales_order">Sales Order</option>
          <option value="purchase_order">Purchase Order</option>
          <option value="delivery">Delivery</option>
          <option value="invoice">Invoice</option>
          <option value="goods_receipt">Goods Receipt</option>
        </select>
      </div>
    </div>

    <!-- Stage filter (shown when stages exist for selected doc_type + source_system) -->
    <div v-if="availableStages.length" class="col-span-2">
      <label class="text-xs text-dark-400 mb-1 block">Notify on Stages <span class="text-dark-500">(none = all changes)</span></label>
      <div class="flex flex-wrap gap-2">
        <label
          v-for="stage in availableStages"
          :key="stage.id"
          class="flex items-center gap-1.5 px-2 py-1 rounded border cursor-pointer text-xs transition-colors"
          :class="selectedStages.includes(stage.stage_key) ? 'border-primary-500 bg-primary-500/10 text-primary-300' : 'border-dark-600 text-dark-400 hover:border-dark-500'"
        >
          <input
            type="checkbox"
            :checked="selectedStages.includes(stage.stage_key)"
            @change="toggleStage(stage.stage_key)"
            class="accent-primary-500"
          />
          {{ stage.stage_label }}
        </label>
      </div>
    </div>
    <div v-else-if="loadingStages" class="col-span-2 text-xs text-dark-500">Loading stages...</div>

    <button type="submit" :disabled="submitting || !email || !docNumber" class="btn-primary text-sm">
      {{ submitting ? 'Subscribing...' : 'Subscribe' }}
    </button>
  </form>
</template>
