<template>
  <div>
    <AppHeader />
    
    <div class="container-fluid py-4">
      <div class="mb-4">
        <NuxtLink to="/employee" class="text-decoration-none">
          <i class="bi bi-arrow-left me-1"></i> 목록으로
        </NuxtLink>
      </div>

      <div class="row" v-if="employee">
        <div class="col-lg-6">
          <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
              <h5 class="mb-0">
                <i class="bi bi-person me-2"></i>직원 정보
              </h5>
              <span :class="employee.isActive ? 'badge bg-success' : 'badge bg-secondary'">
                {{ employee.isActive ? '재직' : '퇴직' }}
              </span>
            </div>
            <div class="card-body">
              <form @submit.prevent="updateEmployee">
                <div class="mb-3">
                  <label class="form-label">이름 <span class="text-danger">*</span></label>
                  <input type="text" class="form-control" v-model="form.employeeName" required />
                </div>
                <div class="mb-3">
                  <label class="form-label">이메일 <span class="text-danger">*</span></label>
                  <input type="email" class="form-control" v-model="form.employeeEmail" required />
                </div>
                <div class="mb-3">
                  <label class="form-label">소속사</label>
                  <select class="form-select" v-model="form.company">
                    <option value="(주)터보소프트">(주)터보소프트</option>
                    <option value="(주)코쿤">(주)코쿤</option>
                    <option value="(주)오솔정보기술">(주)오솔정보기술</option>
                  </select>
                </div>
                <div class="mb-3">
                  <label class="form-label">직급</label>
                  <select class="form-select" v-model="form.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 class="mb-3">
                  <label class="form-label">연락처</label>
                  <input type="text" class="form-control" v-model="form.employeePhone" />
                </div>
                <div class="mb-3">
                  <label class="form-label">입사일</label>
                  <input type="date" class="form-control" v-model="form.joinDate" />
                </div>
                <div class="mb-3">
                  <div class="form-check">
                    <input type="checkbox" class="form-check-input" id="isActive" v-model="form.isActive" />
                    <label class="form-check-label" for="isActive">재직중</label>
                  </div>
                </div>
                
                <div class="d-flex gap-2">
                  <button type="submit" class="btn btn-primary" :disabled="isSubmitting">
                    <i class="bi bi-save me-1"></i> 저장
                  </button>
                  <NuxtLink to="/employee" class="btn btn-outline-secondary">취소</NuxtLink>
                </div>
              </form>
            </div>
          </div>
        </div>

        <div class="col-lg-6">
          <!-- 기본 활동 정보 -->
          <div class="card mb-4">
            <div class="card-header">
              <i class="bi bi-info-circle me-2"></i>기본 정보
            </div>
            <div class="card-body">
              <div class="row">
                <div class="col-6 mb-3">
                  <small class="text-muted d-block">등록일</small>
                  <span>{{ formatDateTime(employee.createdAt) }}</span>
                </div>
                <div class="col-6 mb-3">
                  <small class="text-muted d-block">최종 수정</small>
                  <span>{{ formatDateTime(employee.updatedAt) }}</span>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 로그인 이력 -->
          <div class="card">
            <div class="card-header">
              <i class="bi bi-clock-history me-2"></i>로그인 이력
              <small class="text-muted ms-2">(최근 20건)</small>
            </div>
            <div class="card-body p-0">
              <div class="table-responsive">
                <table class="table table-sm table-hover mb-0">
                  <thead class="table-light">
                    <tr>
                      <th>로그인 시간</th>
                      <th>IP</th>
                      <th>로그아웃</th>
                      <th style="width: 80px">상태</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-if="loginHistory.length === 0">
                      <td colspan="4" class="text-center text-muted py-3">로그인 이력이 없습니다.</td>
                    </tr>
                    <tr v-for="h in loginHistory" :key="h.historyId">
                      <td>{{ formatDateTime(h.loginAt) }}</td>
                      <td><code class="small">{{ h.loginIp || '-' }}</code></td>
                      <td>{{ h.logoutAt ? formatDateTime(h.logoutAt) : '-' }}</td>
                      <td>
                        <span v-if="h.logoutAt" class="badge bg-secondary">로그아웃</span>
                        <span v-else-if="h.isCurrentSession" class="badge bg-success">접속중</span>
                        <span v-else class="badge bg-warning text-dark">세션만료</span>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="text-center py-5" v-else-if="isLoading">
        <div class="spinner-border text-primary"></div>
      </div>
    </div>
  </div>
</template>

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

const employee = ref<any>(null)
const loginHistory = ref<any[]>([])
const isLoading = ref(true)
const isSubmitting = ref(false)

const form = ref({
  employeeName: '',
  employeeEmail: '',
  company: '(주)터보소프트',
  employeePosition: '',
  employeePhone: '',
  joinDate: '',
  isActive: true
})

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

async function loadEmployee() {
  isLoading.value = true
  try {
    const res = await $fetch<{ employee: any, loginHistory: any[] }>(`/api/employee/${route.params.id}/detail`)
    employee.value = res.employee
    loginHistory.value = res.loginHistory || []
    
    const e = res.employee
    form.value = {
      employeeName: e.employeeName || '',
      employeeEmail: e.employeeEmail || '',
      company: e.company || '(주)터보소프트',
      employeePosition: e.employeePosition || '',
      employeePhone: e.employeePhone || '',
      joinDate: e.joinDate ? e.joinDate.split('T')[0] : '',
      isActive: e.isActive
    }
  } catch (e: any) {
    alert('직원 정보를 불러오는데 실패했습니다.')
    router.push('/employee')
  } finally {
    isLoading.value = false
  }
}

async function updateEmployee() {
  if (!form.value.employeeName || !form.value.employeeEmail) {
    alert('이름과 이메일은 필수입니다.')
    return
  }
  
  isSubmitting.value = true
  try {
    await $fetch(`/api/employee/${route.params.id}/update`, {
      method: 'PUT',
      body: form.value
    })
    alert('저장되었습니다.')
    await loadEmployee()
  } catch (e: any) {
    alert(e.data?.message || e.message || '저장에 실패했습니다.')
  } finally {
    isSubmitting.value = false
  }
}

function formatDateTime(dateStr: string) {
  if (!dateStr) return '-'
  const d = new Date(dateStr)
  return d.toLocaleString('ko-KR')
}
</script>
