<script setup>
import { onMounted, ref } from "vue";
import { useSearcher, useForm } 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 AddressForm from "@App/AddressSection.vue";
import Editview from "@Holos/Modal/Edit.vue";
import DestroyView from "@Holos/Modal/Template/Destroy.vue";
import ModalController from "@Controllers/ModalController.js";

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

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

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

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

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

const handleAddressCreated = async (address) => {
  const form = useForm({
    name: address.name,
  });

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

const handleAddressUpdated = async () => {
  const form = useForm({
    name: modelModal.value.name,
  });

  form.put(apiTo("update", { direction: modelModal.value.id }), {
    onSuccess: () => {
      Notify.success(transl('edit.onSuccess'));
      searcher.refresh();
      Modal.switchEditModal();
    },
    onError: () => {
      Notify.error(transl('edit.onError'));
    }
  });
};
</script>

<template>
  <PageHeader title="DIRECCIONES" />
  <AddressForm @address-created="handleAddressCreated" />
  <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">Nombre</th>
          <th class="px-6 py-3 text-center text-sm font-semibold w-32">Acciones</th>
        </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.name }}
            </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="2" class="px-6 py-8 text-center text-gray-500 text-sm">
            {{ transl('list.empty') }}
          </td>
        </template>
      </Table>
    </div>
    <DestroyView
      title="name"
      subtitle=""
      :model="modelModal"
      :show="destroyModal"
      :to="(id) => apiTo('destroy', { direction: 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--;
          }
        }
      "
    />
    <Editview
      :show="editModal"
      :title="transl('edit.title')"
      @close="Modal.switchEditModal"
      @update="handleAddressUpdated"
    >
      <div class="p-4">
        <label
          for="editAddressName"
          class="block text-sm text-gray-600 font-medium mb-2"
        >
          {{ transl('name') }}:
        </label>
        <input
          type="text"
          id="editAddressName"
          v-model="modelModal.name"
          :placeholder="transl('placeholder')"
          class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
        />
      </div>
    </Editview>
  </div>
</template>
