<script setup>
import {ref} from "vue";
import FormModal from "../../../components/Modal/FormModal.vue";

const emit = defineEmits(['close', 'directoryCreated']);

const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  maxWidth: {
    type: String,
    default: '2xl',
  },
  closeable: {
    type: Boolean,
    default: true,
  },
  currentDirectory: {
    type: Object,
    default: () => ({id: null, name: null}),
  },
});

const close = () => {
  form.value.name = null;
  emit('close');
};

const form = ref({
  name: null,
})

const createDirectory = async () => {
  const response = await fetch(`${window.daylight.apiBase}/media/directories`, {
    method: 'POST',
    body: JSON.stringify({
      parent_id: props.currentDirectory?.id,
      name: form.value.name
    }),
    headers: {
      'Content-Type': 'application/json',
      'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
    },
  }).then(res => {
    if (!res.ok) {
      throw new Error('Network response was not ok');
    }

    return res.json();
  });

  emit('directoryCreated', response)

  close()
}

</script>

<template>
  <FormModal :show="show" :max-width="maxWidth" :closeable="closeable" @close="close">
    <template #title>
      Create directory
    </template>

    <template #content>
      <div class="w-full">
        <div class="mb-2 grid grid-cols-3 w-full items-center">
          <label class="block font-medium text-sm text-gray-700">
            Name
          </label>

          <input
              type="text"
              class="col-span-2 w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm text-black text-sm"
              placeholder="Directory name.."
              required
              v-model="form.name"
          >
        </div>
      </div>

    </template>

    <template #footer>
      <button
          @click.prevent="close"
          class="mr-2 py-2.5 px-4 border rounded-md text-sm leading-5 font-medium focus:outline-none focus:border-blue-300 focus:shadow-outline-blue transition duration-150 ease-in-out bg-white text-sky-600 hover:opacity-75 border-sky-600"
      >
        Cancel
      </button>

      <button
          @click.prevent="createDirectory"
          :disabled="!form.name || form.name.trim().length === 0"
          :class="{ 'opacity-50': !form.name || form.name.trim().length === 0 }"
          class="py-2.5 px-4 border rounded-md text-sm leading-5 font-medium focus:outline-none focus:border-blue-300 focus:shadow-outline-blue transition duration-150 ease-in-out bg-sky-600 text-white hover:bg-sky-700 border-sky-600 text-sm"
      >
        Create directory
      </button>
    </template>
  </FormModal>
</template>
