<script setup>
import dayjs from 'dayjs'
import { parseDate } from '@internationalized/date'

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({})

const deliveryDateValue = computed({
  get: () => {
    if (!form.value.deliveryDate) {
      return null
    }

    try {
      return parseDate(form.value.deliveryDate)
    } catch {
      return null
    }
  },
  set: (value) => {
    form.value.deliveryDate = value ? value.toString() : ''
  }
})

// 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
      v-if="props.context && props.token"
      class="overflow-hidden border-white/70 shadow-xl ring-1 ring-black/5"
      :ui="{ body: { padding: 'p-6 sm:p-8' }, header: { padding: 'p-6 sm:p-8 pb-0' }, footer: { padding: 'p-6 sm:p-8 pt-0' } }"
  >
    <template #header>
      <div class="space-y-3 text-center">
        <div class="mx-auto flex h-14 w-14 items-center justify-center rounded-2xl bg-primary/10 text-primary ring-1 ring-primary/15">
          <UIcon name="i-heroicons-clipboard-document-check" class="h-7 w-7" />
        </div>
        <div>
          <h1 class="text-xl font-semibold text-highlighted">{{ config?.ui?.title || 'Erfassung' }}</h1>
          <p v-if="config?.ui?.description" class="mt-1 text-sm text-muted">{{ config?.ui?.description }}</p>
        </div>
      </div>
    </template>

    <div class="space-y-5">
      <UAlert
          color="primary"
          variant="soft"
          icon="i-heroicons-sparkles"
          title="Schnelle Erfassung"
          description="Alle Angaben werden direkt dem passenden Workflow zugeordnet."
      />

      <UFormField
          label="Datum der Ausführung"
          :error="errors.deliveryDate"
          required
      >
        <div class="flex gap-2">
          <UPopover>
            <UButton
                color="neutral"
                variant="outline"
                size="lg"
                icon="i-heroicons-calendar-days"
                class="min-w-0 flex-1 justify-between"
            >
              <span class="truncate text-left">
                {{ form.deliveryDate ? dayjs(form.deliveryDate).format('DD.MM.YYYY') : 'Kein Datum' }}
              </span>
            </UButton>

            <template #content>
              <div class="p-2">
                <UCalendar v-model="deliveryDateValue" />
                <div class="flex justify-end border-t border-default pt-2">
                  <UButton color="neutral" variant="ghost" size="sm" @click="setDeliveryDateToToday">
                    Heute
                  </UButton>
                </div>
              </div>
            </template>
          </UPopover>

          <UButton color="neutral" variant="soft" size="lg" label="Heute" @click="setDeliveryDateToToday" />
        </div>
      </UFormField>

      <UFormField
          v-if="!context?.meta?.defaultProfileId && data?.profiles?.length > 0"
          label="Mitarbeiter"
          :error="errors.profile"
          required
      >
        <USelectMenu
            v-model="form.profile"
            :items="data.profiles"
            label-key="fullName"
            value-key="id"
            placeholder="Name auswählen..."
            size="lg"
            class="w-full"
            :search-input="{ placeholder: 'Mitarbeiter suchen...' }"
            :filter-fields="['fullName']"
        />
      </UFormField>

      <UFormField
          v-if="data?.projects?.length > 0"
          :label="config.ui?.labels?.project || 'Projekt / Auftrag'"
          :error="errors.project"
          required
      >
        <USelectMenu
            v-model="form.project"
            :items="data.projects"
            label-key="name"
            value-key="id"
            placeholder="Wählen..."
            size="lg"
            class="w-full"
            :search-input="{ placeholder: 'Projekt suchen...' }"
            :filter-fields="['name']"
        />
      </UFormField>

      <UFormField
          v-if="data?.services?.length > 0"
          :label="config?.ui?.labels?.service || 'Tätigkeit'"
          :error="errors.service"
          required
      >
        <USelectMenu
            v-model="form.service"
            :items="data.services"
            label-key="name"
            value-key="id"
            placeholder="Wählen..."
            size="lg"
            class="w-full"
            :search-input="{ placeholder: 'Tätigkeit suchen...' }"
            :filter-fields="['name']"
        />
      </UFormField>

      <UFormField
          label="Menge / Dauer"
          :error="errors.quantity"
          required
      >
        <UInput
            v-model="form.quantity"
            type="number"
            step="0.25"
            size="lg"
            placeholder="0.00"
            class="w-full"
        >
          <template #trailing>
            <span class="pr-2 text-sm text-muted">{{ currentUnit }}</span>
          </template>
        </UInput>
      </UFormField>

      <UFormField
          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" class="w-full">
          <template #trailing>
            <span class="text-xs text-muted">Liter</span>
          </template>
        </UInput>
      </UFormField>

      <UFormField :label="config?.ui?.labels?.description || 'Notiz / Vorkommnisse'">
        <UTextarea v-model="form.description" :rows="4" autoresize class="w-full" placeholder="Optional..." />
      </UFormField>

    </div>

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