<template>
  <div>
    <AppHeader />
    
    <div class="container py-4">
      <div class="row justify-content-center">
        <div class="col-lg-8">
          <!-- 헤더 -->
          <div class="d-flex justify-content-between align-items-center mb-4">
            <h4 class="mb-0">
              <i class="bi bi-person-plus me-2"></i>사용자 추가
            </h4>
            <NuxtLink to="/admin/user" class="btn btn-outline-secondary">
              <i class="bi bi-arrow-left me-1"></i>목록으로
            </NuxtLink>
          </div>

          <!-- 폼 -->
          <div class="card">
            <div class="card-body">
              <form @submit.prevent="saveUser">
                <div class="row mb-3">
                  <label class="col-3 col-form-label">이름 <span class="text-danger">*</span></label>
                  <div class="col-9">
                    <input type="text" class="form-control" v-model="form.employeeName" required />
                  </div>
                </div>

                <div class="row mb-3">
                  <label class="col-3 col-form-label">이메일 <span class="text-danger">*</span></label>
                  <div class="col-9">
                    <input type="email" class="form-control" v-model="form.employeeEmail" required />
                  </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="form.company">
                      <option value="">(선택)</option>
                      <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="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>
                        <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>
                      <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>
                      </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="form.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="form.joinDate" />
                  </div>
                </div>

                <div class="text-end">
                  <NuxtLink to="/admin/user" class="btn btn-secondary me-2">취소</NuxtLink>
                  <button type="submit" class="btn btn-primary" :disabled="!canSave || isSaving">
                    <span v-if="isSaving" class="spinner-border spinner-border-sm me-1"></span>
                    저장
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

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

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

const canSave = computed(() => {
  return form.value.employeeName.trim() && form.value.employeeEmail.trim()
})

onMounted(async () => {
  const user = await fetchCurrentUser()
  if (!user) {
    router.push('/login')
    return
  }
  
  if (!hasMenuAccess('ADMIN_USER')) {
    alert('접근 권한이 없습니다.')
    router.push('/')
    return
  }
})

async function saveUser() {
  if (!canSave.value) return
  
  isSaving.value = true
  try {
    await $fetch('/api/employee/create', {
      method: 'POST',
      body: {
        employeeName: form.value.employeeName,
        employeeEmail: form.value.employeeEmail,
        company: form.value.company || null,
        employeePosition: form.value.employeePosition || null,
        employeePhone: form.value.employeePhone || null,
        joinDate: form.value.joinDate || null
      }
    })
    
    alert('사용자가 등록되었습니다.')
    router.push('/admin/user')
  } catch (e: any) {
    console.error(e)
    alert(e.data?.message || '저장에 실패했습니다.')
  } finally {
    isSaving.value = false
  }
}
</script>
