<script setup>
definePageMeta({
  layout: 'admin'
})

const saving = ref(false)
const loadingProfile = ref(true)
const savingProfile = ref(false)
const savingPassword = ref(false)
const uploadingAvatar = ref(false)
const removingAvatar = ref(false)
const errorMessage = ref('')
const profileMessage = ref('')
const passwordMessage = ref('')
const toast = ref(null)
let toastTimer = null
const avatarInputRef = ref(null)

const { data: settings } = await useFetch('/admin/api/settings')

const form = reactive({
  title: settings.value?.title || 'sori.studio',
  description: settings.value?.description || '',
  siteUrl: settings.value?.siteUrl || 'https://sori.studio',
  logoText: settings.value?.logoText || '井',
  copyrightText: settings.value?.copyrightText || '©2026 sori.studio'
})

const profileForm = reactive({
  email: '',
  username: '',
  avatarUrl: ''
})

const passwordForm = reactive({
  currentPassword: '',
  nextPassword: '',
  nextPasswordConfirm: ''
})

/**
 * 관리자 프로필을 조회한다.
 * @returns {Promise<void>}
 */
const loadAdminProfile = async () => {
  loadingProfile.value = true
  profileMessage.value = ''

  try {
    const profile = await $fetch('/api/auth/profile')
    profileForm.email = profile.email || ''
    profileForm.username = profile.username || ''
    profileForm.avatarUrl = profile.avatarUrl || ''
  } catch {
    profileMessage.value = '관리자 프로필을 불러오지 못했습니다. 다시 로그인해 주세요.'
  } finally {
    loadingProfile.value = false
  }
}

/**
 * 닉네임 중복 여부를 확인한다.
 * @returns {Promise<boolean>} 사용 가능 여부
 */
const checkUsernameAvailable = async () => {
  const username = profileForm.username.trim()
  if (!username) {
    profileMessage.value = '관리자 이름을 입력해 주세요.'
    return false
  }

  try {
    const result = await $fetch('/api/auth/check-username', {
      query: {
        username
      }
    })

    if (!result.available) {
      profileMessage.value = '이미 사용 중인 이름입니다.'
      return false
    }
  } catch (error) {
    profileMessage.value = error?.data?.message || '이름 중복 확인에 실패했습니다.'
    return false
  }

  return true
}

/**
 * 관리자 프로필을 저장한다.
 * @returns {Promise<void>}
 */
const saveAdminProfile = async () => {
  const available = await checkUsernameAvailable()
  if (!available) {
    return
  }

  savingProfile.value = true
  profileMessage.value = ''

  try {
    await $fetch('/api/auth/profile', {
      method: 'PUT',
      body: {
        username: profileForm.username.trim(),
        avatarUrl: profileForm.avatarUrl.trim()
      }
    })
    profileMessage.value = '관리자 프로필이 저장되었습니다.'
  } catch (error) {
    profileMessage.value = error?.data?.message || '관리자 프로필 저장에 실패했습니다.'
  } finally {
    savingProfile.value = false
  }
}

/**
 * 관리자 썸네일 파일 선택창을 연다.
 * @returns {void}
 */
const openAvatarFilePicker = () => {
  avatarInputRef.value?.click()
}

/**
 * 관리자 썸네일을 업로드한다.
 * @param {Event} event - 파일 선택 이벤트
 * @returns {Promise<void>}
 */
const uploadAvatar = async (event) => {
  const target = /** @type {HTMLInputElement | null} */ (event.target instanceof HTMLInputElement ? event.target : null)
  const file = target?.files?.[0]

  if (!file || uploadingAvatar.value) {
    return
  }

  uploadingAvatar.value = true
  profileMessage.value = ''

  try {
    const formData = new FormData()
    formData.append('file', file)
    const result = await $fetch('/api/auth/avatar', {
      method: 'POST',
      body: formData
    })
    profileForm.avatarUrl = result.avatarUrl || ''
    profileMessage.value = '관리자 썸네일이 업로드되었습니다.'
  } catch (error) {
    profileMessage.value = error?.data?.message || '관리자 썸네일 업로드에 실패했습니다.'
  } finally {
    uploadingAvatar.value = false
    if (target) {
      target.value = ''
    }
  }
}

/**
 * 관리자 썸네일을 제거한다.
 * @returns {Promise<void>}
 */
const removeAvatar = async () => {
  if (removingAvatar.value) {
    return
  }

  removingAvatar.value = true
  profileMessage.value = ''

  try {
    await $fetch('/api/auth/avatar', {
      method: 'DELETE'
    })
    profileForm.avatarUrl = ''
    profileMessage.value = '관리자 썸네일이 제거되었습니다.'
  } catch (error) {
    profileMessage.value = error?.data?.message || '관리자 썸네일 제거에 실패했습니다.'
  } finally {
    removingAvatar.value = false
  }
}

/**
 * 관리자 비밀번호를 변경한다.
 * @returns {Promise<void>}
 */
const saveAdminPassword = async () => {
  passwordMessage.value = ''

  if (!passwordForm.currentPassword || !passwordForm.nextPassword || !passwordForm.nextPasswordConfirm) {
    passwordMessage.value = '모든 비밀번호 입력값을 작성해 주세요.'
    return
  }

  if (passwordForm.nextPassword !== passwordForm.nextPasswordConfirm) {
    passwordMessage.value = '새 비밀번호와 확인 값이 일치하지 않습니다.'
    return
  }

  savingPassword.value = true

  try {
    await $fetch('/api/auth/password', {
      method: 'PUT',
      body: {
        currentPassword: passwordForm.currentPassword,
        nextPassword: passwordForm.nextPassword
      }
    })

    passwordForm.currentPassword = ''
    passwordForm.nextPassword = ''
    passwordForm.nextPasswordConfirm = ''
    passwordMessage.value = '관리자 비밀번호가 변경되었습니다.'
  } catch (error) {
    passwordMessage.value = error?.data?.message || '관리자 비밀번호 변경에 실패했습니다.'
  } finally {
    savingPassword.value = false
  }
}

/**
 * 저장 상태 토스트 표시
 * @param {'success'|'error'|'info'} type - 토스트 타입
 * @param {string} message - 표시 메시지
 * @returns {void}
 */
const showToast = (type, message) => {
  window.clearTimeout(toastTimer)
  toast.value = { type, message }
  toastTimer = window.setTimeout(() => {
    toast.value = null
  }, 3200)
}

/**
 * 사이트 설정 저장
 * @returns {Promise<void>} 저장 결과
 */
const saveSettings = async () => {
  saving.value = true
  errorMessage.value = ''
  showToast('info', '사이트 설정을 저장하는 중입니다.')

  try {
    const updatedSettings = await $fetch('/admin/api/settings', {
      method: 'PUT',
      body: {
        title: form.title,
        description: form.description,
        siteUrl: form.siteUrl,
        logoText: form.logoText,
        copyrightText: form.copyrightText
      }
    })

    Object.assign(form, updatedSettings)
    showToast('success', '사이트 설정이 저장되었습니다.')
  } catch (error) {
    errorMessage.value = error?.data?.message || '사이트 설정을 저장하지 못했습니다.'
    showToast('error', errorMessage.value)
  } finally {
    saving.value = false
  }
}

onBeforeUnmount(() => {
  window.clearTimeout(toastTimer)
})

onMounted(loadAdminProfile)
</script>

<template>
  <section class="admin-settings bg-paper p-6">
    <div class="admin-settings__header mb-8">
      <p class="admin-settings__eyebrow text-xs font-semibold uppercase text-muted">
        Settings
      </p>
      <h1 class="admin-settings__title mt-2 text-3xl font-semibold">
        사이트 설정
      </h1>
    </div>

    <p v-if="errorMessage" class="admin-settings__error mb-5 rounded border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
      {{ errorMessage }}
    </p>

    <section class="admin-settings__profile mb-6 max-w-3xl rounded border border-line bg-white p-5">
      <h2 class="text-base font-semibold text-ink">관리자 프로필</h2>
      <p class="mt-1 text-xs text-muted">
        썸네일과 이름을 수정할 수 있습니다.
      </p>

      <div v-if="loadingProfile" class="mt-4 text-sm text-muted">
        관리자 프로필을 불러오는 중입니다.
      </div>

      <div v-else class="mt-4 flex flex-col gap-4">
        <div class="flex flex-col gap-3 rounded border border-line bg-paper p-3 md:flex-row md:items-center">
          <div class="relative w-fit shrink-0">
            <button
              type="button"
              class="group relative h-24 w-24 overflow-hidden rounded-full border border-line bg-white"
              :disabled="uploadingAvatar || removingAvatar"
              @click="openAvatarFilePicker"
            >
              <img
                v-if="profileForm.avatarUrl"
                :src="profileForm.avatarUrl"
                alt="관리자 썸네일"
                class="h-full w-full object-cover"
              >
              <span
                v-else
                class="grid h-full w-full place-items-center text-2xl font-semibold text-muted"
              >
                {{ (profileForm.username || profileForm.email || '@').slice(0, 1).toUpperCase() }}
              </span>
              <span class="pointer-events-none absolute inset-0 grid place-items-center bg-black/45 text-[11px] font-medium text-white opacity-0 transition-opacity duration-200 group-hover:opacity-100">
                {{ profileForm.avatarUrl ? '이미지 변경' : '썸네일 등록' }}
              </span>
            </button>
            <button
              v-if="profileForm.avatarUrl"
              type="button"
              class="absolute right-0 top-0 grid h-6 w-6 -translate-y-1/3 translate-x-1/3 place-items-center rounded-full border border-line bg-paper text-xs text-muted transition-opacity hover:opacity-80 disabled:opacity-50"
              :disabled="removingAvatar"
              @click.stop="removeAvatar"
            >
              {{ removingAvatar ? '...' : 'X' }}
            </button>
          </div>
          <div class="grid min-w-0 flex-1 gap-3">
            <label class="grid gap-1 text-sm">
              <span class="text-xs text-muted">관리자 이름</span>
              <input
                v-model="profileForm.username"
                type="text"
                class="rounded border border-line bg-white px-3 py-2"
              >
            </label>
            <label class="grid gap-1 text-sm">
              <span class="text-xs text-muted">관리자 이메일</span>
              <input
                :value="profileForm.email"
                type="text"
                class="rounded border border-line bg-[#f7f7f5] px-3 py-2 text-muted"
                readonly
              >
            </label>
          </div>
        </div>

        <input
          ref="avatarInputRef"
          type="file"
          accept="image/jpeg,image/png,image/webp,image/gif"
          class="hidden"
          :disabled="uploadingAvatar"
          @change="uploadAvatar"
        >

        <div class="flex items-center gap-2">
          <button
            class="rounded bg-[#15171a] px-4 py-2 text-sm font-semibold text-white disabled:opacity-50"
            type="button"
            :disabled="savingProfile"
            @click="saveAdminProfile"
          >
            {{ savingProfile ? '저장 중' : '관리자 프로필 저장' }}
          </button>
          <p v-if="profileMessage" class="text-xs text-muted">
            {{ profileMessage }}
          </p>
        </div>
      </div>
    </section>

    <section class="admin-settings__password mb-6 max-w-3xl rounded border border-line bg-white p-5">
      <h2 class="text-base font-semibold text-ink">관리자 비밀번호 변경</h2>
      <p class="mt-1 text-xs text-muted">
        현재 비밀번호 확인 후 새 비밀번호로 변경할 수 있습니다.
      </p>

      <div class="mt-4 grid gap-3">
        <input
          v-model="passwordForm.currentPassword"
          type="password"
          class="rounded border border-line bg-white px-3 py-2 text-sm"
          placeholder="현재 비밀번호"
        >
        <input
          v-model="passwordForm.nextPassword"
          type="password"
          class="rounded border border-line bg-white px-3 py-2 text-sm"
          placeholder="새 비밀번호"
        >
        <input
          v-model="passwordForm.nextPasswordConfirm"
          type="password"
          class="rounded border border-line bg-white px-3 py-2 text-sm"
          placeholder="새 비밀번호 확인"
        >
      </div>

      <div class="mt-4 flex items-center gap-2">
        <button
          class="rounded bg-[#15171a] px-4 py-2 text-sm font-semibold text-white disabled:opacity-50"
          type="button"
          :disabled="savingPassword"
          @click="saveAdminPassword"
        >
          {{ savingPassword ? '변경 중' : '관리자 비밀번호 변경' }}
        </button>
        <p v-if="passwordMessage" class="text-xs text-muted">
          {{ passwordMessage }}
        </p>
      </div>
    </section>

    <form class="admin-settings__form grid max-w-3xl gap-6" @submit.prevent="saveSettings">
      <label class="admin-settings__field grid gap-2 text-sm">
        <span class="admin-settings__label font-medium">사이트 이름</span>
        <input
          v-model="form.title"
          class="admin-settings__input rounded border border-line bg-white px-3 py-2"
          type="text"
          required
        >
      </label>

      <label class="admin-settings__field grid gap-2 text-sm">
        <span class="admin-settings__label font-medium">사이트 설명</span>
        <textarea
          v-model="form.description"
          class="admin-settings__textarea min-h-28 resize-y rounded border border-line bg-white px-3 py-2"
        />
      </label>

      <label class="admin-settings__field grid gap-2 text-sm">
        <span class="admin-settings__label font-medium">사이트 URL</span>
        <input
          v-model="form.siteUrl"
          class="admin-settings__input rounded border border-line bg-white px-3 py-2"
          type="url"
          required
        >
      </label>

      <div class="admin-settings__grid grid gap-4 md:grid-cols-2">
        <label class="admin-settings__field grid gap-2 text-sm">
          <span class="admin-settings__label font-medium">로고 텍스트</span>
          <input
            v-model="form.logoText"
            class="admin-settings__input rounded border border-line bg-white px-3 py-2"
            type="text"
            maxlength="8"
            required
          >
        </label>

        <label class="admin-settings__field grid gap-2 text-sm">
          <span class="admin-settings__label font-medium">저작권 문구</span>
          <input
            v-model="form.copyrightText"
            class="admin-settings__input rounded border border-line bg-white px-3 py-2"
            type="text"
            required
          >
        </label>
      </div>

      <div class="admin-settings__preview rounded border border-line bg-white p-5">
        <p class="admin-settings__preview-label text-xs font-semibold uppercase text-muted">
          공개 화면 미리보기
        </p>
        <div class="admin-settings__preview-body mt-4 flex items-center gap-3">
          <div class="admin-settings__preview-logo grid h-12 w-12 place-items-center rounded-2xl bg-[#15171a] text-2xl font-bold text-white">
            {{ form.logoText || '井' }}
          </div>
          <div>
            <p class="admin-settings__preview-title font-semibold">
              {{ form.title || 'sori.studio' }}
            </p>
            <p class="admin-settings__preview-description text-sm text-muted">
              {{ form.description || '사이트 설명이 공개 화면에 표시됩니다.' }}
            </p>
          </div>
        </div>
      </div>

      <div class="admin-settings__actions flex justify-end border-t border-line pt-5">
        <button
          class="admin-settings__submit rounded bg-[#15171a] px-4 py-2 text-sm font-semibold text-white disabled:opacity-50"
          type="submit"
          :disabled="saving"
        >
          {{ saving ? '저장 중' : '설정 저장' }}
        </button>
      </div>
    </form>

    <div
      v-if="toast"
      class="admin-settings__toast fixed right-5 top-5 z-50 rounded border px-4 py-3 text-sm font-semibold shadow-lg"
      :class="{
        'border-green-200 bg-green-50 text-green-800': toast.type === 'success',
        'border-red-200 bg-red-50 text-red-800': toast.type === 'error',
        'border-line bg-white text-ink': toast.type === 'info'
      }"
      role="status"
    >
      {{ toast.message }}
    </div>
  </section>
</template>
