<script setup lang="ts">
import type { PropType } from "vue"

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 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
  }
}
</script>

<template>
  <UModal :open="true" @close="emit('close')">
    <template #header>
      <h2 class="text-lg font-semibold">{{ isEdit ? 'Edit' : 'Create' }} Task</h2>
    </template>

    <div class="space-y-4 p-4">
      <UAlert v-if="error" color="red" :title="error" />

      <div>
        <label class="block text-sm font-medium mb-1">Name</label>
        <UInput v-model="form.name" placeholder="Task name" />
      </div>

      <div>
        <label class="block text-sm font-medium mb-1">Type</label>
        <USelect
          v-model="form.type"
          :options="[
            { label: 'Function', value: 'function' },
            { label: 'HTTP Request', value: 'http' },
          ]"
        />
      </div>

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

      <!-- Function fields -->
      <template v-if="form.type === 'function'">
        <div>
          <label class="block text-sm font-medium mb-1">Function</label>
          <USelect
            v-model="form.functionName"
            :options="registeredFunctions.map((f: string) => ({ label: f, value: f }))"
            placeholder="Select function"
          />
        </div>
        <div>
          <label class="block text-sm font-medium mb-1">Payload (JSON)</label>
          <UInput v-model="form.functionPayload" placeholder='{"key": "value"}' />
        </div>
      </template>

      <!-- HTTP fields -->
      <template v-if="form.type === 'http'">
        <div class="grid grid-cols-4 gap-2">
          <div class="col-span-1">
            <label class="block text-sm font-medium mb-1">Method</label>
            <USelect
              v-model="form.httpMethod"
              :options="['GET','POST','PUT','DELETE'].map(m => ({ label: m, value: m }))"
            />
          </div>
          <div class="col-span-3">
            <label class="block text-sm font-medium mb-1">URL</label>
            <UInput v-model="form.httpUrl" placeholder="https://example.com/api" />
          </div>
        </div>
        <div>
          <label class="block text-sm font-medium mb-1">Headers (JSON)</label>
          <UInput v-model="form.httpHeaders" placeholder='{"Authorization": "Bearer ..."}' />
        </div>
        <div>
          <label class="block text-sm font-medium mb-1">Body</label>
          <UInput v-model="form.httpBody" />
        </div>
      </template>

      <!-- Advanced settings -->
      <details class="border rounded-lg p-3">
        <summary class="text-sm font-medium cursor-pointer">Advanced</summary>
        <div class="space-y-3 mt-3">
          <label class="flex items-center gap-2">
            <input type="checkbox" v-model="form.catchUp" />
            <span class="text-sm">Catch up missed executions after restart</span>
          </label>
          <label class="flex items-center gap-2">
            <input type="checkbox" v-model="form.enabled" />
            <span class="text-sm">Enabled</span>
          </label>
          <div class="grid grid-cols-3 gap-3">
            <div>
              <label class="block text-xs font-medium mb-1">Max Retries</label>
              <UInput v-model.number="form.maxRetries" type="number" min="0" />
            </div>
            <div>
              <label class="block text-xs font-medium mb-1">Retry Delay (s)</label>
              <UInput v-model.number="form.retryDelaySeconds" type="number" min="1" />
            </div>
            <div>
              <label class="block text-xs font-medium mb-1">Timeout (s)</label>
              <UInput v-model.number="form.timeoutSeconds" type="number" min="1" />
            </div>
          </div>
        </div>
      </details>
    </div>

    <template #footer>
      <div class="flex justify-end gap-2">
        <UButton variant="ghost" @click="emit('close')">Cancel</UButton>
        <UButton :loading="saving" @click="save">
          {{ isEdit ? 'Update' : 'Create' }}
        </UButton>
      </div>
    </template>
  </UModal>
</template>
