<template>
  <div class="admin--service-center-form">
    <form @submit.prevent="handleSubmit" class="admin--form">
      <!-- 서비스센터명 -->
      <div class="admin--form-group">
        <label class="admin--form-label"
          >서비스센터명 <span class="admin--required">*</span></label
        >
        <input
          v-model="formData.name"
          type="text"
          class="admin--form-input"
          placeholder="서비스센터명을 입력하세요"
          required
        />
      </div>

      <!-- 소속명 선택 -->
      <div class="admin--form-group">
        <label class="admin--form-label"
          >딜러사 명 <span class="admin--required">*</span></label
        >
        <select v-model="formData.branch_id" class="admin--form-select" required>
          <option value="">소속 지점을 선택하세요</option>
          <option v-for="branch in branches" :key="branch.id" :value="branch.id">
            {{ branch.name }}
          </option>
        </select>
      </div>

      <!-- 대표번호 -->
      <div class="admin--form-group">
        <label class="admin--form-label"
          >대표번호 <span class="admin--required">*</span></label
        >
        <input
          v-model="formData.phone"
          type="tel"
          class="admin--form-input"
          placeholder="02-1234-5678"
          required
        />
      </div>

      <!-- 주소 -->
      <div class="admin--form-group">
        <label class="admin--form-label"
          >주소 <span class="admin--required">*</span></label
        >
        <input
          v-model="formData.address"
          type="text"
          class="admin--form-input"
          placeholder="주소를 입력하세요"
          required
        />
      </div>

      <!-- 상세주소 -->
      <div class="admin--form-group">
        <label class="admin--form-label">상세주소</label>
        <input
          v-model="formData.detail_address"
          type="text"
          class="admin--form-input"
          placeholder="상세주소를 입력하세요"
        />
      </div>

      <!-- 위도/경도 -->
      <div class="admin--form-group">
        <label class="admin--form-label">위치 좌표</label>
        <div class="admin--coordinate-group">
          <div class="admin--coordinate-item">
            <label>위도</label>
            <input
              v-model.number="formData.latitude"
              type="text"
              step="any"
              class="admin--form-input"
              placeholder="37.5665"
            />
          </div>
          <div class="admin--coordinate-item">
            <label>경도</label>
            <input
              v-model.number="formData.longitude"
              type="text"
              step="any"
              class="admin--form-input"
              placeholder="126.9780"
            />
          </div>
        </div>
      </div>

      <!-- 영업시간 -->
      <div class="admin--form-group">
        <label class="admin--form-label">영업시간</label>
        <textarea
          v-model="formData.business_hours"
          class="admin--form-textarea"
          rows="3"
          placeholder="평일: 09:00 - 18:00&#10;주말: 10:00 - 17:00"
        ></textarea>
      </div>

      <!-- 서비스예약 링크 -->
      <div class="admin--form-group">
        <label class="admin--form-label">서비스예약 링크</label>
        <input
          v-model="formData.service_reservation_link"
          type="url"
          class="admin--form-input"
          placeholder="https://example.com/service-reservation"
        />
      </div>

      <!-- 링크 관리 -->
      <!-- <div class="admin--form-group">
        <label class="admin--form-label">관련 링크</label>
        <div class="admin--multi-input-wrapper">
          <div
            v-for="(link, index) in formData.links"
            :key="index"
            class="admin--multi-input-item"
          >
            <input
              v-model="formData.links[index]"
              type="url"
              class="admin--form-input"
              placeholder="https://example.com"
            />
            <button type="button" class="admin--btn-remove" @click="removeLink(index)">
              삭제
            </button>
          </div>
          <button type="button" class="admin--btn-add" @click="addLink">
            + 링크 추가
          </button>
        </div>
      </div> -->

      <!-- 버튼 영역 -->
      <div class="admin--form-actions">
        <button type="submit" class="admin--btn admin--btn-primary" :disabled="isSaving">
          {{ isSaving ? "저장 중..." : "확인" }}
        </button>
        <button type="button" class="admin--btn admin--btn-secondary" @click="goToList">
          목록
        </button>
      </div>

      <!-- 성공/에러 메시지 -->
      <div v-if="successMessage" class="admin--alert admin--alert-success">
        {{ successMessage }}
      </div>
      <div v-if="errorMessage" class="admin--alert admin--alert-error">
        {{ errorMessage }}
      </div>
    </form>
  </div>
</template>

<script setup>
  import { ref, onMounted } from "vue";
  import { useRouter } from "vue-router";

  definePageMeta({
    layout: "admin",
    middleware: ["auth"],
  });

  const router = useRouter();
  const { get, post } = useApi();

  const isSaving = ref(false);
  const successMessage = ref("");
  const errorMessage = ref("");
  const branches = ref([]);

  const formData = ref({
    name: "",
    branch_id: "",
    phone: "",
    address: "",
    detail_address: "",
    latitude: null,
    longitude: null,
    business_hours: "",
    service_reservation_link: "",
    links: [""], // 초기 링크 하나
  });

  // 지점 목록 로드
  const loadBranches = async () => {
    const { data, error } = await get("/branch/list", { params: { per_page: 1000 } });

    if (data?.success && data?.data?.items) {
      branches.value = data.data.items.filter((branch) => branch.is_active == 1);
    }
  };

  // 링크 추가
  const addLink = () => {
    formData.value.links.push("");
  };

  // 링크 삭제
  const removeLink = (index) => {
    formData.value.links.splice(index, 1);
  };

  // 폼 제출
  const handleSubmit = async () => {
    successMessage.value = "";
    errorMessage.value = "";

    // 유효성 검사
    if (!formData.value.name) {
      errorMessage.value = "서비스센터명을 입력하세요.";
      return;
    }

    if (!formData.value.branch_id) {
      errorMessage.value = "소속 지점을 선택하세요.";
      return;
    }

    if (!formData.value.phone) {
      errorMessage.value = "대표번호를 입력하세요.";
      return;
    }

    if (!formData.value.address) {
      errorMessage.value = "주소를 입력하세요.";
      return;
    }

    isSaving.value = true;

    try {
      // 빈 링크 제거
      const submitData = {
        ...formData.value,
        links: formData.value.links.filter((link) => link.trim() !== ""),
      };

      const { data, error } = await post("/service-center", submitData);

      if (error || !data?.success) {
        errorMessage.value = error?.message || data?.message || "등록에 실패했습니다.";
      } else {
        successMessage.value = data.message || "서비스센터가 등록되었습니다.";
        setTimeout(() => {
          router.push("/site-manager/service-center/list");
        }, 1000);
      }
    } catch (error) {
      errorMessage.value = "서버 오류가 발생했습니다.";
      console.error("Save error:", error);
    } finally {
      isSaving.value = false;
    }
  };

  // 목록으로 이동
  const goToList = () => {
    router.push("/site-manager/service-center/list");
  };

  onMounted(() => {
    loadBranches();
  });
</script>

<style scoped>
  .admin--coordinate-group {
    display: flex;
    gap: 16px;
  }

  .admin--coordinate-item {
    flex: 1;
  }

  .admin--coordinate-item label {
    display: block;
    margin-bottom: 8px;
    font-size: 14px;
    color: #666;
  }
</style>
