<script setup lang="ts">
// Components
import Dialog from '~/components/pub/my-ui/modal/dialog.vue'
import Header from '~/components/pub/my-ui/nav-header/prep.vue'
import RecordConfirmation from '~/components/pub/my-ui/confirmation/record-confirmation.vue'
import AppDivisionList from '~/components/app/division/list.vue'
import AppDivisionEntryForm from '~/components/app/division/entry-form.vue'

// Helpers
import { usePaginatedList } from '~/composables/usePaginatedList'
import { toast } from '~/components/pub/ui/toast'

// Types
import { ActionEvents, type HeaderPrep } from '~/components/pub/my-ui/data/types'
import { DivisionSchema, type DivisionFormData } from '~/schemas/division.schema'
import type { Division } from '~/models/division'
import type { TreeItem } from '~/models/_base'

// Handlers
import {
  recId,
  recAction,
  recItem,
  isReadonly,
  isProcessing,
  isFormEntryDialogOpen,
  isRecordConfirmationOpen,
  onResetState,
  handleActionSave,
  handleActionEdit,
  handleActionRemove,
  handleCancelForm,
} from '~/handlers/division.handler'

// Services
import { getList, getDetail, getValueTreeItems } from '~/services/division.service'

const divisionsTrees = ref<TreeItem[]>([])
const title = ref('')

const {
  data,
  isLoading,
  paginationMeta,
  searchInput,
  handlePageChange,
  handleSearch,
  fetchData: getDivisionList,
} = usePaginatedList({
  fetchFn: async (params: any) => {
    const result = await getList({
      search: params.search,
      sort: 'createdAt:asc',
      'page-number': params['page-number'] || 0,
      'page-size': params['page-size'] || 10,
      includes: 'parent,childrens',
    })
    return { success: result.success || false, body: result.body || {} }
  },
  entityName: 'division',
})

const headerPrep: HeaderPrep = {
  title: 'Divisi',
  icon: 'i-lucide-box',
  refSearchNav: {
    placeholder: 'Cari (min. 3 karakter)...',
    minLength: 3,
    debounceMs: 500,
    showValidationFeedback: true,
    onInput: (value: string) => {
      searchInput.value = value
    },
    onClick: () => {},
    onClear: () => {},
  },
  addNav: {
    label: 'Tambah',
    icon: 'i-lucide-plus',
    onClick: () => {
      recAction.value = ''
      recItem.value = null
      recId.value = 0
      isFormEntryDialogOpen.value = true
      isReadonly.value = false
    },
  },
}

provide('rec_id', recId)
provide('rec_action', recAction)
provide('rec_item', recItem)
provide('table_data_loader', isLoading)

const getCurrentDivisionDetail = async (id: number | string) => {
  const result = await getDetail(id)
  if (result.success) {
    const currentValue = result.body?.data || {}
    recItem.value = currentValue
    isFormEntryDialogOpen.value = true
  }
}

// Watch for row actions when recId or recAction changes
watch([recId, recAction], () => {
  switch (recAction.value) {
    case ActionEvents.showDetail:
      if (recItem.value.code.length > 0) {
        navigateTo({
          name: 'org-src-division-id',
          params: {
            id: recItem.value.code,
          },
        })

        recAction.value = ''
        recItem.value = null
        recId.value = 0
        isFormEntryDialogOpen.value = false
        isReadonly.value = false
      }
      break
    case ActionEvents.showEdit:
      getCurrentDivisionDetail(recItem.value.code)
      title.value = 'Edit Divisi'
      isReadonly.value = false
      break
    case ActionEvents.showConfirmDelete:
      isRecordConfirmationOpen.value = true
      break
  }
})

watch(
  () => data.value,
  async () => {
    if (!data.value) return
    const result = await getList({
      'page-size': 100,
      'only-have-children': false,
      includes: 'parent,childrens',
    })
    if (result.success) {
      const currentData = result.body.data || []
      const normalizedData = currentData.filter((division: Division) => !division.parent_id)
      divisionsTrees.value = getValueTreeItems(normalizedData, true)
    }
  },
)

onMounted(async () => {
  await getDivisionList()
})
</script>

<template>
  <Header
    v-model="searchInput"
    :prep="headerPrep"
    :ref-search-nav="headerPrep.refSearchNav"
    @search="handleSearch"
  />

  <AppDivisionList
    :data="data"
    :pagination-meta="paginationMeta"
    @page-change="handlePageChange"
  />

  <Dialog
    v-model:open="isFormEntryDialogOpen"
    :title="!!recItem ? title : 'Tambah Divisi'"
    size="lg"
    prevent-outside
    @update:open="
      (value: any) => {
        onResetState()
        isFormEntryDialogOpen = value
      }
    "
  >
    <AppDivisionEntryForm
      :schema="DivisionSchema"
      :divisions="divisionsTrees"
      :values="recItem"
      :is-loading="isProcessing"
      :is-readonly="isReadonly"
      @submit="
        (values: DivisionFormData | Record<string, any>, resetForm: () => void) => {
          // console.log(values)
          if (recItem?.code.length > 0) {
            handleActionEdit(recItem.code, values, getDivisionList, resetForm, toast)
            return
          }
          handleActionSave(values, getDivisionList, resetForm, toast)
        }
      "
      @cancel="handleCancelForm"
    />
  </Dialog>

  <!-- Record Confirmation Modal -->
  <RecordConfirmation
    v-model:open="isRecordConfirmationOpen"
    action="delete"
    :record="recItem"
    @confirm="() => handleActionRemove(recItem.code, getDivisionList, toast)"
    @cancel=""
  >
    <template #default="{ record }">
      <div class="text-sm">
        <p>
          <strong>ID:</strong>
          {{ record?.id }}
        </p>
        <p v-if="record?.name">
          <strong>Nama:</strong>
          {{ record.name }}
        </p>
        <p v-if="record?.code">
          <strong>Kode:</strong>
          {{ record.code }}
        </p>
      </div>
    </template>
  </RecordConfirmation>
</template>
