<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">직원 정보 관리</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="이름 또는 이메일 검색"
                @keyup.enter="loadEmployees"
              />
            </div>
            <div class="col-md-2 d-flex align-items-end">
              <button class="btn btn-outline-secondary" @click="loadEmployees">
                <i class="bi bi-search me-1"></i> 조회
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 사원 목록 -->
      <div class="card">
        <div class="table-responsive">
          <table class="table table-hover mb-0">
            <thead class="table-light">
              <tr>
                <th style="width: 100px">사번</th>
                <th>이름</th>
                <th>이메일</th>
                <th style="width: 100px">직급</th>
                <th style="width: 100px">상태</th>
                <th style="width: 80px">상세</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="emp in employees" :key="emp.employeeId">
                <td><code>{{ emp.employeeNumber || '-' }}</code></td>
                <td><strong>{{ emp.employeeName }}</strong></td>
                <td>{{ emp.employeeEmail }}</td>
                <td>{{ emp.employeePosition || '-' }}</td>
                <td>
                  <span :class="emp.isActive ? 'badge bg-success' : 'badge bg-secondary'">
                    {{ emp.isActive ? '재직' : '퇴직' }}
                  </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="employees.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>
              <input type="text" class="form-control" v-model="newEmployee.employeeNumber" />
            </div>
            <div class="mb-3">
              <label class="form-label">직급</label>
              <select class="form-select" v-model="newEmployee.employeePosition">
                <option value="">선택</option>
                <option value="사원">사원</option>
                <option value="대리">대리</option>
                <option value="과장">과장</option>
                <option value="차장">차장</option>
                <option value="부장">부장</option>
                <option value="이사">이사</option>
              </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 showCreateModal = ref(false)

const newEmployee = ref({
  employeeName: '',
  employeeEmail: '',
  employeeNumber: '',
  employeePosition: '',
  employeePhone: '',
  joinDate: ''
})

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

async function loadEmployees() {
  try {
    const query: Record<string, any> = {}
    if (searchKeyword.value) query.keyword = searchKeyword.value
    
    const res = await $fetch<{ employees: any[] }>('/api/employee/list', { query })
    employees.value = res.employees || []
  } catch (e) {
    console.error('Load employees error:', e)
  }
}

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: '',
      employeeNumber: '',
      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>
