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

const { data: members } = await useFetch('/admin/api/members', {
  default: () => []
})
const roleSavingIds = ref([])
const roleMessage = ref('')

const roleOptions = [
  { value: 'owner', label: '소유자' },
  { value: 'admin', label: '관리자' },
  { value: 'member', label: '멤버' }
]

/**
 * 최근 접속 시각 표시 문자열을 반환한다.
 * @param {string | null} value - ISO 시각
 * @returns {string} 표시 문자열
 */
const formatLastSeen = (value) => {
  if (!value) {
    return '-'
  }

  const date = new Date(value)
  if (Number.isNaN(date.getTime())) {
    return '-'
  }

  return date.toLocaleString('ko-KR', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

/**
 * 권한 저장 진행 여부를 확인한다.
 * @param {string} memberId - 회원 ID
 * @returns {boolean} 진행 여부
 */
const isSavingRole = (memberId) => roleSavingIds.value.includes(memberId)

/**
 * 회원 권한을 변경한다.
 * @param {Object} member - 회원 정보
 * @returns {Promise<void>}
 */
const updateRole = async (member) => {
  if (!member?.id || isSavingRole(member.id)) {
    return
  }

  roleSavingIds.value = [...roleSavingIds.value, member.id]
  roleMessage.value = ''

  try {
    const result = await $fetch(`/admin/api/members/${member.id}/role`, {
      method: 'PUT',
      body: {
        role: member.roleCode
      }
    })

    members.value = members.value.map((item) => {
      if (item.id !== member.id) {
        return item
      }

      return {
        ...item,
        role: result.role,
        roleCode: result.roleCode,
        isAdmin: Boolean(result.isAdmin)
      }
    })

    roleMessage.value = '권한이 변경되었습니다.'
  } catch (error) {
    roleMessage.value = error?.data?.message || '권한 변경에 실패했습니다.'
  } finally {
    roleSavingIds.value = roleSavingIds.value.filter((id) => id !== member.id)
  }
}
</script>

<template>
  <section class="admin-members min-h-screen bg-paper">
    <div class="border-b border-line bg-paper px-6 py-5">
      <p class="text-xs font-semibold uppercase text-muted">Admin</p>
      <h1 class="mt-2 text-2xl font-semibold text-ink">멤버</h1>
    </div>

    <div class="px-6 py-5">
      <div class="overflow-x-auto rounded-[10px] border border-line bg-white">
        <table class="min-w-full text-left text-sm">
          <thead class="bg-[#f7f7f5] text-xs uppercase text-muted">
            <tr>
              <th class="px-3 py-2.5">닉네임</th>
              <th class="px-3 py-2.5">권한</th>
              <th class="px-3 py-2.5">이메일</th>
              <th class="px-3 py-2.5">최근 활동</th>
              <th class="px-3 py-2.5">접속 IP</th>
              <th class="px-3 py-2.5">활동 현황</th>
              <th class="px-3 py-2.5 text-right">댓글 개수</th>
              <th class="px-3 py-2.5 text-right">권한 변경</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="member in members" :key="member.id" class="border-t border-line/70">
              <td class="px-3 py-3">
                <div class="flex items-center gap-2">
                  <img
                    v-if="member.avatarUrl"
                    :src="member.avatarUrl"
                    :alt="member.username"
                    class="h-7 w-7 rounded-full object-cover"
                  >
                  <span v-else class="grid h-7 w-7 place-items-center rounded-full bg-[#efefec] text-xs font-semibold text-ink">
                    {{ (member.username || '?').slice(0, 1).toUpperCase() }}
                  </span>
                  <span>{{ member.username }}</span>
                </div>
              </td>
              <td class="px-3 py-3">
                <span
                  class="rounded-full border px-2 py-0.5 text-xs"
                  :class="member.roleCode === 'owner'
                    ? 'border-[#8a56ff]/35 text-[#8a56ff]'
                    : member.roleCode === 'admin'
                      ? 'border-[#ff4f2e]/30 text-[#ff4f2e]'
                      : 'border-line text-muted'"
                >
                  {{ member.role || '멤버' }}
                </span>
              </td>
              <td class="px-3 py-3 text-muted">{{ member.email }}</td>
              <td class="px-3 py-3 text-muted">{{ formatLastSeen(member.lastSeenAt) }}</td>
              <td class="px-3 py-3 text-muted">{{ member.lastSeenIp || '-' }}</td>
              <td class="px-3 py-3">
                <span class="rounded-full border border-line px-2 py-0.5 text-xs">{{ member.activityStatus }}</span>
              </td>
              <td class="px-3 py-3 text-right font-semibold text-ink">{{ member.commentCount }}</td>
              <td class="px-3 py-3">
                <div class="flex justify-end gap-2">
                  <select
                    v-model="member.roleCode"
                    class="rounded border border-line bg-white px-2 py-1 text-xs"
                    :disabled="isSavingRole(member.id)"
                  >
                    <option v-for="option in roleOptions" :key="option.value" :value="option.value">
                      {{ option.label }}
                    </option>
                  </select>
                  <button
                    type="button"
                    class="rounded border border-line px-2 py-1 text-xs font-semibold hover:bg-paper disabled:opacity-50"
                    :disabled="isSavingRole(member.id)"
                    @click="updateRole(member)"
                  >
                    {{ isSavingRole(member.id) ? '저장 중' : '저장' }}
                  </button>
                </div>
              </td>
            </tr>
            <tr v-if="members.length === 0">
              <td colspan="8" class="px-3 py-6 text-center text-sm text-muted">등록된 회원이 없습니다.</td>
            </tr>
          </tbody>
        </table>
      </div>
      <p v-if="roleMessage" class="mt-3 text-xs text-muted">
        {{ roleMessage }}
      </p>
    </div>
  </section>
</template>

