<template>
  <div>
    <AppHeader />
    
    <div class="container-fluid py-4">
      <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
          <h4><i class="bi bi-people me-2"></i>직원 관리</h4>
          <p class="text-muted mb-0">총 {{ employees.length }}명</p>
        </div>
        <button class="btn btn-primary" @click="showCreateModal = true">
          <i class="bi bi-plus-lg me-1"></i> 직원 등록
        </button>
      </div>

      <!-- 검색 -->
      <div class="card mb-4">
        <div class="card-body">
          <div class="row g-3">
            <div class="col-md-4">
              <input 
                type="text" 
                class="form-control" 
                v-model="searchKeyword"
                placeholder="이름 또는 이메일 검색"
              />
            </div>
            <div class="col-md-2">
              <select class="form-select" v-model="filterStatus">
                <option value="">전체</option>
                <option value="active">재직</option>
                <option value="inactive">퇴직</option>
              </select>
            </div>
          </div>
        </div>
      </div>

      <!-- 사원 목록 -->
      <div class="card">
        <div class="table-responsive">
          <table class="table table-hover mb-0">
            <thead class="table-light">
              <tr>
                <th>이름</th>
                <th>이메일</th>
                <th style="width: 150px">소속사</th>
                <th style="width: 120px">직급</th>
                <th style="width: 100px">상태</th>
                <th style="width: 80px">상세</th>
              </tr>
            </thead>
            <tbody>
              <tr v-if="isLoading">
                <td colspan="6" class="text-center py-4">
                  <span class="spinner-border spinner-border-sm me-2"></span>로딩 중...
                </td>
              </tr>
              <tr v-else v-for="emp in filteredEmployees" :key="emp.employeeId">
                <td><strong>{{ emp.employeeName }}</strong></td>
                <td>{{ emp.employeeEmail }}</td>
                <td>{{ emp.company || '-' }}</td>
                <td>{{ emp.employeePosition || '-' }}</td>
                <td>
                  <span :class="emp.isActive !== false ? 'badge bg-success' : 'badge bg-secondary'">
                    {{ emp.isActive !== false ? '재직' : '퇴직' }}
                  </span>
                </td>
                <td>
                  <NuxtLink 
                    :to="`/employee/${emp.employeeId}`" 
                    class="btn btn-sm btn-outline-primary"
                  >
                    <i class="bi bi-eye"></i>
                  </NuxtLink>
                </td>
              </tr>
              <tr v-if="!isLoading && filteredEmployees.length === 0">
                <td colspan="6" class="text-center py-5 text-muted">
                  <i class="bi bi-inbox display-4"></i>
                  <p class="mt-2 mb-0">직원 정보가 없습니다.</p>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- 사원 등록 모달 -->
    <div class="modal fade" :class="{ show: showCreateModal }" :style="{ display: showCreateModal ? 'block' : 'none' }">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">직원 등록</h5>
            <button type="button" class="btn-close" @click="showCreateModal = false"></button>
          </div>
          <div class="modal-body">
            <div class="mb-3">
              <label class="form-label">이름 <span class="text-danger">*</span></label>
              <input type="text" class="form-control" v-model="newEmployee.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="newEmployee.employeeEmail" required />
            </div>
            <div class="mb-3">
              <label class="form-label">소속사</label>
              <select class="form-select" v-model="newEmployee.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="newEmployee.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="newEmployee.employeePhone" />
            </div>
            <div class="mb-3">
              <label class="form-label">입사일</label>
              <input type="date" class="form-control" v-model="newEmployee.joinDate" />
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" @click="showCreateModal = false">취소</button>
            <button type="button" class="btn btn-primary" @click="createEmployee">
              <i class="bi bi-check-lg me-1"></i> 등록
            </button>
          </div>
        </div>
      </div>
    </div>
    <div class="modal-backdrop fade show" v-if="showCreateModal"></div>
  </div>
</template>

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

const employees = ref<any[]>([])
const searchKeyword = ref('')
const filterStatus = ref('')
const showCreateModal = ref(false)
const isLoading = ref(true)

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

// 검색어/필터로 자동 필터링
const filteredEmployees = computed(() => {
  let list = employees.value
  
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    list = list.filter(e => 
      e.employeeName?.toLowerCase().includes(keyword) ||
      e.employeeEmail?.toLowerCase().includes(keyword)
    )
  }
  
  if (filterStatus.value === 'active') {
    list = list.filter(e => e.isActive !== false)
  } else if (filterStatus.value === 'inactive') {
    list = list.filter(e => e.isActive === false)
  }
  
  return list
})

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

async function loadEmployees() {
  isLoading.value = true
  try {
    const res = await $fetch<{ employees: any[] }>('/api/employee/list')
    employees.value = res.employees || []
  } catch (e) {
    console.error('Load employees error:', e)
  } finally {
    isLoading.value = false
  }
}

async function createEmployee() {
  if (!newEmployee.value.employeeName || !newEmployee.value.employeeEmail) {
    alert('이름과 이메일은 필수입니다.')
    return
  }
  
  try {
    await $fetch('/api/employee/create', {
      method: 'POST',
      body: newEmployee.value
    })
    showCreateModal.value = false
    newEmployee.value = {
      employeeName: '',
      employeeEmail: '',
      company: '(주)터보소프트',
      employeePosition: '',
      employeePhone: '',
      joinDate: ''
    }
    await loadEmployees()
  } catch (e: any) {
    alert(e.data?.message || e.message || '등록에 실패했습니다.')
  }
}
</script>

<style scoped>
.modal.show {
  background: rgba(0, 0, 0, 0.5);
}
</style>
