<template>
  <q-card class="fit row justify-start content-center items-center">
    <q-card-section class="fit row justify-start content-center items-center">
      <IsoDateInput
        v-model="job.start"
        class="col-xs-12 col-sm-6 q-pa-sm"
        label="Beginn"
        type="datetime"
        :rules="[notEmpty]"
      />
      <IsoDateInput
        v-model="job.end"
        class="col-xs-12 col-sm-6 q-pa-sm"
        label="Ende"
        type="datetime"
        :rules="[notEmpty, isAfterDate]"
      />
      <q-select
        v-model="job.type"
        filled
        use-input
        label="Dienstart"
        input-debounce="0"
        class="col-xs-12 col-sm-6 q-pa-sm"
        :options="jobtypes"
        option-label="name"
        option-value="id"
        map-options
        clearable
        :rules="[notEmpty]"
      />
      <q-input
        v-model="job.required_services"
        filled
        class="col-xs-12 col-sm-6 q-pa-sm"
        label="Dienstanzahl"
        type="number"
        :rules="[notEmpty]"
      />
      <q-input
        v-model="job.comment"
        class="col-12 q-pa-sm"
        label="Beschreibung"
        type="textarea"
        filled
      />
    </q-card-section>
    <q-card-actions>
      <q-btn label="Schicht löschen" color="negative" :disabled="canDelete" @click="removeJob" />
    </q-card-actions>
  </q-card>
</template>

<script lang="ts">
import { defineComponent, computed, onBeforeMount, PropType } from 'vue';
import { IsoDateInput } from '@flaschengeist/api/components';
import { notEmpty } from '@flaschengeist/api';
import { useEventStore } from '../../store';

export default defineComponent({
  name: 'JobSlot',
  components: { IsoDateInput },
  props: {
    modelValue: {
      required: true,
      type: Object as PropType<FG.Job>,
    },
    canDelete: {
      type: Boolean,
      default: false,
    },
  },
  emits: {
    'remove-job': () => true,
    'update:modelValue': (job: FG.Job) => !!job,
  },
  setup(props, { emit }) {
    const store = useEventStore();

    onBeforeMount(() => store.getJobTypes());

    const jobtypes = computed(() => store.jobTypes);

    const job = new Proxy(props.modelValue, {
      get(target, prop) {
        if (typeof prop === 'string') {
          return (props.modelValue as unknown as Record<string, unknown>)[prop];
        }
      },
      set(obj, prop, value) {
        if (typeof prop === 'string') {
          // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
          emit('update:modelValue', Object.assign({}, props.modelValue, { [prop]: value }));
        }
        return true;
      },
    });

    function removeJob() {
      emit('remove-job');
    }

    function isAfterDate(val: Date) {
      return props.modelValue.start < val || 'Ende muss hinter dem Start liegen';
    }

    return {
      job,
      jobtypes,
      removeJob,
      notEmpty,
      isAfterDate,
    };
  },
});
</script>

<style></style>
