<script>
  import { onMount, onDestroy } from 'svelte'
  import * as consts from 'Editor/scripts/consts'
  import * as utilities from 'Editor/scripts/utilities'
  import { importSettings } from 'Editor/scripts/import'
  import { getProjectsList, getProject, deleteProject } from 'Editor/scripts/storage'
  import { setters } from 'Editor/store'
  import { clear } from 'Editor/store/ui'
  import Modal from 'Editor/components/UI/modal'
  import FormControl from 'Editor/components/UI/form-controls/form-control'

  let modal
  let loading = false
  let projectsList = []
  let deleteConfirm
  let deleteLoading

  onMount(() => {
    createEvents()
  })
  onDestroy(() => {
    removeEvents()
  })

  function createEvents() {
    document.addEventListener(consts.EVENT_OPEN_LOAD_MODAL, handleOpenEvent)
  }
  function removeEvents() {
    document.removeEventListener(consts.EVENT_OPEN_LOAD_MODAL, handleOpenEvent)
  }
  function handleOpenEvent() {
    loading = true

    getProjectsList((data) => {
      projectsList = data
      projectsList = projectsList.sort((a, b) => (parseInt(a.lastSaved) > parseInt(b.lastSaved) ? -1 : 1))
      loading = false
      modal.show()
    })
  }
  function onDelete(e) {
    let id = e.target.dataset.id || e.target.closest('[data-id]').dataset.id
    deleteConfirm = id
  }
  function onLoad(e) {
    clear()

    let id = e.target.dataset.id || e.target.closest('[data-id]').dataset.id

    getProject(id, (data) => {
      if (data) {
        let project = importSettings(data)
        setters.setMapValues(project, true)
        setters.clearHistory()
        modal.hide()
      }
    })
  }
  function onConfirmDelete(e) {
    let id = e.target.dataset.id || e.target.closest('[data-id]').dataset.id
    deleteConfirm = undefined
    deleteLoading = id

    deleteProject(id, (success) => {
      if (!success) {
        console.error('Failed to delete project')
      }

      getProjectsList((data) => {
        projectsList = data
        projectsList = projectsList.sort((a, b) => (parseInt(a.lastSaved) > parseInt(b.lastSaved) ? -1 : 1))
        deleteLoading = undefined
      })
    })
  }
  function onCancelDelete() {
    deleteConfirm = undefined
  }
</script>

<Modal bind:this={modal} cancelButton="Close" title="Load">
  {#if !loading}
    <div class="p-3 max-h-[400px] overflow-y-auto">
      {#if !projectsList || projectsList.length === 0}
        <div class="px-3 py-2 rounded-lg bg-danger-500 bg-opacity-10">No saved image maps found.</div>
      {/if}
      {#each projectsList as project, index (project.id)}
        <div class="my-1 flex items-center rounded-xl bg-theme-500 bg-opacity-10">
          <div
            class="flex-1 flex items-center p-3 rounded-l-lg cursor-pointer btn btn-transparent"
            on:click={onLoad}
            on:keypress={onLoad}
            data-id={project.id}>
            <div class="flex-1">{project.name}</div>
            <div class="ml-2 opacity-50">
              Last edit:
              {utilities.timeSince(project.lastSaved || new Date().getTime())} ago
            </div>
          </div>
          <div class="mx-2 flex">
            {#if deleteConfirm + '' !== project.id + '' && deleteLoading + '' !== project.id + ''}
              <FormControl type="button" icon="fa-solid fa-trash" action={onDelete} id={project.id} />
            {/if}
            {#if deleteConfirm + '' === project.id + ''}
              <FormControl type="button" icon="fa-solid fa-times" action={onCancelDelete} id={project.id} />
              <FormControl type="button" danger icon="fa-solid fa-check" action={onConfirmDelete} id={project.id} />
            {/if}
            {#if deleteLoading + '' === project.id + ''}
              <div class="fa-solid fa-circle-notch fa-spin flex items-center px-3" />
            {/if}
          </div>
        </div>
      {/each}
    </div>
  {:else}
    <div class="p-4">Loading...</div>
  {/if}
</Modal>
