<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: editIsFixedType.value && 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,
    motivation: props.model.motivation,
    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"
      />
      <Input
        v-model="model.article"
        :id="$t('concept.article')"
        type="text"
      />
      <Textarea
        v-model="model.content"
        :id="$t('concept.description')"
      />
      <Textarea
        v-model="model.motivation"
        :id="$t('concept.motivation')"
      />
      <!-- Selector de tipo de cargo -->
      <Selectable
        v-model="chargeTypeObject"
        label="name"
        :title="$t('concept.chargeType')"
        :options="chargeTypesOptions"
        required
      />

      <!-- Rango: solo monto mínimo y monto máximo (UMA o pesos) -->
      <div v-if="editIsRangeType" class="grid grid-cols-2 gap-4">
        <Input
          v-if="editShowUmaFields"
          v-model="model.min_amount_uma"
          :id="$t('concept.minimumAmountUma')"
          type="number"
          step="0.01"
          required
        />
        <Input
          v-if="editShowUmaFields"
          v-model="model.max_amount_uma"
          :id="$t('concept.maximumAmountUma')"
          type="number"
          step="0.01"
          required
        />
        <Input
          v-if="editShowPesoFields"
          v-model="model.min_amount_peso"
          :id="$t('concept.minimumAmountPeso')"
          type="number"
          step="0.01"
          required
        />
        <Input
          v-if="editShowPesoFields"
          v-model="model.max_amount_peso"
          :id="$t('concept.maximumAmountPeso')"
          type="number"
          step="0.01"
          required
        />
      </div>

      <!-- Tabulador: unidad de medida y costo por unidad (UMA o pesos) -->
      <div v-if="editIsFixedType" class="grid grid-cols-2 gap-4">
        <Selectable
          v-model="model.unit"
          label="name"
          value="id"
          :title="$t('concept.sizeUnit')"
          :options="units"
          required
        />
        <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>
  </Editview>
</template>
