<script setup lang="ts">
import {reactive, ref, watch} from "vue";
import Table from "@partials/Table.vue";
import ConfirmDelete from "@partials/dialogs/ConfirmDelete.vue";
import {show_page} from "@/composables/content/show/show_page.ts";
import ShowForm from "@partials/show/ShowForm.vue";
import {baseShow, type Show} from "@models/show/show";

const {items, listData, headers, selected, loading, search, getItems, editItem, deleteItem} = show_page()

let showSelected = ref(baseShow());
const bulk = ref({
  state: false,
  items: [] as Show[],
})
const dialog = reactive({
  open: false,
  type: '',
  title: '',
  text: ''
})

const openDialog = (type, title: string = '', text: string = '') => {
  dialog.open = true
  dialog.type = type
  dialog.title = title
  dialog.text = text
}

const edit = (showSelectedFromUser) => {
  return showSelected.value = {...showSelectedFromUser}
};

const create = () => {
  showSelected.value = baseShow();
  showSelected.value.id = 0
}

const saveItem = (item) => {
  const saved = editItem(item)
  closeDialog()
}

const cancel = (item) => {
  let deleteMessage = 'Vuoi cancellare lo show selezionato?'
  if(bulk.value.state)  deleteMessage = 'Vuoi cancellare gli show selezionati?'
  bulk.value.items = item
  showSelected.value = item
  openDialog(
      'delete',
      'Cancella',
      deleteMessage
  )
}

const confirmDelete = (confirm) => {
  if (confirm) {
    const showIds = bulk.value.items.map(item => item.id)
    deleteItem(showIds)
  }
  closeDialog()
}

const closeDialog = () => {
  dialog.open = false
  resetItemEdited()
}

const updateSearch = (text) => {
  search.value = text
}

const resetItemEdited = () => {
  showSelected.value = baseShow()
}

watch(search, (newValue, oldValue) => {
  const options = {...listData};
  getItems(options)
})

</script>

<template>
  <ShowForm
      v-if="showSelected.id !== null && !dialog.open"
      :show="showSelected"
      @go-back="resetItemEdited"
  />
  <Table
      v-else
      :headers="headers"
      v-model:selected="selected"
      v-model:search="search"
      :list-data="listData"
      :items="items"
      :loading="loading"
      :get-items="getItems"
      :actions="true"
      :show-select="true"
      @update-table="getItems"
      @update-search="updateSearch"
      @delete-item="cancel"
      @edit-item="edit"
  >
    <template v-slot:header-buttons>
      <v-btn color="primary" @click="create">
        Crea una nuova trasmissione
      </v-btn>
    </template>
    <template v-slot:dialog>
      <v-dialog v-model="dialog.open">
        <ConfirmDelete
            v-if="dialog.type === 'delete'"
            :title="dialog.title"
            :text="dialog.text"
            :bulk="bulk.state"
            @confirm="confirmDelete"
            @after-leave="closeDialog"
        />
      </v-dialog>
    </template>
  </Table>
</template>