<template>
    <div v-if="isOpen" class="modal-dialog" @click.self="closeModal">
      <div class="modal-content">
        <h5 class="modal-title">To. {{ targetUser.MEMBERNAM }} 🎁</h5>
        <button class="close-btn" @click="closeModal">✖</button>

        <div class="modal-body">
          <p>해당 직원에게 부여할 연차 개수를 선택하세요. (남은 개수: {{ availableQuota }}개)</p>

          <div class="vacation-control">
            <button @click="decreaseCount" :disabled="grantCount < 2" class="count-btn">-</button>
            <span class="grant-count">{{ grantCount }}</span>
            <button @click="increaseCount" :disabled="grantCount >= availableQuota" class="count-btn">+</button>
          </div>

          <button class="gift-btn" @click="saveVacationGrant" :disabled="grantCount === 0">
            <i class="bx bx-gift"></i>
          </button>
        </div>
      </div>
    </div>
  </template>

  <script setup>
  import { ref, defineProps, defineEmits, watch, onMounted } from "vue";
  import axios from "@api";

  const props = defineProps({
    isOpen: Boolean,
    targetUser: Object,
  });

  const emit = defineEmits(["close", "updateVacation"]);
  const grantCount = ref(0);
  const maxQuota = 2;
  const sentCount = ref(0);
  const availableQuota = ref(2);

  const fetchSentVacationCount = async () => {
    try {
      const payload = { receiverId: props.targetUser.MEMBERSEQ };
      const response = await axios.get("vacation/sent", { params: payload });
      sentCount.value = response.data.data[0].count || 0;
      availableQuota.value = Math.max(maxQuota - sentCount.value, 0);
      grantCount.value = availableQuota.value; // ✅ 남은 개수로 기본값 설정
    } catch (error) {
      console.error("🚨 연차 전송 기록 조회 실패:", error);
      availableQuota.value = maxQuota;
      grantCount.value = maxQuota; // 기본값 설정
    }
  };

  const increaseCount = () => {
    if (grantCount.value < availableQuota.value) {
      grantCount.value++;
    }
  };

  const decreaseCount = () => {
    if (grantCount.value > 0) {
      grantCount.value--;
    }
  };

  const saveVacationGrant = async () => {
    try {
      const payload = [
        {
          date: new Date().toISOString().split("T")[0],
          type: "700103",
          receiverId: props.targetUser.MEMBERSEQ,
          count: grantCount.value,
        },
      ];
      console.log(props.targetUser)
      console.log(payload)
      const response = await axios.post("vacation", payload);
        console.log(response)
      if (response.data && response.data.status === "OK") {
        alert("✅ 연차가 부여되었습니다.");
        await fetchSentVacationCount();
        emit("updateVacation");
        closeModal();
      } else {
        alert("🚨 연차 추가 중 오류가 발생했습니다.");
      }
    } catch (error) {
      console.error("🚨 연차 추가 실패:", error);
      alert("연차 추가에 실패했습니다.");
    }
  };

  const closeModal = () => {
    emit("close");
  };

  watch(
    () => props.isOpen,
    async (newVal) => {
      if (newVal && props.targetUser && props.targetUser.MEMBERSEQ) {
        console.log("🟢 모달이 열렸습니다. 데이터를 로드합니다.");
        await fetchSentVacationCount();
      }
    }
  );

  watch(
    () => props.targetUser,
    async (newUser) => {
      if (newUser && newUser.MEMBERSEQ) {
        await fetchSentVacationCount();
      }
    },
    { deep: true }
  );

  onMounted(async () => {
    if (props.isOpen && props.targetUser && props.targetUser.MEMBERSEQ) {
      await fetchSentVacationCount();
    }
  });
  </script>


  <style scoped>

  /* 모달 본문 */
  .modal-content {
    background: white;
    padding: 20px;
    border-radius: 12px;
    width: 400px;
    box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.15);
    text-align: center;
    position: relative;
  }

  /* 닫기 버튼 */
  .close-btn {
    position: absolute;
    top: 10px;
    right: 10px;
    background: none;
    border: none;
    font-size: 18px;
    cursor: pointer;
  }

  /* 연차 개수 조정 버튼 */
  .vacation-control {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 10px;
    margin-top: 15px;
  }

  .count-btn {
    font-size: 18px;
    padding: 6px 12px;
    border: none;
    background: #007bff;
    color: white;
    border-radius: 5px;
    cursor: pointer;
  }

  .count-btn:disabled {
    background: #ccc;
    cursor: not-allowed;
  }

  /* 개수 표시 */
  .grant-count {
    font-size: 20px;
    font-weight: bold;
    color: #333;
  }

  /* 선물 아이콘 버튼 */
  .gift-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    background: #28a745;
    color: white;
    border: none;
    border-radius: 8px;
    padding: 10px 15px;
    margin-top: 15px;
    cursor: pointer;
    transition: 0.3s;
  }

  .gift-btn:hover {
    background: #218838;
  }

  .gift-btn:disabled {
    background: #ccc;
    cursor: not-allowed;
  }
  </style>
