<template>
  <div class="min-h-screen bg-background">
    <NuxtLayout name="default">
      <main class="container mx-auto px-4 py-8">
        <div v-if="loading" class="text-center py-12">Loading...</div>
        <div v-else-if="error" class="text-destructive">Error: {{ error }}</div>
        <div v-else>
          <div class="flex items-center justify-between mb-6">
            <h1 class="text-3xl font-bold">Approval Definitions</h1>
            <button
              @click="showCreateForm = true"
              class="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90"
            >
              New Definition
            </button>
          </div>

          <div v-if="showCreateForm" class="mb-6 p-6 border rounded-lg bg-card">
            <h2 class="text-xl font-semibold mb-4">Create Approval Definition</h2>
            <form @submit.prevent="createDefinition" class="space-y-4">
              <div>
                <label class="block text-sm font-medium mb-2">Name</label>
                <input
                  v-model="newDefinition.name"
                  type="text"
                  required
                  class="w-full px-3 py-2 border rounded-md bg-background"
                  placeholder="Expense Approval"
                />
              </div>
              <div>
                <label class="block text-sm font-medium mb-2">Trigger Type</label>
                <select
                  v-model="newDefinition.triggerType"
                  required
                  class="w-full px-3 py-2 border rounded-md bg-background"
                >
                  <option value="action">Action</option>
                  <option value="state_transition">State Transition</option>
                  <option value="field_change">Field Change</option>
                </select>
              </div>
              <div>
                <label class="block text-sm font-medium mb-2">Target Object Type</label>
                <input
                  v-model="newDefinition.targetObjectType"
                  type="text"
                  class="w-full px-3 py-2 border rounded-md bg-background"
                  placeholder="Expense"
                />
              </div>
              <div>
                <label class="block text-sm font-medium mb-2">Description</label>
                <textarea
                  v-model="newDefinition.description"
                  class="w-full px-3 py-2 border rounded-md bg-background"
                  rows="2"
                />
              </div>
              <div>
                <label class="block text-sm font-medium mb-2">Entry Criteria (JSON)</label>
                <textarea
                  v-model="newDefinition.entryCriteria"
                  class="w-full px-3 py-2 border rounded-md bg-background font-mono text-sm"
                  rows="3"
                  placeholder='{"amount": {"gte": 500}}'
                />
              </div>
              <div>
                <label class="block text-sm font-medium mb-2">Steps (JSON Array)</label>
                <textarea
                  v-model="newDefinition.steps"
                  class="w-full px-3 py-2 border rounded-md bg-background font-mono text-sm"
                  rows="4"
                  placeholder='[{"key":"manager","name":"Manager Review","assignees":[]}]'
                />
              </div>
              <div>
                <label class="block text-sm font-medium mb-2">Voting Policy (JSON)</label>
                <textarea
                  v-model="newDefinition.votingPolicy"
                  class="w-full px-3 py-2 border rounded-md bg-background font-mono text-sm"
                  rows="3"
                  placeholder='{"type":"majority"}'
                />
              </div>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label class="block text-sm font-medium mb-2">Rejection Rule</label>
                  <input
                    v-model="newDefinition.rejectionRule"
                    type="text"
                    class="w-full px-3 py-2 border rounded-md bg-background"
                    placeholder="any"
                  />
                </div>
                <div>
                  <label class="block text-sm font-medium mb-2">Material Change Policy</label>
                  <input
                    v-model="newDefinition.materialChangePolicy"
                    type="text"
                    class="w-full px-3 py-2 border rounded-md bg-background"
                    placeholder="invalidate"
                  />
                </div>
              </div>
              <div class="flex items-center gap-2">
                <input id="isActive" v-model="newDefinition.isActive" type="checkbox" />
                <label for="isActive" class="text-sm">Active</label>
              </div>
              <div class="flex gap-2">
                <button
                  type="submit"
                  class="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90"
                >
                  Create
                </button>
                <button
                  type="button"
                  @click="showCreateForm = false"
                  class="px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/90"
                >
                  Cancel
                </button>
              </div>
            </form>
          </div>

          <div class="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
            <div
              v-for="definition in definitions"
              :key="definition.id"
              class="p-6 border rounded-lg bg-card"
            >
              <div class="flex items-start justify-between mb-2">
                <h3 class="text-xl font-semibold">{{ definition.name }}</h3>
                <span
                  class="text-xs px-2 py-1 rounded"
                  :class="definition.isActive ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground'"
                >
                  {{ definition.isActive ? 'Active' : 'Inactive' }}
                </span>
              </div>
              <p class="text-sm text-muted-foreground mb-4">
                {{ definition.description || 'No description' }}
              </p>
              <div class="text-sm space-y-1">
                <div><span class="text-muted-foreground">Trigger:</span> {{ definition.triggerType }}</div>
                <div>
                  <span class="text-muted-foreground">Target:</span>
                  {{ definition.targetObjectType || 'Any' }}
                </div>
                <div>
                  <span class="text-muted-foreground">Version:</span> {{ definition.version }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </main>
    </NuxtLayout>
  </div>
</template>

<script setup lang="ts">
const { api } = useApi()

const definitions = ref<any[]>([])
const loading = ref(true)
const error = ref<string | null>(null)
const showCreateForm = ref(false)
const newDefinition = ref({
  name: '',
  triggerType: 'action',
  targetObjectType: '',
  description: '',
  entryCriteria: '',
  steps: '',
  votingPolicy: '',
  rejectionRule: 'any',
  materialChangePolicy: 'invalidate',
  isActive: true,
})

const parseJson = (value: string) => {
  if (!value) return undefined
  try {
    return JSON.parse(value)
  } catch (err) {
    return undefined
  }
}

const fetchDefinitions = async () => {
  try {
    loading.value = true
    definitions.value = await api.get('/setup/approvals')
  } catch (e: any) {
    error.value = e.message
  } finally {
    loading.value = false
  }
}

const createDefinition = async () => {
  try {
    await api.post('/setup/approvals', {
      name: newDefinition.value.name,
      triggerType: newDefinition.value.triggerType,
      targetObjectType: newDefinition.value.targetObjectType || undefined,
      description: newDefinition.value.description || undefined,
      entryCriteria: parseJson(newDefinition.value.entryCriteria),
      steps: parseJson(newDefinition.value.steps),
      votingPolicy: parseJson(newDefinition.value.votingPolicy),
      rejectionRule: newDefinition.value.rejectionRule || undefined,
      materialChangePolicy: newDefinition.value.materialChangePolicy || undefined,
      isActive: newDefinition.value.isActive,
    })
    showCreateForm.value = false
    newDefinition.value = {
      name: '',
      triggerType: 'action',
      targetObjectType: '',
      description: '',
      entryCriteria: '',
      steps: '',
      votingPolicy: '',
      rejectionRule: 'any',
      materialChangePolicy: 'invalidate',
      isActive: true,
    }
    await fetchDefinitions()
  } catch (e: any) {
    alert('Error creating approval definition: ' + e.message)
  }
}

onMounted(() => {
  fetchDefinitions()
})
</script>
