<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 Requests</h1>
            <button
              @click="showCreateForm = true"
              class="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90"
            >
              New Request
            </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 Request</h2>
            <form @submit.prevent="createRequest" class="space-y-4">
              <div>
                <label class="block text-sm font-medium mb-2">Definition</label>
                <select
                  v-model="newRequest.definitionId"
                  required
                  class="w-full px-3 py-2 border rounded-md bg-background"
                >
                  <option value="" disabled>Select a definition</option>
                  <option v-for="definition in definitions" :key="definition.id" :value="definition.id">
                    {{ definition.name }}
                  </option>
                </select>
              </div>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label class="block text-sm font-medium mb-2">Target Object Type</label>
                  <input
                    v-model="newRequest.targetObjectType"
                    type="text"
                    required
                    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">Target Object ID</label>
                  <input
                    v-model="newRequest.targetObjectId"
                    type="text"
                    required
                    class="w-full px-3 py-2 border rounded-md bg-background"
                    placeholder="record-id"
                  />
                </div>
              </div>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label class="block text-sm font-medium mb-2">Action</label>
                  <input
                    v-model="newRequest.action"
                    type="text"
                    class="w-full px-3 py-2 border rounded-md bg-background"
                    placeholder="submit"
                  />
                </div>
                <div>
                  <label class="block text-sm font-medium mb-2">Submitted By (User ID)</label>
                  <input
                    v-model="newRequest.submittedById"
                    type="text"
                    class="w-full px-3 py-2 border rounded-md bg-background"
                    placeholder="user-id"
                  />
                </div>
              </div>
              <div>
                <label class="block text-sm font-medium mb-2">Snapshot (JSON)</label>
                <textarea
                  v-model="newRequest.snapshot"
                  class="w-full px-3 py-2 border rounded-md bg-background font-mono text-sm"
                  rows="3"
                  placeholder='{"amount": 1200, "currency": "USD"}'
                />
              </div>
              <div>
                <label class="block text-sm font-medium mb-2">Field Changes (JSON)</label>
                <textarea
                  v-model="newRequest.fieldChanges"
                  class="w-full px-3 py-2 border rounded-md bg-background font-mono text-sm"
                  rows="3"
                  placeholder='{"amount": {"from": 500, "to": 1200}}'
                />
              </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">
            <div
              v-for="request in requests"
              :key="request.id"
              class="p-6 border rounded-lg bg-card"
            >
              <div class="flex items-center justify-between mb-4">
                <div>
                  <h3 class="text-lg font-semibold">{{ request.definition?.name || 'Approval Request' }}</h3>
                  <p class="text-sm text-muted-foreground">
                    {{ request.targetObjectType }} • {{ request.targetObjectId }}
                  </p>
                </div>
                <span
                  class="text-xs px-2 py-1 rounded"
                  :class="statusClass(request.status)"
                >
                  {{ request.status }}
                </span>
              </div>
              <div class="text-sm text-muted-foreground">
                <div>Steps: {{ request.steps?.length || 0 }}</div>
                <div>Submitted: {{ formatDate(request.submittedAt) }}</div>
              </div>
            </div>
          </div>
        </div>
      </main>
    </NuxtLayout>
  </div>
</template>

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

const requests = ref<any[]>([])
const definitions = ref<any[]>([])
const loading = ref(true)
const error = ref<string | null>(null)
const showCreateForm = ref(false)
const newRequest = ref({
  definitionId: '',
  targetObjectType: '',
  targetObjectId: '',
  action: '',
  submittedById: '',
  snapshot: '',
  fieldChanges: '',
})

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

const statusClass = (status: string) => {
  if (status === 'approved') return 'bg-primary/10 text-primary'
  if (status === 'rejected') return 'bg-destructive/10 text-destructive'
  return 'bg-muted text-muted-foreground'
}

const formatDate = (value?: string) => {
  if (!value) return '—'
  const date = new Date(value)
  return date.toLocaleString()
}

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

const fetchDefinitions = async () => {
  try {
    definitions.value = await api.get('/setup/approvals')
  } catch (e) {
    definitions.value = []
  }
}

const createRequest = async () => {
  try {
    await api.post('/approvals', {
      definitionId: newRequest.value.definitionId,
      targetObjectType: newRequest.value.targetObjectType,
      targetObjectId: newRequest.value.targetObjectId,
      action: newRequest.value.action || undefined,
      submittedById: newRequest.value.submittedById || undefined,
      snapshot: parseJson(newRequest.value.snapshot),
      fieldChanges: parseJson(newRequest.value.fieldChanges),
    })
    showCreateForm.value = false
    newRequest.value = {
      definitionId: '',
      targetObjectType: '',
      targetObjectId: '',
      action: '',
      submittedById: '',
      snapshot: '',
      fieldChanges: '',
    }
    await fetchRequests()
  } catch (e: any) {
    alert('Error creating approval request: ' + e.message)
  }
}

onMounted(async () => {
  await Promise.all([fetchRequests(), fetchDefinitions()])
})
</script>
