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

const props = defineProps<{
  modelValue: boolean;
  entry?:  null;
}>();

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

const { create, update } = useStaffTime();

// v-model für das Modal
const show = computed({
  get: () => props.modelValue,
  set: (v: boolean) => emit("update:modelValue", v),
});

// 🧱 Lokale reactive Kopie, die beim Öffnen aus props.entry befüllt wird
const local = reactive<{
  id?: string;
  description: string;
  started_at: string;
  stopped_at: string | null;
  type: string;
}>({
  id: "",
  description: "",
  started_at: dayjs().startOf("hour").format("YYYY-MM-DDTHH:mm"),
  stopped_at: dayjs().add(1, "hour").format("YYYY-MM-DDTHH:mm"),
  type: "work",
});

// 📡 Wenn das Modal geöffnet wird, Entry-Daten übernehmen
watch(
    () => props.entry,
    (val) => {
      if (val) {
        Object.assign(local, {
          id: val.id,
          description: val.description || "",
          started_at: dayjs(val.started_at).format("YYYY-MM-DDTHH:mm"),
          stopped_at: val.stopped_at
              ? dayjs(val.stopped_at).format("YYYY-MM-DDTHH:mm")
              : dayjs(val.started_at).add(1, "hour").format("YYYY-MM-DDTHH:mm"),
          type: val.type || "work",
        });
      } else {
        Object.assign(local, {
          id: "",
          description: "",
          started_at: dayjs().startOf("hour").format("YYYY-MM-DDTHH:mm"),
          stopped_at: dayjs().add(1, "hour").format("YYYY-MM-DDTHH:mm"),
          type: "work",
        });
      }
    },
    { immediate: true }
);

const loading = ref(false);

async function handleSubmit() {
  loading.value = true;
  try {
    const payload = {
      description: local.description,
      started_at: dayjs(local.started_at).toISOString(),
      stopped_at: local.stopped_at ? dayjs(local.stopped_at).toISOString() : null,
      type: local.type,
    };

    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">
        <UFormGroup label="Beschreibung" name="description">
          <UInput v-model="local.description" placeholder="Was wurde gemacht?" />
        </UFormGroup>

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

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

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