<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">Tasks</h1>
            <button
              @click="showCreateForm = true"
              class="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90"
            >
              New Task
            </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 Task</h2>
            <form @submit.prevent="createTask" class="space-y-4">
              <div>
                <label class="block text-sm font-medium mb-2">Title</label>
                <input
                  v-model="newTask.title"
                  type="text"
                  required
                  class="w-full px-3 py-2 border rounded-md bg-background"
                  placeholder="Follow up on approval"
                />
              </div>
              <div>
                <label class="block text-sm font-medium mb-2">Description</label>
                <textarea
                  v-model="newTask.description"
                  class="w-full px-3 py-2 border rounded-md bg-background"
                  rows="2"
                />
              </div>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label class="block text-sm font-medium mb-2">Assigned To (User ID)</label>
                  <input
                    v-model="newTask.assignedToId"
                    type="text"
                    class="w-full px-3 py-2 border rounded-md bg-background"
                  />
                </div>
                <div>
                  <label class="block text-sm font-medium mb-2">Due At</label>
                  <input
                    v-model="newTask.dueAt"
                    type="datetime-local"
                    class="w-full px-3 py-2 border rounded-md bg-background"
                  />
                </div>
              </div>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label class="block text-sm font-medium mb-2">Related Object Type</label>
                  <input
                    v-model="newTask.relatedObjectType"
                    type="text"
                    class="w-full px-3 py-2 border rounded-md bg-background"
                    placeholder="ApprovalAssignment"
                  />
                </div>
                <div>
                  <label class="block text-sm font-medium mb-2">Related Object ID</label>
                  <input
                    v-model="newTask.relatedObjectId"
                    type="text"
                    class="w-full px-3 py-2 border rounded-md bg-background"
                  />
                </div>
              </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="task in tasks"
              :key="task.id"
              class="p-6 border rounded-lg bg-card"
            >
              <div class="flex items-center justify-between mb-2">
                <h3 class="text-lg font-semibold">{{ task.title }}</h3>
                <span
                  class="text-xs px-2 py-1 rounded"
                  :class="task.status === 'completed' ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground'"
                >
                  {{ task.status }}
                </span>
              </div>
              <p class="text-sm text-muted-foreground mb-2">
                {{ task.description || 'No description' }}
              </p>
              <div class="text-sm text-muted-foreground">
                <div>Assigned: {{ task.assignedToId || 'Unassigned' }}</div>
                <div>Due: {{ formatDate(task.dueAt) }}</div>
              </div>
            </div>
          </div>
        </div>
      </main>
    </NuxtLayout>
  </div>
</template>

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

const tasks = ref<any[]>([])
const loading = ref(true)
const error = ref<string | null>(null)
const showCreateForm = ref(false)
const newTask = ref({
  title: '',
  description: '',
  assignedToId: '',
  dueAt: '',
  relatedObjectType: '',
  relatedObjectId: '',
})

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

const fetchTasks = async () => {
  try {
    loading.value = true
    tasks.value = await api.get('/tasks')
  } catch (e: any) {
    console.log('here');
    error.value = e.message
  } finally {
    loading.value = false
  }
}

const createTask = async () => {
  try {
    await api.post('/tasks', {
      title: newTask.value.title,
      description: newTask.value.description || undefined,
      assignedToId: newTask.value.assignedToId || undefined,
      dueAt: newTask.value.dueAt || undefined,
      relatedObjectType: newTask.value.relatedObjectType || undefined,
      relatedObjectId: newTask.value.relatedObjectId || undefined,
    })
    showCreateForm.value = false
    newTask.value = {
      title: '',
      description: '',
      assignedToId: '',
      dueAt: '',
      relatedObjectType: '',
      relatedObjectId: '',
    }
    await fetchTasks()
  } catch (e: any) {
    alert('Error creating task: ' + e.message)
  }
}

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