<script setup lang="ts">
import type { PropType } from "vue"
import type { SelectItem } from "@nuxt/ui"

const props = defineProps({
  task: { type: Object as PropType<any>, default: null },
  registeredFunctions: { type: Array as PropType<string[]>, default: () => [] },
})

const emit = defineEmits(["close"])

const isEdit = computed(() => !!props.task)

const form = reactive({
  name: props.task?.name ?? "",
  cronExpression: props.task?.cronExpression ?? "0 9 * * *",
  type: (props.task?.type ?? "function") as "function" | "http",
  functionName: props.task?.functionName ?? "",
  functionPayload: props.task?.functionPayload ?? "",
  httpMethod: props.task?.httpMethod ?? "GET",
  httpUrl: props.task?.httpUrl ?? "",
  httpHeaders: props.task?.httpHeaders ?? "",
  httpBody: props.task?.httpBody ?? "",
  catchUp: props.task?.catchUp === 1,
  enabled: props.task ? props.task.enabled === 1 : true,
  maxRetries: props.task?.maxRetries ?? 0,
  retryDelaySeconds: props.task?.retryDelaySeconds ?? 60,
  timeoutSeconds: props.task?.timeoutSeconds ?? 300,
})

const saving = ref(false)
const error = ref("")
const showAdvanced = ref(false)

const typeItems: SelectItem[] = [
  { label: "Function", value: "function" },
  { label: "HTTP Request", value: "http" },
]

const httpMethodItems: SelectItem[] = [
  { label: "GET", value: "GET" },
  { label: "POST", value: "POST" },
  { label: "PUT", value: "PUT" },
  { label: "DELETE", value: "DELETE" },
]

const functionItems = computed<SelectItem[]>(() =>
  props.registeredFunctions.map((f) => ({ label: f, value: f }))
)

const cronPresets = [
  { label: "Every minute", value: "* * * * *" },
  { label: "Every 5 minutes", value: "*/5 * * * *" },
  { label: "Every hour", value: "0 * * * *" },
  { label: "Daily at 9am", value: "0 9 * * *" },
  { label: "Daily at midnight", value: "0 0 * * *" },
  { label: "Weekly Monday 9am", value: "0 9 * * 1" },
]

async function save() {
  saving.value = true
  error.value = ""

  const body = {
    ...form,
    catchUp: form.catchUp ? 1 : 0,
    enabled: form.enabled ? 1 : 0,
  }

  try {
    if (isEdit.value) {
      await $fetch(`/api/scheduler/tasks/${props.task.id}`, {
        method: "PUT",
        body,
      })
    } else {
      await $fetch("/api/scheduler/tasks", {
        method: "POST",
        body,
      })
    }
    emit("close")
  } catch (err: any) {
    error.value = err?.data?.message ?? err?.message ?? "Save failed"
  } finally {
    saving.value = false
  }
}

function onOverlayClick(e: MouseEvent) {
  if ((e.target as HTMLElement).dataset.overlay === "true") {
    emit("close")
  }
}
</script>

<template>
  <div
    data-overlay="true"
    class="fixed inset-0 z-50 flex items-start justify-center pt-[10vh] bg-black/40"
    @click="onOverlayClick"
  >
    <div class="bg-white rounded-xl shadow-xl w-full max-w-lg max-h-[80vh] overflow-y-auto">
      <!-- Header -->
      <div class="flex items-center justify-between px-6 py-4 border-b">
        <h2 class="text-lg font-semibold">{{ isEdit ? 'Edit' : 'Create' }} Task</h2>
        <UButton
          variant="ghost"
          color="neutral"
          size="sm"
          icon="i-lucide-x"
          square
          @click="emit('close')"
        />
      </div>

      <!-- Body -->
      <div class="space-y-4 p-6">
        <div v-if="error" class="bg-red-50 text-red-700 rounded-lg px-4 py-3 text-sm">
          {{ error }}
        </div>

        <UFormField label="Name" required>
          <UInput v-model="form.name" placeholder="Task name" />
        </UFormField>

        <UFormField label="Type" required>
          <USelect v-model="form.type" :items="typeItems" />
        </UFormField>

        <UFormField label="Cron Expression" required>
          <UInput v-model="form.cronExpression" placeholder="0 9 * * *" />
          <div class="flex gap-1 mt-1.5 flex-wrap">
            <UButton
              v-for="preset in cronPresets"
              :key="preset.value"
              size="xs"
              variant="ghost"
              @click="form.cronExpression = preset.value"
            >
              {{ preset.label }}
            </UButton>
          </div>
        </UFormField>

        <!-- Function fields -->
        <template v-if="form.type === 'function'">
          <UFormField label="Function" required>
            <USelect
              v-model="form.functionName"
              :items="functionItems"
              placeholder="Select function"
            />
          </UFormField>
          <UFormField label="Payload (JSON)">
            <UInput v-model="form.functionPayload" placeholder='{"key": "value"}' />
          </UFormField>
        </template>

        <!-- HTTP fields -->
        <template v-if="form.type === 'http'">
          <div class="grid grid-cols-4 gap-3">
            <UFormField label="Method" class="col-span-1">
              <USelect v-model="form.httpMethod" :items="httpMethodItems" />
            </UFormField>
            <UFormField label="URL" required class="col-span-3">
              <UInput v-model="form.httpUrl" placeholder="https://example.com/api" />
            </UFormField>
          </div>
          <UFormField label="Headers (JSON)">
            <UInput v-model="form.httpHeaders" placeholder='{"Authorization": "Bearer ..."}' />
          </UFormField>
          <UFormField label="Body">
            <UTextarea v-model="form.httpBody" :rows="3" />
          </UFormField>
        </template>

        <!-- Advanced settings -->
        <div class="border rounded-lg">
          <button
            type="button"
            class="w-full flex items-center justify-between px-4 py-2.5 text-sm font-medium hover:bg-gray-50 rounded-lg transition-colors"
            @click="showAdvanced = !showAdvanced"
          >
            <span>Advanced</span>
            <UIcon
              :name="showAdvanced ? 'i-lucide-chevron-up' : 'i-lucide-chevron-down'"
              class="size-4 text-gray-400"
            />
          </button>
          <div v-if="showAdvanced" class="space-y-4 px-4 pb-4 border-t pt-4">
            <div class="flex flex-col gap-3">
              <UCheckbox v-model="form.catchUp" label="Catch up missed executions after restart" />
              <UCheckbox v-model="form.enabled" label="Enabled" />
            </div>
            <div class="grid grid-cols-3 gap-3">
              <UFormField label="Max Retries">
                <UInput v-model.number="form.maxRetries" type="number" :min="0" />
              </UFormField>
              <UFormField label="Retry Delay (s)">
                <UInput v-model.number="form.retryDelaySeconds" type="number" :min="1" />
              </UFormField>
              <UFormField label="Timeout (s)">
                <UInput v-model.number="form.timeoutSeconds" type="number" :min="1" />
              </UFormField>
            </div>
          </div>
        </div>
      </div>

      <!-- Footer -->
      <div class="flex justify-end gap-2 px-6 py-4 border-t bg-gray-50 rounded-b-xl">
        <UButton variant="ghost" @click="emit('close')">Cancel</UButton>
        <UButton :loading="saving" @click="save">
          {{ isEdit ? 'Update' : 'Create' }}
        </UButton>
      </div>
    </div>
  </div>
</template>
