<script setup>
import { onMounted, ref } from "vue";
import { useSearcher, useForm, api, apiURL } from "@Services/Api";
import { apiTo, transl } from "./Module";

import Table from "@Holos/Table.vue";
import IconButton from "@Holos/Button/Icon.vue";
import PageHeader from "@Holos/PageHeader.vue";
import ConceptForm from "@App/ConceptSection.vue";
import DestroyView from "@Holos/Modal/Template/Destroy.vue";
import ModalController from "@Controllers/ModalController.js";
import EditModal from "./Modal/Edit.vue";

/** Controladores */
const Modal = new ModalController();

/** Propiedades */
const destroyModal = ref(Modal.destroyModal);
const editModal = ref(Modal.editModal);
const modelModal = ref(Modal.modelModal);

const addresses = ref([]);
const units = ref([]);

const models = ref({
  data: [],
  total: 0,
});

/** Inicializar searcher */
const searcher = useSearcher({
  url: apiTo("index"),
  filters: { paginate: true },
  onSuccess: (data) => {
    models.value = data.models;
  },
});

api.get(apiURL("directions"), {
  onSuccess: (data) => {
    addresses.value = data.models?.data || data.data || [];
  },
});

api.get(apiURL("units"), {
  onSuccess: (data) => {
    units.value = data.models?.data || data.data || [];
  },
});

/** Cargar datos iniciales */
onMounted(() => {
  searcher.search();
});

/** crear concepto */
const handleConceptCreated = async (conceptData) => {
  const form = useForm(conceptData);

  form.post(apiTo("store"), {
    onSuccess: () => {
      Notify.success(transl("create.onSuccess"));
      searcher.refresh();
    },
    onError: () => {
      Notify.error(transl("create.onError"));
    },
  });
};

const handleConceptUpdated = () => {
  searcher.refresh();
  Modal.switchEditModal();
};
</script>
<template>
  <PageHeader :title="transl('title')" />
  <ConceptForm @concept-created="handleConceptCreated" />
  <div class="mx-4 mb-4">
    <div class="bg-white rounded-lg shadow-md overflow-hidden">
      <Table
        :items="models"
        :processing="searcher.processing"
        @send-pagination="(page) => searcher.pagination(page)"
      >
        <template #head>
          <th class="px-6 py-3 text-left text-sm font-semibold" v-text="transl('direction')" />
          <th class="px-6 py-3 text-left text-sm font-semibold" v-text="transl('shortName')" />
          <th class="px-6 py-3 text-left text-sm font-semibold" v-text="transl('name')" />
          <th class="px-6 py-3 text-left text-sm font-semibold" v-text="transl('legal')" />
          <th class="px-6 py-3 text-left text-sm font-semibold" v-text="transl('article')" />
          <th class="px-6 py-3 text-left text-sm font-semibold" v-text="transl('description')" />
          <th class="px-6 py-3 text-center text-sm font-semibold w-32" v-text="$t('actions')" />
        </template>
        <template #body="{ items }">
          <tr v-for="model in items" :key="model.id" class="border-b border-gray-200 hover:bg-gray-50 transition-colors">
            <td class="px-6 py-4 text-sm text-gray-700">
              {{ model.direction?.name || "-" }}
            </td>
            <td class="px-6 py-4 text-sm text-gray-700">
              {{ model.short_name }}
            </td>
            <td class="px-6 py-4 text-sm text-gray-700">
              {{ model.name }}
            </td>
            <td class="px-6 py-4 text-sm text-gray-700">
              {{ model.legal_instrument }}
            </td>
            <td class="px-6 py-4 text-sm text-gray-700">
              {{ model.article }}
            </td>
            <td class="px-6 py-4 text-sm text-gray-700">
              {{ model.content }}
            </td>
            <td class="px-6 py-4">
              <div class="flex justify-center items-center space-x-2">
                <IconButton
                  icon="edit"
                  title="Editar"
                  @click="Modal.switchEditModal(model)"
                  outline
                />
                <IconButton
                  icon="delete"
                  title="Eliminar"
                  @click="Modal.switchDestroyModal(model)"
                  outline
                />
              </div>
            </td>
          </tr>
        </template>
        <template #empty>
          <td colspan="7" class="px-6 py-8 text-center text-gray-500 text-sm">
            {{ transl("list.empty") }}
          </td>
        </template>
      </Table>
    </div>
    <DestroyView
      title="name"
      subtitle="content"
      :model="modelModal"
      :show="destroyModal"
      :to="(id) => apiTo('destroy', { charge_concept: id })"
      @close="Modal.switchDestroyModal"
      @update="
        () => {
          const index = models.data.findIndex((m) => m.id === modelModal.id);
          if (index > -1) {
            models.data.splice(index, 1);
            models.total--;
          }
        }
      "
    />
    <EditModal
      :show="editModal"
      :model="modelModal"
      :addresses="addresses"
      :units="units"
      @close="Modal.switchEditModal"
      @updated="handleConceptUpdated"
    />
  </div>
</template>
