<script setup lang="ts">
import dayjs from "dayjs";

const props = defineProps<{
  modelValue: boolean;
  entry?: any | null;
  users: any[];
  canSelectUser: boolean;
  defaultUserId: string;
}>();

const emit = defineEmits(["update:modelValue", "saved"]);

const { create, update } = useStaffTime();

const show = computed({
  get: () => props.modelValue,
  set: (v: boolean) => emit("update:modelValue", v),
});

// 🌈 Typen
const typeOptions = [
  { label: "Arbeitszeit", value: "work" },
  { label: "Urlaub", value: "vacation" },
  { label: "Krankheit", value: "sick" },
  { label: "Feiertag", value: "holiday" },
];

// Lokaler State
const local = reactive({
  id: "",
  user_id: "",               // 👈 Mitarbeiter
  description: "",
  started_at: "",
  stopped_at: "",
  type: "work",
  vacation_reason: "",
  sick_reason: "",
});

// 📡 ENTRY —> LOCAL
watch(
    () => props.entry,
    (val) => {
      if (val) {
        Object.assign(local, {
          id: val.id,
          user_id: val.user_id, // 👈 Mitarbeiter vorbelegen
          description: val.description || "",
          type: val.type || "work",

          started_at:
              val.type === "vacation"
                  ? dayjs(val.started_at).format("YYYY-MM-DD")
                  : dayjs(val.started_at).format("YYYY-MM-DDTHH:mm"),

          stopped_at:
              val.type === "vacation"
                  ? dayjs(val.stopped_at).format("YYYY-MM-DD")
                  : dayjs(val.stopped_at).format("YYYY-MM-DDTHH:mm"),

          vacation_reason: val.vacation_reason || "",
          sick_reason: val.sick_reason || "",
        });
      } else {
        Object.assign(local, {
          id: "",
          user_id: props.defaultUserId, // 👈 Neuer Eintrag → aktueller Nutzer
          description: "",
          type: "work",
          started_at: dayjs().format("YYYY-MM-DDTHH:mm"),
          stopped_at: dayjs().add(1, "hour").format("YYYY-MM-DDTHH:mm"),
          vacation_reason: "",
          sick_reason: "",
        });
      }
    },
    { immediate: true }
);

const loading = ref(false);

async function handleSubmit() {
  loading.value = true;
  try {
    const payload: any = {
      user_id: local.user_id,   // 👈 immer senden
      type: local.type,
    };

    if (local.type === "vacation") {
      payload.started_at = dayjs(local.started_at).startOf("day").toISOString();
      payload.stopped_at = dayjs(local.stopped_at).endOf("day").toISOString();
      payload.vacation_reason = local.vacation_reason;
    } else {
      payload.started_at = dayjs(local.started_at).toISOString();
      payload.stopped_at = local.stopped_at
          ? dayjs(local.stopped_at).toISOString()
          : null;
      payload.description = local.description;

      if (local.type === "sick") {
        payload.sick_reason = local.sick_reason;
      }
    }

    if (local.id) {
      await update(local.id, payload);
    } else {
      await create(payload);
    }

    emit("saved");
    show.value = false;
  } finally {
    loading.value = false;
  }
}
</script>


<template>
  <UModal v-model="show" :ui="{ width: 'w-full sm:max-w-md' }" :key="local.id || 'new'">
    <UCard>
      <template #header>
        <div class="font-semibold text-lg">
          {{ local.id ? "Zeit bearbeiten" : "Neue Zeit erfassen" }}
        </div>
      </template>

      <UForm @submit.prevent="handleSubmit" class="space-y-4">

        <!-- 👥 Mitarbeiter-Auswahl -->
        <UFormGroup label="Mitarbeiter" v-if="props.canSelectUser">
          <USelectMenu
              v-model="local.user_id"
              :options="props.users.map(u => ({
              label: u.full_name || u.email,
              value: u.user_id
            }))"
              placeholder="Mitarbeiter wählen"
              option-attribute="label"
              value-attribute="value"
          />
        </UFormGroup>

        <!-- TYPE -->
        <UFormGroup label="Typ">
          <USelect v-model="local.type" :options="typeOptions" />
        </UFormGroup>

        <!-- VACATION -->
        <template v-if="local.type === 'vacation'">
          <UFormGroup label="Urlaubsgrund">
            <UInput v-model="local.vacation_reason" />
          </UFormGroup>

          <UFormGroup label="Start (Tag)">
            <UInput v-model="local.started_at" type="date" />
          </UFormGroup>

          <UFormGroup label="Ende (Tag)">
            <UInput v-model="local.stopped_at" type="date" />
          </UFormGroup>
        </template>

        <!-- SICK -->
        <template v-else-if="local.type === 'sick'">
          <UFormGroup label="Krankheitsgrund">
            <UInput v-model="local.sick_reason" />
          </UFormGroup>

          <UFormGroup label="Start (Tag)">
            <UInput v-model="local.started_at" type="date" />
          </UFormGroup>

          <UFormGroup label="Ende (Tag)">
            <UInput v-model="local.stopped_at" type="date" />
          </UFormGroup>
        </template>

        <!-- WORK / OTHER -->
        <template v-else>
          <UFormGroup label="Beschreibung">
            <UInput v-model="local.description" placeholder="Was wurde gemacht?" />
          </UFormGroup>

          <UFormGroup label="Startzeit">
            <UInput v-model="local.started_at" type="datetime-local" />
          </UFormGroup>

          <UFormGroup label="Endzeit">
            <UInput v-model="local.stopped_at" type="datetime-local" />
          </UFormGroup>
        </template>

        <!-- ACTIONS -->
        <div class="flex justify-end gap-2 mt-4">
          <UButton color="gray" label="Abbrechen" @click="show = false" />
          <UButton color="primary" :loading="loading" type="submit" label="Speichern" />
        </div>
      </UForm>
    </UCard>
  </UModal>
</template>

