<template>
  <Modal ref="modalRef" size="md">
    <template #title>
      Create a new storage {{ set === true ? 'set' : '' }}
    </template>

    <template #default="{ closeModal }">
      <FormAlert :message="error" />
      <Form @submit="onSubmit" v-model="data" :validators="validators">
        <FormField name="displayName" label="Display Name" required />
        <FormSelectField
          :options="selectOptions"
          name="type"
          label="Type"
          required
        />
        <FormField name="locationDescription" label="Location description">
          <span class="text-sm">Describe the location of this storage</span>
        </FormField>
        <FormColorField name="color" label="Color" />
        <div class="flex justify-end space-x-1">
          <button
            class="inline-flex justify-center rounded-md border border-transparent bg-green-600 py-2 px-4 text-sm font-medium text-white shadow-sm hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
            type="submit"
            @click="submitlock = true"
          >
            Submit and add another
          </button>
          <button
            class="inline-flex justify-center rounded-md border border-transparent bg-green-600 py-2 px-4 text-sm font-medium text-white shadow-sm hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
            type="submit"
          >
            Submit
          </button>
        </div>
      </Form>
    </template>
  </Modal>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { useAccessToken } from '../../composables/useAccessToken';
import { BACKEND_URL } from '../../constants';
import { StorageSetTypeName } from '../../enums/storage-set-type.enum';
import { StorageTypeName } from '../../enums/storage-type.enum';
import { BuildingListItem } from '../../interfaces/building.interfaces';
import { RoomListItem } from '../../interfaces/room.interfaces';
import {
  StorageSetListItem,
  StorageSharedType,
} from '../../interfaces/storage.interfaces';
import jfetch from '../../utils/jfetch';
import takeError from '../../utils/take-error';
import { FormSubmit, SelectOption } from '../form/form.types';
import Form from '../form/Form.vue';
import FormAlert from '../form/FormAlert.vue';
import FormField from '../form/FormField.vue';
import FormSelectField from '../form/fields/FormSelectField.vue';
import { IsRequired, MinLength } from '../form/validators';
import Modal from '../Modal.vue';
import FormColorField from '../form/fields/FormColorField.vue';

const { authHeader } = useAccessToken();
const defaults = {
  displayName: '',
  type: '',
  locationDescription: '',
  color: '#000000',
};

const modalRef = ref<InstanceType<typeof Modal>>();
const room = ref<RoomListItem>();
const building = ref<BuildingListItem>();
const set = ref<StorageSetListItem | boolean>();
const data = ref({ ...defaults });
const error = ref('');
const submitlock = ref(false);
const selectOptions = computed(() => {
  const source = set.value === true ? StorageSetTypeName : StorageTypeName;
  return Object.keys(source).reduce<SelectOption[]>(
    (list, key) => [
      ...list,
      { value: key.toString(), name: source[key as keyof typeof source] },
    ],
    []
  );
});

const validators = ref([
  {
    field: 'displayName',
    validators: [MinLength(3), IsRequired()],
  },
  {
    field: 'type',
    validators: [IsRequired()],
  },
]);

const emit = defineEmits<{
  (e: 'added', storage: StorageSharedType): void;
}>();

const reset = () => {
  data.value = { ...defaults };
};

defineExpose({
  openModal: (
    useBuilding: BuildingListItem,
    useRoom: RoomListItem,
    useSet?: StorageSetListItem | boolean
  ) => {
    room.value = useRoom;
    building.value = useBuilding;
    set.value = useSet;
    reset();
    modalRef.value?.openModal();
  },
});

const onSubmit = async (value: FormSubmit) => {
  error.value = '';

  if (!value.isValid || !room.value) return;

  const createURL = `${BACKEND_URL}/storage${
    set.value === true ? '/set' : ''
  }/room/${room.value.id}`;

  let createdStorage: StorageSharedType;
  try {
    const response = await jfetch(createURL, {
      method: 'POST',
      body: {
        ...value.formData,
        location: '0,0',
      },
      headers: authHeader.value,
    });

    createdStorage = response.data;
  } catch (e) {
    error.value = takeError(e);
    return;
  }

  // Add created storage to set
  if (set.value && typeof set.value !== 'boolean') {
    await jfetch(
      `${BACKEND_URL}/storage/set/${set.value.id}/${createdStorage.id}`,
      {
        method: 'POST',
        headers: authHeader.value,
      }
    );
  }

  emit('added', createdStorage);
  if (submitlock.value) {
    submitlock.value = false;
    return;
  }

  modalRef.value?.closeModal();
};
</script>
