<script setup>
import { onMounted, ref, inject, onBeforeMount, watch, computed } from "vue";
import {
  getDepartmentList,
  postDepartmentList,
  deleteDepartmentItem,
} from "@/apis/asset";
import useFormErrorMessage from "@/hooks/useFormErrorMessage";
import * as yup from "yup";
import { twMerge } from "tailwind-merge";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const { openToast, cancelToastOpen } = inject("app_toast");
const { formState } = inject("asset_table_modal_form");

const selectedOption = ref("add");

const DeptFormState = ref({ id: 0, name: "" });
const departmentList = ref([]);

const getDepartment = async () => {
  const res = await getDepartmentList();
  departmentList.value = res.data.map((d) => ({ ...d, key: d.id }));
};

onMounted(() => {
  getDepartment();
});

// modal
const openModal = () => {
  if (selectedOption.value === "add") {
    DeptFormState.value = {
      id: 0,
      name: "",
    };
  } else if (selectedOption.value === "edit") {
    const dept = departmentList.value.find(
      (d) => d.id === formState.value.department_id
    );
    if (dept) {
      DeptFormState.value = {
        id: dept.id,
        name: dept.name,
      };
    }
  }
  asset_add_dept.showModal();
};

const form = ref(null);

const deptScheme = yup.object({
  name: yup.string().required(t("button.required")),
});

const { formErrorMsg, handleSubmit, handleErrorReset, updateScheme } =
  useFormErrorMessage(deptScheme);
const onOk = async () => {
  const value = await handleSubmit(deptScheme, DeptFormState.value);

  const res = await postDepartmentList(value);
  if (res.isSuccess) {
    getDepartment();
    onCancel();
  }
};

const onDelete = async () => {
  openToast(
    "warning",
    t("msg.sure_to_delete"),
    "#asset_add_table_item",
    async () => {
      await cancelToastOpen();
      const res = await deleteDepartmentItem(formState.value.department_id);
      if (res.isSuccess) {
        getDepartment();
        openToast("success", t("msg.delete_success"), "#asset_add_table_item");
      } else {
        openToast("error", res.msg, "#asset_add_table_item");
      }
    }
  );
};

const onCancel = () => {
  DeptFormState.value = {
    id: 0,
    name: "",
  };
  asset_add_dept.close();
};
</script>

<template>
  <div className="join w-72 mb-4">
    <Select
      :value="formState"
      selectClass="border-info focus-within:border-info rounded-r-none"
      name="department_id"
      Attribute="name"
      :options="departmentList"
      :isBottomLabelExist="false"
    >
      <template #topLeft>{{ $t("assetManagement.department") }}</template>
    </Select>
    <select
      v-model="selectedOption"
      className="select border-info focus-within:border-info join-item mt-11"
    >
      <option value="add" selected>{{ $t("button.add") }}</option>
      <option value="edit">{{ $t("button.edit") }}</option>
      <option value="delete">{{ $t("button.delete") }}</option>
    </select>
    <button
      type="button"
      class="btn btn-success join-item mt-11"
      @click="selectedOption === 'delete' ? onDelete() : openModal()"
      :aria-label="$t('button.submit')"
    >
      {{ $t("button.submit") }}
    </button>
  </div>
  <Modal
    id="asset_add_dept"
    :title="t('assetManagement.department')"
    :onCancel="onCancel"
    :width="400"
  >
    <template #modalContent>
      <form ref="form">
        <Input :value="DeptFormState" width="270" name="name">
          <template #topLeft>{{
            $t("assetManagement.department_name")
          }}</template>
          <template #bottomLeft
            ><span class="text-error text-base">
              {{ formErrorMsg.name }}
            </span></template
          ></Input
        >
      </form>
    </template>
    <template #modalAction>
      <button
        type="reset"
        class="btn btn-outline-success mr-2"
        @click.prevent="onCancel"
      >
        {{ $t("button.cancel") }}
      </button>
      <button type="submit" class="btn btn-outline-success" @click="onOk">
        {{ $t("button.submit") }}
      </button>
    </template></Modal
  >
</template>

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