<template>
  <div class="relative" :class="{ 'overflow-hidden max-h-[80vh]': isLoading }">
    <div class="sticky bg-white z-150 py-4 -mt-6 -mx-8 px-8 border-b border-gray-200 mb-4">
      <div class="grid lg:grid-cols-2">
        <div class="flex items-center text-sm gap-4">
          <div v-if="currentDirectory" class="flex items-center">
            <button v-if="currentDirectory.parent_id" @click.prevent="changeCurrentDirectory(currentDirectory?.parent_id)">
              <svg class="w-4 h-4" data-slot="icon" fill="none" stroke-width="1.5" stroke="currentColor"
                   viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                <path stroke-linecap="round" stroke-linejoin="round" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
              </svg>
            </button>

            <button v-else @click.prevent="changeCurrentDirectory(null)">
              <svg class="w-4 h-4" data-slot="icon" fill="none" stroke-width="1.5" stroke="currentColor"
                   viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                <path stroke-linecap="round" stroke-linejoin="round" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
              </svg>
            </button>
          </div>

          <h1 class="text-xl leading-loose font-medium" v-if="currentDirectory">{{ currentDirectory.name }}</h1>
          <h1 class="text-xl leading-loose font-medium" v-else>{{ __('daylight::media.media') }}</h1>
        </div>

        <div class="flex items-center lg:justify-end text-sm gap-4">
          <SecondaryButton @click.prevent="showCreateDirectoryModal = !showCreateDirectoryModal">
            {{ __('daylight::media.create_directory') }}
          </SecondaryButton>

          <PrimaryButton @click.prevent="uploadFiles">
            {{ __('daylight::media.upload_files') }}
          </PrimaryButton>
        </div>
      </div>
    </div>

    <div>
      <CreateDirectoryModal
          :show="showCreateDirectoryModal"
          :currentDirectory="currentDirectory"
          @close="showCreateDirectoryModal = false"
          @directoryCreated="fetchData(currentPage, $event.parent_id ? $event.parent_id : null)"
      />

      <EmptyState v-if="directories.length === 0 && files.data?.length === 0"/>

      <Directories
          :selectable="selectable"
          :directories="directories"
          @changeCurrentDirectory="changeCurrentDirectory"
          @directoryUpdated="fetchData(currentPage, $event.parent_id ? $event.parent_id : null)"
          @directoryDeleted="fetchData(currentPage, currentDirectory?.id ? currentDirectory?.id : null)"
      />

      <hr class="my-8 border-gray-200" v-if="directories.length > 0 && files.data.length > 0">

      <Files
          :files="files"
          :selectable="selectable"
          :selectedItems="selectedItems"
          @changePage="changePage"
          @fileDeleted="fetchData(currentPage, currentDirectory?.id ? currentDirectory?.id : null)"
          @selectFile="selectFile"
      />
    </div>

    <template v-if="selectable">
      <div
          class="sticky bottom-0 bg-white border-t border-gray-300 -mx-8 px-8 -mb-4 py-4 flex items-center justify-between z-50">
        <p class="text-sm text-gray-500">{{ selectedItems.length }} item(s) selected</p>
        <div class="flex items-center justify-end gap-4">
          <SecondaryButton @click.prevent="$emit('close')">{{ __('daylight::general.cancel') }}</SecondaryButton>
          <PrimaryButton @click.prevent="submitSelectedFiles">{{ __('daylight::general.select') }}</PrimaryButton>
        </div>
      </div>
    </template>

    <Loader v-show="isLoading" />
  </div>
</template>

<script setup>
import {onMounted, ref, watch} from "vue";
import EmptyState from "./components/EmptyState.vue";
import Directories from "./components/Directories.vue";
import Files from "./components/Files.vue";
import SecondaryButton from "../../components/Buttons/SecondaryButton.vue";
import PrimaryButton from "../../components/Buttons/PrimaryButton.vue";
import CreateDirectoryModal from "./components/CreateDirectoryModal.vue";
import {openUploadModal} from "@bytescale/upload-widget-vue";
import {useRoute, useRouter} from "vue-router";
import Loader from "./components/Loader.vue";

const files = ref({})
const directories = ref([]);
const currentDirectory = ref(null);
const currentPage = ref(1);
const isLoading = ref(true)

const router = useRouter();
const route = useRoute();

const props = defineProps({
  singleFile: {
    type: Boolean,
    default: false
  },
  selectable: {
    type: Boolean,
    default: false
  },
  active: {
    type: Array,
    default: () => []
  },
})

const selectedItems = ref(props.active)

const emit = defineEmits(['filesSelected'])

const showCreateDirectoryModal = ref(false)

const changePage = (page) => {
  fetchData(page);

  router.push({
    query: {
      directory: currentDirectory.value?.id ?? null,
      page: page
    }
  })

  window.scrollTo(0, 0);
}

const changeCurrentDirectory = (directoryId = null) => {
  fetchData(1, directoryId);

  router.push({
    path: '/', query: {
      directory: directoryId,
      page: 1
    }
  })

  window.scrollTo(0, 0);
}

const selectFile = (file) => {
  if (props.singleFile) {
    selectedItems.value = [
      {
        id: file.id,
        name: file.name,
        handle: file.handle,
        type: file.type,
        size: file.size,
      }
    ]
    return
  }

  // Check if file.id is already in selectedItems
  const index = selectedItems.value.findIndex((item) => item.id === file.id)

  if (index === -1) {
    selectedItems.value.push({
      id: file.id,
      name: file.name,
      handle: file.handle,
      type: file.type,
      size: file.size,
    })
  } else {
    selectedItems.value.splice(index, 1)
  }
}

const submitSelectedFiles = () => {
  emit('filesSelected', selectedItems.value)
}

const options = {
  apiKey: window.daylight.publicKey,
  showFinishButton: true,
  path: {
    folderPath: `${window.daylight.cdnDirectory}${currentDirectory.value ? '/' + currentDirectory.value.slug : ''}`,
    fileNameFallback: '{ORIGINAL_FILE_NAME}-{UNIQUE_DIGITS_6}{ORIGINAL_FILE_EXT}',
  },
  editor: {
    images: {
      crop: false,
    }
  },
  maxFileCount: 50,
};

const uploadFiles = async (event) => {
  console.log(options);

  openUploadModal({
    event,
    options,
    onComplete: async (uploadedFiles) => {
      await fetch(`${window.daylight.apiBase}/media`, {
        method: 'POST',
        body: JSON.stringify({
          currentDirectory: currentDirectory.value?.id,
          files: uploadedFiles
        }),
        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();
      });

      await fetchData(
          currentPage.value,
          currentDirectory.value?.id ? currentDirectory.value?.id : null
      )

      if (props.selectable) {
        selectFile(data[0])
      }
    }
  })
}


onMounted(async () => {
  await router.isReady();

  currentPage.value = parseInt(route.query.page) || 1;
  currentDirectory.value = route.query.directory ? { id: route.query.directory } : null;

  fetchData(
      route.query.page ?? 1,
      currentDirectory.value?.id ?? null
  );
});

watch(() => route.query, async (query) => {
  currentPage.value = parseInt(route.query.page) || 1;
  currentDirectory.value = route.query.directory ? { id: route.query.directory } : null;
})

const fetchData = async (page = 1, directory = null) => {
  isLoading.value = true;
  currentPage.value = page

  try {
    const response = await fetch(`${window.daylight.apiBase}/media?page=${page}${directory ? `&directory=${directory}` : ''}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
      },
    });

    if (!response.ok) {
      throw new Error('Network response was not ok');
    }

    const data = await response.json();

    files.value = data.files || [];
    directories.value = data.directories || [];
    currentDirectory.value = data.currentDirectory || null

    isLoading.value = false;
  } catch (error) {
    console.error('Error fetching media data:', error);
  }
};

</script>