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

const runtimeConfig = useRuntimeConfig()
const emit = defineEmits(['success'])
const toast = useToast()

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

// Initiale Werte setzen (Quantity statt Start/EndDate)
const form = ref({
  profile: props.context.meta?.defaultProfileId || null,
  project: null,
  service: config.value?.defaults?.serviceId || null,
  quantity: config.value?.features?.timeTracking?.defaultDurationHours || 1,
  dieselUsage: 0,
  description: ''
})

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

const validate = () => {
  errors.value = {}
  let isValid = true
  const validationRules = config.value.validation || {}

  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
  }

  if (!form.value.quantity || form.value.quantity <= 0) {
    errors.value.quantity = 'Menge erforderlich'
    isValid = false
  }

  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 }
    const headers = {}
    if (props.pin) headers['x-public-pin'] = props.pin

    await $fetch(`${runtimeConfig.public.apiBase}/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
        />
      </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..."
            searchable
        />
      </UFormGroup>

      <UFormGroup
          v-if="config?.features?.timeTracking?.allowManualTime"
          label="Menge / Dauer"
          :error="errors.quantity"
          required
      >
        <UInput
            v-model="form.quantity"
            type="number"
            step="0.25"
            size="lg"
            placeholder="0.00"
        >
          <template #trailing>
            <span class="text-gray-500 text-sm pr-2">
              {{ data?.units?.[0]?.symbol || 'h' }}
            </span>
          </template>
        </UInput>
      </UFormGroup>

      <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>