<script setup lang="ts">
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 = [
  { label: "Function", value: "function" },
  { label: "HTTP Request", value: "http" },
]

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

const functionItems = computed(() =>
  props.registeredFunctions.map((f: string) => ({ 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 text-gray-900">{{ isEdit ? 'Edit' : 'Create' }} Task</h2>
        <button
          class="p-1 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded"
          @click="emit('close')"
        >
          <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </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>

        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">Name *</label>
          <input
            v-model="form.name"
            type="text"
            placeholder="Task name"
            class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#cc785c] focus:border-transparent"
          />
        </div>

        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">Type *</label>
          <select
            v-model="form.type"
            class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#cc785c] focus:border-transparent"
          >
            <option v-for="item in typeItems" :key="item.value" :value="item.value">
              {{ item.label }}
            </option>
          </select>
        </div>

        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">Cron Expression *</label>
          <input
            v-model="form.cronExpression"
            type="text"
            placeholder="0 9 * * *"
            class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-[#cc785c] focus:border-transparent"
          />
          <div class="flex gap-1 mt-1.5 flex-wrap">
            <button
              v-for="preset in cronPresets"
              :key="preset.value"
              type="button"
              class="px-2 py-1 text-xs text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded transition-colors"
              @click="form.cronExpression = preset.value"
            >
              {{ preset.label }}
            </button>
          </div>
        </div>

        <!-- Function fields -->
        <template v-if="form.type === 'function'">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Function *</label>
            <select
              v-model="form.functionName"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#cc785c] focus:border-transparent"
            >
              <option value="" disabled>Select function</option>
              <option v-for="item in functionItems" :key="item.value" :value="item.value">
                {{ item.label }}
              </option>
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Payload (JSON)</label>
            <input
              v-model="form.functionPayload"
              type="text"
              placeholder='{"key": "value"}'
              class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-[#cc785c] focus:border-transparent"
            />
          </div>
        </template>

        <!-- HTTP fields -->
        <template v-if="form.type === 'http'">
          <div class="grid grid-cols-4 gap-3">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Method</label>
              <select
                v-model="form.httpMethod"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#cc785c] focus:border-transparent"
              >
                <option v-for="item in httpMethodItems" :key="item.value" :value="item.value">
                  {{ item.label }}
                </option>
              </select>
            </div>
            <div class="col-span-3">
              <label class="block text-sm font-medium text-gray-700 mb-1">URL *</label>
              <input
                v-model="form.httpUrl"
                type="text"
                placeholder="https://example.com/api"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#cc785c] focus:border-transparent"
              />
            </div>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Headers (JSON)</label>
            <input
              v-model="form.httpHeaders"
              type="text"
              placeholder='{"Authorization": "Bearer ..."}'
              class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-[#cc785c] focus:border-transparent"
            />
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Body</label>
            <textarea
              v-model="form.httpBody"
              rows="3"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm font-mono focus:outline-none focus:ring-2 focus:ring-[#cc785c] focus:border-transparent"
            ></textarea>
          </div>
        </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>
            <svg
              :class="['w-4 h-4 text-gray-400 transition-transform', showAdvanced ? 'rotate-180' : '']"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
            </svg>
          </button>
          <div v-if="showAdvanced" class="space-y-4 px-4 pb-4 border-t pt-4">
            <div class="flex flex-col gap-3">
              <label class="flex items-center gap-2">
                <input
                  v-model="form.catchUp"
                  type="checkbox"
                  class="w-4 h-4 text-[#cc785c] border-gray-300 rounded focus:ring-[#cc785c]"
                />
                <span class="text-sm text-gray-700">Catch up missed executions after restart</span>
              </label>
              <label class="flex items-center gap-2">
                <input
                  v-model="form.enabled"
                  type="checkbox"
                  class="w-4 h-4 text-[#cc785c] border-gray-300 rounded focus:ring-[#cc785c]"
                />
                <span class="text-sm text-gray-700">Enabled</span>
              </label>
            </div>
            <div class="grid grid-cols-3 gap-3">
              <div>
                <label class="block text-xs text-gray-500 mb-1">Max Retries</label>
                <input
                  v-model.number="form.maxRetries"
                  type="number"
                  min="0"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#cc785c] focus:border-transparent"
                />
              </div>
              <div>
                <label class="block text-xs text-gray-500 mb-1">Retry Delay (s)</label>
                <input
                  v-model.number="form.retryDelaySeconds"
                  type="number"
                  min="1"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#cc785c] focus:border-transparent"
                />
              </div>
              <div>
                <label class="block text-xs text-gray-500 mb-1">Timeout (s)</label>
                <input
                  v-model.number="form.timeoutSeconds"
                  type="number"
                  min="1"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#cc785c] focus:border-transparent"
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Footer -->
      <div class="flex justify-end gap-2 px-6 py-4 border-t bg-gray-50 rounded-b-xl">
        <button
          class="px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 rounded-lg transition-colors"
          @click="emit('close')"
        >
          Cancel
        </button>
        <button
          :disabled="saving"
          class="px-4 py-2 bg-[#cc785c] text-white text-sm font-medium rounded-lg hover:bg-[#a9583e] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          @click="save"
        >
          {{ saving ? 'Saving...' : (isEdit ? 'Update' : 'Create') }}
        </button>
      </div>
    </div>
  </div>
</template>