<script setup>
import { computed } from "vue";
import { useForm } from "@Services/Api";
import { apiTo, transl } from "../Module";

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";

/** Props */
const props = defineProps({
  show: Boolean,
  model: Object,
  addresses: Array,
  units: Array,
});

/** Eventos */
const emit = defineEmits(['close', 'updated']);

const chargeTypesOptions = [
  { id: 'uma_range', name: 'UMA Range' },
  { id: 'peso_range', name: 'Peso Range' },
  { id: 'uma_fixed', name: 'UMA unitario' },
  { id: 'peso_fixed', name: 'Peso unitario' },
];

const conceptTypesOptions = [
  { id: "membership", name: "Membresía" },
  { id: "fine", name: "Multa" },
];

const chargeTypeObject = computed({
  get() {
    if (!props.model.charge_type) return null;
    return typeof props.model.charge_type === 'object' && props.model.charge_type?.id
      ? props.model.charge_type.id
      : chargeTypesOptions.find(opt => opt.id === props.model.charge_type) || null;
  },
  set(value) {
    props.model.charge_type = value;
  }
});

const conceptTypeObject = computed({
  get() {
    if (!props.model.concept_type) return null;
    const conceptTypeId = typeof props.model.concept_type === 'object' && props.model.concept_type?.id
      ? props.model.concept_type.id
      : props.model.concept_type;
    return conceptTypesOptions.find(opt => opt.id === conceptTypeId) || null;
  },
  set(value) {
    if (value && typeof value === 'object' && value.id) {
      props.model.concept_type = value.id;
    } else if (value) {
      props.model.concept_type = value;
    } else {
      props.model.concept_type = null;
    }
  }
});

const editChargeTypeId = computed(() => {
  if (!props.model.charge_type) return null;
  return typeof props.model.charge_type === 'object' && props.model.charge_type?.id
    ? props.model.charge_type.id
    : props.model.charge_type;
});

const editShowUmaFields = computed(() => {
  return editChargeTypeId.value === 'uma_range' || editChargeTypeId.value === 'uma_fixed';
});

const editShowPesoFields = computed(() => {
  return editChargeTypeId.value === 'peso_range' || editChargeTypeId.value === 'peso_fixed';
});

const editIsRangeType = computed(() => {
  return editChargeTypeId.value === 'uma_range' || editChargeTypeId.value === 'peso_range';
});

const editIsFixedType = computed(() => {
  return editChargeTypeId.value === 'uma_fixed' || editChargeTypeId.value === 'peso_fixed';
});

/** Metodos */
const handleUpdate = async () => {
  const transformedData = {
    direction_id: typeof props.model.direction === 'object' ? props.model.direction.id : Number(props.model.direction_id),
    unit_id: props.model.unit ? (typeof props.model.unit === 'object' ? props.model.unit.id : Number(props.model.unit)) : null,
    short_name: props.model.short_name,
    concept_type: props.model.concept_type,
    name: props.model.name,
    legal_instrument: props.model.legal_instrument,
    article: props.model.article,
    content: props.model.content,
    charge_type: editChargeTypeId.value,
    // Campos UMA para tipos de rango
    min_amount_uma: (editShowUmaFields.value && editIsRangeType.value && props.model.min_amount_uma) ? Number(props.model.min_amount_uma) : null,
    max_amount_uma: (editShowUmaFields.value && editIsRangeType.value && props.model.max_amount_uma) ? Number(props.model.max_amount_uma) : null,
    // Campos Peso para tipos de rango
    min_amount_peso: (editShowPesoFields.value && editIsRangeType.value && props.model.min_amount_peso) ? Number(props.model.min_amount_peso) : null,
    max_amount_peso: (editShowPesoFields.value && editIsRangeType.value && props.model.max_amount_peso) ? Number(props.model.max_amount_peso) : null,
    // Campos de costo unitario para tipos fijos
    unit_cost_uma: (editShowUmaFields.value && editIsFixedType.value && props.model.unit_cost_uma) ? Number(props.model.unit_cost_uma) : null,
    unit_cost_peso: (editShowPesoFields.value && editIsFixedType.value && props.model.unit_cost_peso) ? Number(props.model.unit_cost_peso) : null,
  };

  const form = useForm(transformedData);

  form.put(apiTo("update", { charge_concept: props.model.id }), {
    onSuccess: () => {
      Notify.success(transl("edit.onSuccess"));
      emit('updated');
    },
    onError: () => {
      Notify.error(transl("edit.onError"));
    },
  });
};
</script>

<template>
  <Editview
    :show="show"
    :title="transl('edit.title')"
    @close="emit('close')"
    @update="handleUpdate"
  >
    <div class="p-4 space-y-4">
      <Selectable
        v-model="conceptTypeObject"
        label="name"
        :title="$t('concept.conceptType')"
        :options="conceptTypesOptions"
        required
      />
      <Selectable
        v-model="model.direction"
        label="name"
        value="id"
        :title="$t('concept.direction')"
        :options="addresses"
        required
      />
      <Input
        v-model="model.short_name"
        :id="$t('concept.shortName')"
        type="text"
        required
      />
      <Input
        v-model="model.name"
        :id="$t('concept.name')"
        type="text"
        required
      />
      <Input
        v-model="model.legal_instrument"
        :id="$t('concept.legal')"
        type="text"
        required
      />
      <Input
        v-model="model.article"
        :id="$t('concept.article')"
        type="text"
        required
      />
      <Textarea
        v-model="model.content"
        :id="$t('concept.description')"
        required
      />

      <!-- Selector de tipo de cargo -->
      <Selectable
        v-model="chargeTypeObject"
        label="name"
        :title="$t('concept.chargeType')"
        :options="chargeTypesOptions"
        required
      />

      <div v-if="editShowUmaFields && editIsRangeType" class="grid grid-cols-2 gap-4">
        <Input
          v-model="model.min_amount_uma"
          :id="$t('concept.minimumAmountUma')"
          type="number"
          step="0.01"
          required
        />
        <Input
          v-model="model.max_amount_uma"
          :id="$t('concept.maximumAmountUma')"
          type="number"
          step="0.01"
          required
        />
      </div>

      <div v-if="editShowPesoFields && editIsRangeType" class="grid grid-cols-2 gap-4">
        <Input
          v-model="model.min_amount_peso"
          :id="$t('concept.minimumAmountPeso')"
          type="number"
          step="0.01"
          required
        />
        <Input
          v-model="model.max_amount_peso"
          :id="$t('concept.maximumAmountPeso')"
          type="number"
          step="0.01"
          required
        />
      </div>

      <Selectable
        v-model="model.unit"
        label="name"
        value="id"
        :title="$t('concept.sizeUnit')"
        :options="units"
        required
      />

      <div v-if="editIsFixedType">
        <hr class="my-4 border-gray-300" />
        <h4 class="text-lg font-semibold mb-2 text-gray-700">
          {{ $t('concept.tabulator') }}
        </h4>
        <div class="grid grid-cols-2 gap-4">
          <Input
            v-if="editShowUmaFields"
            v-model="model.unit_cost_uma"
            :id="$t('concept.costUnitUma')"
            type="number"
            step="0.01"
            required
          />

          <Input
            v-if="editShowPesoFields"
            v-model="model.unit_cost_peso"
            :id="$t('concept.costUnitPeso')"
            type="number"
            step="0.01"
            required
          />
        </div>
      </div>
    </div>
  </Editview>
</template>
