<template>
  <div class="admin--page-content">
    <div class="admin--form">
      <form @submit.prevent="handleSubmit">
        <table class="admin--form--table">
          <colgroup>
            <col style="width: 140px;">
            <col>
          </colgroup>
          <tbody>
            <tr>
              <th><div>분야 <span class="admin--required">*</span></div></th>
              <td>
                <div class="input--wrap">
                  <select v-model="formData.field_id" class="admin--form-select w--240" required>
                    <option value="">선택하세요</option>
                    <option v-for="f in fieldOptions" :key="f.id" :value="f.id">{{ f.name }}</option>
                  </select>
                </div>
              </td>
            </tr>
            <tr>
              <th><div>지역 <span class="admin--required">*</span></div></th>
              <td>
                <div class="input--wrap">
                  <select v-model="formData.area_id" class="admin--form-select w--240" required>
                    <option value="">선택하세요</option>
                    <option v-for="a in areaOptions" :key="a.id" :value="a.id">{{ a.name }}</option>
                  </select>
                </div>
              </td>
            </tr>
            <tr>
              <th><div>선상명 <span class="admin--required">*</span></div></th>
              <td>
                <div class="input--wrap">
                  <input v-model="formData.name" type="text" class="admin--form-input" placeholder="예: 파이럿호" required />
                </div>
              </td>
            </tr>
            <tr>
              <th><div>낚시지역</div></th>
              <td>
                <div class="input--wrap">
                  <input v-model="formData.area_detail" type="text" class="admin--form-input" placeholder="예: 모슬포항" />
                </div>
              </td>
            </tr>
            <tr>
              <th><div>중량(톤수)</div></th>
              <td>
                <div class="input--wrap">
                  <input v-model="formData.tonnage" type="text" class="admin--form-input w--240" placeholder="예: 9.77톤" />
                </div>
              </td>
            </tr>
            <tr>
              <th><div>탑승인원</div></th>
              <td>
                <div class="input--wrap">
                  <input v-model="formData.capacity" type="text" class="admin--form-input w--240" placeholder="예: 20인승, 낚시 전용선" />
                </div>
              </td>
            </tr>  
            <tr>
              <th><div>우편번호</div></th>
              <td>
                <div class="input--wrap">
                  <input v-model="formData.zip_code" type="text" class="admin--form-input w--160" placeholder="우편번호" readonly />
                  <button type="button" class="admin--btn-small admin--btn-blue" @click="openPostcode">
                    우편번호 검색
                  </button>
                </div>
              </td>
            </tr>
            <tr>
              <th><div>주소</div></th>
              <td>
                <div class="input--wrap">
                  <input v-model="formData.address" type="text" class="admin--form-input w--full" placeholder="우편번호 검색 시 자동 입력" readonly />
                </div>
              </td>
            </tr>
            <tr>
              <th><div>상세주소</div></th>
              <td>
                <div class="input--wrap">
                  <input v-model="formData.address_detail" type="text" class="admin--form-input w--full" placeholder="" />
                </div>
              </td>
            </tr>
            <tr>
              <th><div>참고항목</div></th>
              <td>
                <div class="input--wrap">
                  <input v-model="formData.address_refer" type="text" class="admin--form-input w--full" placeholder="예: 선착장 입구 우측" />
                </div>
              </td>
            </tr>
            <tr>
              <th><div>좌표</div></th>
              <td>
                <div class="input--wrap admin--inline-group">
                  <input v-model="formData.lat" type="text" class="admin--form-input w--200" placeholder="위도 (lat)" />
                  <input v-model="formData.lng" type="text" class="admin--form-input w--200" placeholder="경도 (lng)" />
                </div>
                <p v-if="coordError" class="">{{ coordError }}</p>
                <p v-else class="mt--10">주소를 검색하면 위도·경도가 자동 입력됩니다.</p>
              </td>
            </tr>
            <tr>
              <th><div>제휴 여부</div></th>
              <td>
                <div class="input--wrap">
                  <label class="admin--radio-label">
                    <input type="radio" v-model="formData.partnership_YN" value="Y" /> 제휴
                  </label>
                  <label class="admin--radio-label ml--16">
                    <input type="radio" v-model="formData.partnership_YN" value="N" /> 비제휴
                  </label>
                </div>
              </td>
            </tr>
            <tr v-if="isPartner">
              <th><div>계좌번호</div></th>
              <td>
                <div class="input--wrap">
                  <select v-model="formData.bank_code" class="admin--form-select w--120">
                    <option value="">은행명</option>
                    <option v-for="b in bankOptions" :key="b.code" :value="b.code">{{ b.name }}</option>
                  </select>
                  <input v-model="formData.account_number" type="text" class="admin--form-input w--300" placeholder="'-' 없이 숫자만 입력" />
                  <input v-model="formData.account_holder" type="text" class="admin--form-input w--240" placeholder="예금주명" />
                </div>
                <p class="mt--10">정산 입금 계좌 (제휴 업체용)</p>
              </td>
            </tr>
            <tr>
              <th><div>상태</div></th>
              <td>
                <div class="input--wrap">
                  <label class="admin--radio-label">
                    <input type="radio" v-model="formData.status_YN" value="Y" /> 사용중
                  </label>
                  <label class="admin--radio-label ml--16">
                    <input type="radio" v-model="formData.status_YN" value="N" /> 미사용
                  </label>
                </div>
              </td>
            </tr>
          </tbody>
        </table>

        <!-- 버튼 영역 -->
        <div class="admin--form-actions">
          <button type="button" class="admin--btn" @click="goToList">
            ← 목록으로
          </button>
          <button type="submit" class="admin--btn admin--btn-red ml--auto" :disabled="isSaving">
            {{ isSaving ? "저장 중..." : "저장" }}
          </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>
  </div>
</template>

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

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

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

  const isSaving = ref(false);
  const successMessage = ref("");
  const errorMessage = ref("");
  const coordError = ref("");

  // 분야 / 지역 select 옵션
  const fieldOptions = ref([]);
  const areaOptions = ref([]);

  // 주요 은행 목록 (금융결제원 표준 코드)
  const bankOptions = [
    { code: "002", name: "산업은행" },
    { code: "003", name: "기업은행" },
    { code: "004", name: "국민은행" },
    { code: "007", name: "수협은행" },
    { code: "011", name: "농협은행" },
    { code: "020", name: "우리은행" },
    { code: "023", name: "SC제일은행" },
    { code: "031", name: "대구은행" },
    { code: "032", name: "부산은행" },
    { code: "034", name: "광주은행" },
    { code: "035", name: "제주은행" },
    { code: "037", name: "전북은행" },
    { code: "039", name: "경남은행" },
    { code: "045", name: "새마을금고" },
    { code: "071", name: "우체국" },
    { code: "081", name: "하나은행" },
    { code: "088", name: "신한은행" },
    { code: "089", name: "케이뱅크" },
    { code: "090", name: "카카오뱅크" },
    { code: "092", name: "토스뱅크" },
  ];

  const formData = ref({
    field_id: "",
    area_id: "",
    name: "",
    area_detail: "",
    tonnage: "",
    capacity: "",
    zip_code: "",
    address: "",
    address_detail: "",
    address_refer: "",
    lat: "",
    lng: "",
    bank_code: "",
    account_number: "",
    account_holder: "",
    partnership_YN: "N",
    status_YN: "Y",
  });

  // 제휴 여부 — 비제휴면 계좌 입력 비활성화
  const isPartner = computed(() => formData.value.partnership_YN === "Y");

  // 비제휴로 전환 시 입력했던 계좌 정보 초기화
  watch(
    () => formData.value.partnership_YN,
    (val) => {
      if (val === "N") {
        formData.value.bank_code = "";
        formData.value.account_number = "";
        formData.value.account_holder = "";
      }
    }
  );

  // 분야 / 지역 옵션 로드
  const loadOptions = async () => {
    const [fieldRes, areaRes] = await Promise.all([
      get("/field/list", { params: { per_page: 1000 } }),
      get("/area/list", { params: { per_page: 1000 } }),
    ]);

    // API는 id DESC(최신순)로 주므로 뒤집어서 먼저 등록한 순(수도권 등)이 위로 오게
    if (fieldRes.data?.success) fieldOptions.value = (fieldRes.data.data.items || []).reverse();
    if (areaRes.data?.success) areaOptions.value = (areaRes.data.data.items || []).reverse();
  };

  // 외부 스크립트 동적 로드
  const loadScript = (src) =>
    new Promise((resolve, reject) => {
      if (document.querySelector(`script[src="${src}"]`)) {
        resolve();
        return;
      }
      const s = document.createElement("script");
      s.src = src;
      s.onload = () => resolve();
      s.onerror = () => reject(new Error(`스크립트 로드 실패: ${src}`));
      document.head.appendChild(s);
    });

  // 주소 → 위도/경도 변환 (Google Geocoding API)
  const searchCoords = async (address) => {
    coordError.value = "";

    const key = config.public.googleMapKey;
    if (!key) {
      coordError.value = "좌표를 자동으로 가져올 수 없습니다. 위도/경도를 직접 입력하세요.";
      return;
    }

    try {
      const url = new URL("https://maps.googleapis.com/maps/api/geocode/json");
      url.searchParams.set("address", address);
      url.searchParams.set("key", key);
      url.searchParams.set("language", "ko");
      url.searchParams.set("region", "kr");

      const res = await fetch(url);
      const data = await res.json();

      if (data.status === "OK" && data.results?.[0]) {
        const loc = data.results[0].geometry.location;
        formData.value.lat = String(loc.lat);
        formData.value.lng = String(loc.lng);
      } else {
        formData.value.lat = "";
        formData.value.lng = "";
        coordError.value = "좌표를 찾지 못했습니다. 직접 입력해 주세요.";
      }
    } catch (e) {
      console.error("Geocoding error:", e);
      formData.value.lat = "";
      formData.value.lng = "";
      coordError.value = "좌표 조회 중 오류가 발생했습니다. 위도/경도를 직접 입력해주세요.";
    }
  };

  // 우편번호 검색 (Daum Postcode)
  const openPostcode = async () => {
    coordError.value = "";
    try {
      await loadScript("https://t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js");
    } catch (e) {
      errorMessage.value = "우편번호 서비스를 불러오지 못했습니다.";
      return;
    }

    new window.daum.Postcode({
      oncomplete: (data) => {
        formData.value.zip_code = data.zonecode;
        formData.value.address = data.roadAddress || data.jibunAddress;
        // 선택한 주소로 좌표 자동 조회
        searchCoords(formData.value.address);
      },
    }).open();
  };

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

    // 필수값 검증
    if (!formData.value.field_id) return (errorMessage.value = "분야를 선택하세요.");
    if (!formData.value.area_id) return (errorMessage.value = "지역을 선택하세요.");
    if (!formData.value.name.trim()) return (errorMessage.value = "선상명을 입력하세요.");

    isSaving.value = true;
    try {
      const { data, error } = await post("/onboard", { ...formData.value });

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

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

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