<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 Editview from "@Holos/Modal/Edit.vue";
import Input from "@Holos/Form/Input.vue";
import Textarea from "@Holos/Form/Textarea.vue";
import Selectable from "@Holos/Form/Selectable.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: {},
  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 = async () => {
  const transformedData = {
    direction_id: typeof modelModal.value.direction === 'object' ? modelModal.value.direction.id : Number(modelModal.value.direction_id),
    unit_id: modelModal.value.unit ? (typeof modelModal.value.unit === 'object' ? modelModal.value.unit.id : Number(modelModal.value.unit)) : null,
    short_name: modelModal.value.short_name,
    name: modelModal.value.name,
    legal_instrument: modelModal.value.legal_instrument,
    article: modelModal.value.article,
    content: modelModal.value.content,
    min_amount_uma: modelModal.value.min_amount_uma ? Number(modelModal.value.min_amount_uma) : null,
    max_amount_uma: modelModal.value.max_amount_uma ? Number(modelModal.value.max_amount_uma) : null,
    min_amount_peso: modelModal.value.min_amount_peso ? Number(modelModal.value.min_amount_peso) : null,
    max_amount_peso: modelModal.value.max_amount_peso ? Number(modelModal.value.max_amount_peso) : null,
    unit_cost_uma: modelModal.value.unit_cost_uma ? Number(modelModal.value.unit_cost_uma) : null,
    unit_cost_peso: modelModal.value.unit_cost_peso ? Number(modelModal.value.unit_cost_peso) : null,
  };

  const form = useForm(transformedData);

  form.put(apiTo("update", { charge_concept: modelModal.value.id }), {
    onSuccess: () => {
      Notify.success(transl("edit.onSuccess"));
      searcher.refresh();
      Modal.switchEditModal();
    },
    onError: () => {
      Notify.error(transl("edit.onError"));
    },
  });
};
</script>
<template>
  <PageHeader :title="transl('title')" />
  <ConceptForm @concept-created="handleConceptCreated" />
  <div class="m-3">
    <Table
      :items="models"
      :processing="searcher.processing"
      @send-pagination="(page) => searcher.pagination(page)"
    >
      <template #head>
        <th v-text="transl('direction')" />
        <th v-text="transl('shortName')" />
        <th v-text="transl('name')" />
        <th v-text="transl('legal')" />
        <th v-text="transl('article')" />
        <th v-text="transl('description')" />
        <th v-text="$t('actions')" class="w-32 text-center" />
      </template>
      <template #body="{ items }">
        <tr v-for="model in items" :key="model.id" class="table-row">
          <td class="table-cell border">
            {{ model.direction?.name || "-" }}
          </td>
          <td class="table-cell border">
            {{ model.short_name }}
          </td>
          <td class="table-cell border">
            {{ model.name }}
          </td>
          <td class="table-cell border">
            {{ model.legal_instrument }}
          </td>
          <td class="table-cell border">
            {{ model.article }}
          </td>
          <td class="table-cell border">
            {{ model.content }}
          </td>
          <td class="table-cell">
            <div class="table-actions">
              <IconButton
                icon="edit"
                :title="$t('crud.edit')"
                @click="Modal.switchEditModal(model)"
                outline
              />
              <IconButton
                icon="delete"
                :title="$t('crud.destroy')"
                @click="Modal.switchDestroyModal(model)"
                outline
              />
            </div>
          </td>
        </tr>
      </template>
      <template #empty>
        <td colspan="7" class="table-cell text-center py-4 text-gray-500">
          {{ transl("list.empty") }}
        </td>
      </template>
    </Table>
    <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--;
          }
        }
      "
    />
    <Editview
      :show="editModal"
      :title="transl('edit.title')"
      @close="Modal.switchEditModal"
      @update="handleConceptUpdated"
    >
      <div class="p-4 space-y-4">
        <Selectable
          v-model="modelModal.direction"
          label="name"
          value="id"
          :title="$t('concept.direction')"
          :options="addresses"
          required
        />
        <Input
          v-model="modelModal.short_name"
          :id="$t('concept.shortName')"
          type="text"
          required
        />
        <Input
          v-model="modelModal.name"
          :id="$t('concept.name')"
          type="text"
          required
        />
        <Input
          v-model="modelModal.legal_instrument"
          :id="$t('concept.legal')"
          type="text"
          required
        />
        <Input
          v-model="modelModal.article"
          :id="$t('concept.article')"
          type="text"
          required
        />
        <Textarea
          v-model="modelModal.content"
          :id="$t('concept.description')"
          required
        />
        <div class="grid grid-cols-2 gap-4">
          <Input
            v-model="modelModal.min_amount_uma"
            :id="$t('concept.minimumAmountUma')"
            type="number"
            step="0.01"
          />
          <Input
            v-model="modelModal.max_amount_uma"
            :id="$t('concept.maximumAmountUma')"
            type="number"
            step="0.01"
          />
        </div>
        <div class="grid grid-cols-2 gap-4">
          <Input
            v-model="modelModal.min_amount_peso"
            :id="$t('concept.minimumAmountPeso')"
            type="number"
            step="0.01"
          />
          <Input
            v-model="modelModal.max_amount_peso"
            :id="$t('concept.maximumAmountPeso')"
            type="number"
            step="0.01"
          />
        </div>
        <hr class="my-4 border-gray-300" />
        <h4 class="text-lg font-semibold mb-2 text-gray-700">
          {{ $t('concept.tabulator') }}
        </h4>
        <Selectable
          v-model="modelModal.unit"
          label="name"
          value="id"
          :title="$t('concept.sizeUnit')"
          :options="units"
        />
        <div class="grid grid-cols-2 gap-4">
          <Input
            v-model="modelModal.unit_cost_uma"
            :id="$t('concept.costUnitUma')"
            type="number"
            step="0.01"
          />
          <Input
            v-model="modelModal.unit_cost_peso"
            :id="$t('concept.costUnitPeso')"
            type="number"
            step="0.01"
          />
        </div>
      </div>
    </Editview>
  </div>
</template>
