<script setup>
import { inject, defineProps, watch, ref } from "vue";
import useFormErrorMessage from "@/hooks/useFormErrorMessage";
import { postEditCarbonValue } from "@/apis/energy";
import * as yup from "yup";
import { useI18n } from "vue-i18n";
import useBuildingStore from "@/stores/useBuildingStore";
const store = useBuildingStore();
const { t } = useI18n();
const { openToast } = inject("app_toast");
const props = defineProps({
  carbonData: Object,
  getData: Function,
});

let scheme = yup.object({
  coefficient: yup.number().required(t("button.required")),
});

const form = ref(null);
const formState = ref({
  coefficient: null,
});

const { formErrorMsg, handleSubmit, handleErrorReset } = useFormErrorMessage(
  scheme.value
);

watch(
  () => props.carbonData,
  (newValue) => {
    if (newValue) {
      formState.value = {
        ...newValue,
      };
    }
  }
);

const onOk = async () => {
  const values = await handleSubmit(scheme, formState.value);

  const res = await postEditCarbonValue({
    ...values,
    "building_guid":store.selectedBuilding.building_guid,
  });
  if (res.isSuccess) {
    props.getData();
    closeModal();
  } else {
    openToast("error", res.msg, "#carbon_emission_item");
  }
};

const openModal = () => {
  carbon_emission_item.showModal();
};

const onCancel = () => {
  carbon_emission_item.close();
};

const closeModal = () => {
  handleErrorReset();
  onCancel();
};
</script>

<template>
  <button class="btn btn-xs btn-success absolute top-0 right-0" @click.stop.prevent="openModal">
    {{ $t("button.edit") }}
  </button>
  <Modal
    id="carbon_emission_item"
    :title="t('energy.edit_carbon_emission')"
    :onCancel="closeModal"
    :width="400"
  >
    <template #modalContent>
      <form ref="form" class="mt-5 flex flex-col items-center">
        <Input :value="formState" class="w-full" name="coefficient">
          <template #topLeft>{{$t('energy.carbon_emission_coefficient')}}</template>
          <template #bottomLeft>
            <span class="text-error text-base">
              {{ formErrorMsg.coefficient }}
            </span>
          </template>
        </Input>
      </form>
    </template>
    <template #modalAction>
      <button
        type="reset"
        class="btn btn-outline-success mr-2"
        @click.prevent="closeModal"
      >
        {{ $t("button.cancel") }}
      </button>
      <button
        type="submit"
        class="btn btn-outline-success"
        @click.prevent="onOk"
      >
        {{ $t("button.submit") }}
      </button>
    </template>
  </Modal>
</template>

<style lang="scss" scoped></style>
