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

const ui = useUiStore()
const searchTerm = ref('')
const results = ref<any[]>([])
const selectedChain = ref<any>(null)
const searching = ref(false)

async function search() {
  if (!searchTerm.value.trim()) return
  searching.value = true
  try {
    const { data } = await configApi.searchDocuments(searchTerm.value.trim())
    results.value = data.results || []
  } catch {
    ui.showToast('Search failed', 'error')
  } finally {
    searching.value = false
  }
}

async function viewChain(chainId: string) {
  try {
    const { data } = await configApi.getChain(chainId)
    selectedChain.value = data
  } catch {
    ui.showToast('Could not load chain', 'error')
  }
}

const docTypeLabels: Record<string, string> = {
  sales_order: 'Sales Order',
  purchase_order: 'Purchase Order',
  invoice: 'Invoice',
  delivery: 'Delivery',
  goods_receipt: 'Goods Receipt',
}

const systemColors: Record<string, string> = {
  sap_b1: 'text-blue-400',
  sap_ecc: 'text-yellow-400',
  infor: 'text-green-400',
  hubspot: 'text-orange-400',
}
</script>

<template>
  <div class="h-full flex flex-col p-4">
    <div class="max-w-5xl mx-auto w-full">
      <h2 class="text-lg font-semibold mb-4">Document Tracking</h2>
      <p class="text-dark-400 text-sm mb-4">Track documents (orders, invoices) across legal entities and ERP systems.</p>

      <!-- Search -->
      <div class="flex gap-3 mb-6">
        <input
          v-model="searchTerm"
          @keyup.enter="search"
          placeholder="Search by order number, PO number, or reference..."
          class="input-field flex-1"
        />
        <button @click="search" :disabled="searching" class="btn-primary">
          {{ searching ? 'Searching...' : 'Search' }}
        </button>
      </div>

      <!-- Results -->
      <div v-if="results.length" class="space-y-3 mb-6">
        <div v-for="doc in results" :key="doc.id" class="card flex items-center justify-between">
          <div>
            <div class="flex items-center gap-2">
              <span :class="systemColors[doc.source_system] || 'text-dark-300'" class="text-xs font-medium uppercase">
                {{ doc.source_system }}
              </span>
              <span class="text-dark-500 text-xs">{{ doc.entity_name }}</span>
            </div>
            <div class="font-medium mt-1">
              {{ docTypeLabels[doc.doc_type] || doc.doc_type }} #{{ doc.doc_number }}
            </div>
            <div class="text-xs text-dark-500 mt-0.5">
              {{ doc.doc_date || 'No date' }}
              <span v-if="doc.reference_number" class="ml-2">Ref: {{ doc.reference_number }}</span>
              <span v-if="doc.total_amount" class="ml-2">{{ doc.currency }} {{ doc.total_amount?.toLocaleString() }}</span>
            </div>
          </div>
          <button v-if="doc.chain_id" @click="viewChain(doc.chain_id)" class="btn-secondary text-xs">
            View Chain
          </button>
        </div>
      </div>

      <!-- Chain detail -->
      <div v-if="selectedChain" class="card">
        <div class="flex items-center justify-between mb-4">
          <h3 class="font-semibold">Document Chain: {{ selectedChain.chain_reference }}</h3>
          <button @click="selectedChain = null" class="text-dark-500 hover:text-dark-300 text-sm">Close</button>
        </div>

        <!-- Timeline -->
        <div class="relative pl-6">
          <div class="absolute left-2 top-0 bottom-0 w-0.5 bg-dark-600" />

          <div v-for="(doc, i) in selectedChain.documents" :key="doc.id" class="relative mb-4 last:mb-0">
            <div class="absolute -left-4 w-4 h-4 rounded-full border-2 border-dark-600 bg-dark-800" />
            <div class="ml-4 p-3 bg-dark-900 rounded-lg">
              <div class="flex items-center gap-2 mb-1">
                <span :class="systemColors[doc.source_system] || 'text-dark-300'" class="text-xs font-bold uppercase">
                  {{ doc.source_system }}
                </span>
                <span class="text-dark-500 text-xs">{{ doc.entity_name }}</span>
                <span class="text-dark-600 text-xs ml-auto">{{ doc.doc_date }}</span>
              </div>
              <div class="font-medium text-sm">
                {{ docTypeLabels[doc.doc_type] || doc.doc_type }} #{{ doc.doc_number }}
              </div>
              <div v-if="doc.total_amount" class="text-xs text-dark-400 mt-0.5">
                {{ doc.currency }} {{ doc.total_amount?.toLocaleString() }}
                <span v-if="doc.status" class="ml-2">Status: {{ doc.status }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <p v-if="!results.length && !selectedChain" class="text-dark-500 text-center py-12">
        Search for a document number to track it across systems.
      </p>
    </div>
  </div>
</template>
