<template>
  <div>
    <AppHeader />
    
    <div class="container py-4">
    <h2 class="mb-4">👤 마이페이지</h2>
    
    <!-- 내 정보 -->
    <div class="card mb-4">
      <div class="card-header d-flex justify-content-between align-items-center">
        <strong>내 정보</strong>
        <button v-if="!isEditing" class="btn btn-sm btn-outline-primary" @click="startEdit">
          수정
        </button>
      </div>
      <div class="card-body">
        <div v-if="isLoading" class="text-center py-4">
          <span class="spinner-border spinner-border-sm me-2"></span>로딩 중...
        </div>
        <div v-else>
          <!-- 보기 모드 -->
          <div v-if="!isEditing">
            <div class="row mb-2">
              <div class="col-3 text-muted">이름</div>
              <div class="col-9"><strong>{{ userInfo.employeeName }}</strong></div>
            </div>
            <div class="row mb-2">
              <div class="col-3 text-muted">이메일</div>
              <div class="col-9">{{ userInfo.employeeEmail }}</div>
            </div>
            <div class="row mb-2">
              <div class="col-3 text-muted">소속사</div>
              <div class="col-9">{{ userInfo.company || '-' }}</div>
            </div>
            <div class="row mb-2">
              <div class="col-3 text-muted">직급</div>
              <div class="col-9">{{ userInfo.employeePosition || '-' }}</div>
            </div>
            <div class="row mb-2">
              <div class="col-3 text-muted">연락처</div>
              <div class="col-9">{{ userInfo.employeePhone || '-' }}</div>
            </div>
            <div class="row mb-2">
              <div class="col-3 text-muted">입사일</div>
              <div class="col-9">{{ userInfo.joinDate ? userInfo.joinDate.split('T')[0] : '-' }}</div>
            </div>
          </div>
          
          <!-- 수정 모드 -->
          <form v-else @submit.prevent="saveProfile">
            <div class="row mb-3">
              <label class="col-3 col-form-label">이름</label>
              <div class="col-9">
                <input type="text" class="form-control" v-model="editForm.employeeName" required />
              </div>
            </div>
            <div class="row mb-3">
              <label class="col-3 col-form-label">이메일</label>
              <div class="col-9">
                <input type="email" class="form-control" :value="userInfo.employeeEmail" disabled />
                <small class="text-muted">이메일은 변경할 수 없습니다.</small>
              </div>
            </div>
            <div class="row mb-3">
              <label class="col-3 col-form-label">소속사</label>
              <div class="col-9">
                <select class="form-select" v-model="editForm.company">
                  <option value="(주)터보소프트">(주)터보소프트</option>
                  <option value="(주)코쿤">(주)코쿤</option>
                  <option value="(주)오솔정보기술">(주)오솔정보기술</option>
                </select>
              </div>
            </div>
            <div class="row mb-3">
              <label class="col-3 col-form-label">직급</label>
              <div class="col-9">
                <select class="form-select" v-model="editForm.employeePosition">
                  <option value="">선택</option>
                  <optgroup label="일반">
                    <option value="사원">사원</option>
                    <option value="대리">대리</option>
                    <option value="과장">과장</option>
                    <option value="차장">차장</option>
                    <option value="부장">부장</option>
                    <option value="이사">이사</option>
                  </optgroup>
                  <optgroup label="연구소">
                    <option value="연구원">연구원</option>
                    <option value="주임연구원">주임연구원</option>
                    <option value="선임연구원">선임연구원</option>
                    <option value="책임연구원">책임연구원</option>
                    <option value="수석연구원">수석연구원</option>
                    <option value="소장">소장</option>
                  </optgroup>
                </select>
              </div>
            </div>
            <div class="row mb-3">
              <label class="col-3 col-form-label">연락처</label>
              <div class="col-9">
                <input type="tel" class="form-control" v-model="editForm.employeePhone" placeholder="010-0000-0000" />
              </div>
            </div>
            <div class="row mb-3">
              <label class="col-3 col-form-label">입사일</label>
              <div class="col-9">
                <input type="date" class="form-control" v-model="editForm.joinDate" />
              </div>
            </div>
            <div class="text-end">
              <button type="button" class="btn btn-secondary me-2" @click="cancelEdit">취소</button>
              <button type="submit" class="btn btn-primary" :disabled="isSaving">
                <span v-if="isSaving" class="spinner-border spinner-border-sm me-1"></span>
                저장
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
    
    <!-- 로그인 이력 -->
    <div class="card">
      <div class="card-header">
        <strong>로그인 이력</strong>
        <small class="text-muted ms-2">(최근 50건)</small>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-hover mb-0">
            <thead class="table-light">
              <tr>
                <th style="width: 180px">로그인 시간</th>
                <th style="width: 130px">로그인 IP</th>
                <th style="width: 180px">로그아웃 시간</th>
                <th style="width: 130px">로그아웃 IP</th>
                <th style="width: 100px">상태</th>
              </tr>
            </thead>
            <tbody>
              <tr v-if="isLoadingHistory">
                <td colspan="5" class="text-center py-4">
                  <span class="spinner-border spinner-border-sm me-2"></span>로딩 중...
                </td>
              </tr>
              <tr v-else-if="loginHistory.length === 0">
                <td colspan="5" class="text-center py-4 text-muted">로그인 이력이 없습니다.</td>
              </tr>
              <tr v-else v-for="h in loginHistory" :key="h.historyId">
                <td>{{ formatDateTime(h.loginAt) }}</td>
                <td><code>{{ h.loginIp || '-' }}</code></td>
                <td>{{ h.logoutAt ? formatDateTime(h.logoutAt) : '-' }}</td>
                <td><code>{{ h.logoutIp || '-' }}</code></td>
                <td>
                  <span v-if="h.sessionStatus === 'logout'" class="badge bg-secondary">로그아웃</span>
                  <span v-else-if="h.isCurrentSession" class="badge bg-success">접속중</span>
                  <span v-else-if="h.sessionStatus === 'active'" class="badge bg-info">활성</span>
                  <span v-else class="badge bg-warning text-dark">세션만료</span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    </div>
  </div>
</template>

<script setup lang="ts">
const { fetchCurrentUser } = useAuth()
const router = useRouter()

const userInfo = ref<any>({})
const loginHistory = ref<any[]>([])
const isLoading = ref(true)
const isLoadingHistory = ref(true)
const isEditing = ref(false)
const isSaving = ref(false)

const editForm = ref({
  employeeName: '',
  company: '',
  employeePosition: '',
  employeePhone: '',
  joinDate: ''
})

onMounted(async () => {
  const user = await fetchCurrentUser()
  if (!user) {
    router.push('/login')
    return
  }
  loadUserInfo()
  loadLoginHistory()
})

async function loadUserInfo() {
  isLoading.value = true
  try {
    const res = await $fetch<any>('/api/auth/me')
    userInfo.value = res.user
  } catch (e) {
    console.error(e)
  } finally {
    isLoading.value = false
  }
}

async function loadLoginHistory() {
  isLoadingHistory.value = true
  try {
    const res = await $fetch<any>('/api/auth/login-history')
    loginHistory.value = res.history
  } catch (e) {
    console.error(e)
  } finally {
    isLoadingHistory.value = false
  }
}

function startEdit() {
  editForm.value = {
    employeeName: userInfo.value.employeeName || '',
    company: userInfo.value.company || '(주)터보소프트',
    employeePosition: userInfo.value.employeePosition || '',
    employeePhone: userInfo.value.employeePhone || '',
    joinDate: userInfo.value.joinDate ? userInfo.value.joinDate.split('T')[0] : ''
  }
  isEditing.value = true
}

function cancelEdit() {
  isEditing.value = false
}

async function saveProfile() {
  isSaving.value = true
  try {
    await $fetch(`/api/employee/${userInfo.value.employeeId}/update`, {
      method: 'PUT',
      body: editForm.value
    })
    alert('저장되었습니다.')
    isEditing.value = false
    loadUserInfo()
  } catch (e: any) {
    alert(e.data?.message || '저장에 실패했습니다.')
  } finally {
    isSaving.value = false
  }
}

function formatDateTime(dateStr: string) {
  if (!dateStr) return '-'
  const d = new Date(dateStr)
  return d.toLocaleString('ko-KR', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}
</script>
