<script setup>
import dayjs from 'dayjs'

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
const form = ref({
  deliveryDate: dayjs().format('YYYY-MM-DD'), // Standard: Heute
  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({})

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

  if (!form.value.deliveryDate) {
    errors.value.deliveryDate = 'Datum erforderlich'
    isValid = false
  }

  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
  }

  // Profil nur validieren, wenn Auswahl nötig und 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 Diesel
  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', icon: 'i-heroicons-exclamation-triangle' })
  } finally {
    isSubmitting.value = false
  }
}

// Hilfsfunktion für die dynamische Einheiten-Anzeige
const currentUnit = computed(() => {
  if (!form.value.service) return data.value?.units?.[0]?.symbol || 'h'
  const selectedService = data.value.services?.find(s => s.id === form.value.service)
  return selectedService?.unitSymbol || data.value?.units?.[0]?.symbol || 'h'
})

const setDeliveryDateToToday = () => {
  form.value.deliveryDate = dayjs().format('YYYY-MM-DD')
}
</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
          label="Datum der Ausführung"
          :error="errors.deliveryDate"
          required
      >
        <div class="flex items-center gap-2">
          <UInput
              v-model="form.deliveryDate"
              type="date"
              size="lg"
              icon="i-heroicons-calendar-days"
              class="flex-1"
          />
          <UButton color="gray" variant="soft" size="lg" label="Heute" @click="setDeliveryDateToToday" />
        </div>
      </UFormGroup>

      <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
            size="lg"
        />
      </UFormGroup>

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

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

      <UFormGroup
          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">{{ currentUnit }}</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" size="lg">
          <template #trailing>
            <span class="text-gray-500 text-xs">Liter</span>
          </template>
        </UInput>
      </UFormGroup>

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

    </div>

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