<script setup>
import dayjs from 'dayjs'

const props = defineProps({
  context: { type: Object, required: true },
  token: { type: String, required: true },
  pin: { type: String, default: '' }
})

const emit = defineEmits(['success'])
const { $api } = useNuxtApp()
const toast = useToast()

const config = computed(() => props.context.config)
const data = computed(() => props.context.data)

// Initiale Werte setzen
const form = ref({
  profile: props.context.meta?.defaultProfileId || null,
  project: null,
  service: config.value?.defaults?.serviceId || null,
  // Wenn manualTime erlaubt, setze Startzeit auf jetzt, sonst null (wird im Backend gesetzt)
  startDate: config.value?.features?.timeTracking?.allowManualTime ? new Date() : null,
  endDate: config.value?.features?.timeTracking?.allowManualTime ? dayjs().add(1, 'hour').toDate() : null,
  dieselUsage: 0,
  description: ''
})

const isSubmitting = ref(false)
const errors = ref({})

// Validierung basierend auf JSON Config
const validate = () => {
  errors.value = {}
  let isValid = true
  const validationRules = config.value.validation || {}

  // Standard-Validierung
  if (!form.value.project && data.value.projects?.length > 0) {
    errors.value.project = 'Pflichtfeld'
    isValid = false
  }

  if (!form.value.service && data.value.services?.length > 0) {
    errors.value.service = 'Pflichtfeld'
    isValid = false
  }

  // Profil nur validieren, wenn Auswahl möglich ist
  if (!form.value.profile && data.value.profiles?.length > 0 && !props.context.meta.defaultProfileId) {
    errors.value.profile = 'Bitte Mitarbeiter wählen'
    isValid = false
  }

  // Feature: Agriculture
  if (config.value.features?.agriculture?.showDieselUsage && validationRules.requireDiesel) {
    if (!form.value.dieselUsage || form.value.dieselUsage <= 0) {
      errors.value.diesel = 'Dieselverbrauch erforderlich'
      isValid = false
    }
  }

  return isValid
}

const submit = async () => {
  if (!validate()) return

  isSubmitting.value = true
  try {
    const payload = { ...form.value }

    // Headers vorbereiten (PIN mitsenden!)
    const headers = {}
    if (props.pin) headers['x-public-pin'] = props.pin

    // An den Submit-Endpunkt senden (den müssen wir im Backend noch bauen!)
    await $fetch(`http://localhost:3100/workflows/submit/${props.token}`, {
      method: 'POST',
      body: payload,
      headers
    })

    emit('success')
  } catch (e) {
    console.error(e)
    toast.add({ title: 'Fehler beim Speichern', color: 'red' })
  } finally {
    isSubmitting.value = false
  }
}
</script>

<template>
  <UCard :ui="{ body: { padding: 'p-6 sm:p-8' } }" v-if="props.context && props.token">
    <template #header>
      <div class="text-center">
        <h1 class="text-xl font-bold text-gray-900">{{ config?.ui?.title || 'Erfassung' }}</h1>
        <p v-if="config?.ui?.description" class="text-sm text-gray-500 mt-1">{{ config?.ui?.description }}</p>
      </div>
    </template>

    <div class="space-y-5">

      <UFormGroup
          v-if="!context?.meta?.defaultProfileId && data?.profiles?.length > 0"
          label="Mitarbeiter"
          :error="errors.profile"
          required
      >
        <USelectMenu
            v-model="form.profile"
            :options="data.profiles"
            option-attribute="fullName"
            value-attribute="id"
            placeholder="Name auswählen..."
            searchable
            searchable-placeholder="Suchen..."
        />
      </UFormGroup>

      <UFormGroup
          v-if="data?.projects?.length > 0"
          :label="config.ui?.labels?.project || 'Projekt'"
          :error="errors.project"
          required
      >
        <USelectMenu
            v-model="form.project"
            :options="data.projects"
            option-attribute="name"
            value-attribute="id"
            placeholder="Wählen..."
            searchable
        />
      </UFormGroup>

      <UFormGroup
          v-if="data?.services?.length > 0"
          :label="config?.ui?.labels?.service || 'Leistung'"
          :error="errors.service"
          required
      >
        <USelectMenu
            v-model="form.service"
            :options="data.services"
            option-attribute="name"
            value-attribute="id"
            placeholder="Wählen..."
        />
      </UFormGroup>

      <div v-if="config?.features?.timeTracking?.allowManualTime" class="grid grid-cols-2 gap-3">
        <UFormGroup label="Start">
          <input
              type="datetime-local"
              class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-primary-600 sm:text-sm sm:leading-6 px-2"
              :value="dayjs(form.startDate).format('YYYY-MM-DDTHH:mm')"
              @input="e => form.startDate = new Date(e.target.value)"
          />
        </UFormGroup>
        <UFormGroup label="Dauer (Stunden)">
          <input
              type="number"
              step="0.25"
              placeholder="z.B. 1.5"
              class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-primary-600 sm:text-sm sm:leading-6 px-2"
              @input="e => form.endDate = dayjs(form.startDate).add(parseFloat(e.target.value), 'hour').toDate()"
          />
        </UFormGroup>
        <UFormGroup label="Ende" class="col-span-2">
          <input
              type="datetime-local"
              class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-primary-600 sm:text-sm sm:leading-6 px-2"
              :value="dayjs(form.endDate).format('YYYY-MM-DDTHH:mm')"
              @input="e => form.endDate = new Date(e.target.value)"
          />
        </UFormGroup>
      </div>

      <UFormGroup
          v-if="config?.features?.agriculture?.showDieselUsage"
          label="Dieselverbrauch"
          :error="errors.diesel"
          :required="config?.validation?.requireDiesel"
      >
        <UInput v-model="form.dieselUsage" type="number" step="0.1" placeholder="0.0">
          <template #trailing>
            <span class="text-gray-500 text-xs">Liter</span>
          </template>
        </UInput>
      </UFormGroup>

      <UFormGroup :label="config?.ui?.labels?.description || 'Notiz'">
        <UTextarea v-model="form.description" :rows="3" />
      </UFormGroup>

    </div>

    <template #footer>
      <UButton
          block
          size="xl"
          :loading="isSubmitting"
          @click="submit"
          :label="config?.ui?.submitButtonText || 'Speichern'"
      />
    </template>
  </UCard>
</template>