<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-folder 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="프로젝트명 또는 코드 검색"
              />
            </div>
            <div class="col-md-2">
              <select class="form-select" v-model="filterStatus">
                <option value="">전체 상태</option>
                <option value="ACTIVE">진행중</option>
                <option value="COMPLETED">완료</option>
                <option value="HOLD">보류</option>
              </select>
            </div>
            <div class="col-md-2 d-flex align-items-end">
              <button class="btn btn-outline-secondary" @click="loadProjects">
                <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>프로젝트 코드</th>
                <th>프로젝트명</th>
                <th>발주처</th>
                <th style="width: 120px">기간</th>
                <th style="width: 100px">상태</th>
                <th style="width: 80px">상세</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="project in filteredProjects" :key="project.projectId">
                <td><code>{{ project.projectCode || '-' }}</code></td>
                <td>
                  <strong>{{ project.projectName }}</strong>
                </td>
                <td>{{ project.clientName || '-' }}</td>
                <td>
                  <small v-if="project.startDate">
                    {{ formatDate(project.startDate) }} ~
                    <br />{{ formatDate(project.endDate) || '진행중' }}
                  </small>
                  <span v-else>-</span>
                </td>
                <td>
                  <span :class="getStatusBadgeClass(project.projectStatus)">
                    {{ getStatusText(project.projectStatus) }}
                  </span>
                </td>
                <td>
                  <NuxtLink 
                    :to="`/project/${project.projectId}`" 
                    class="btn btn-sm btn-outline-primary"
                  >
                    <i class="bi bi-eye"></i>
                  </NuxtLink>
                </td>
              </tr>
              <tr v-if="filteredProjects.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 modal-lg">
        <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="row g-3">
              <div class="col-md-4">
                <label class="form-label">프로젝트 코드</label>
                <input type="text" class="form-control" v-model="newProject.projectCode" placeholder="예: 2026-KDCA-001" />
              </div>
              <div class="col-md-8">
                <label class="form-label">프로젝트명 <span class="text-danger">*</span></label>
                <input type="text" class="form-control" v-model="newProject.projectName" required />
              </div>
              <div class="col-md-6">
                <label class="form-label">발주처</label>
                <input type="text" class="form-control" v-model="newProject.clientName" />
              </div>
              <div class="col-md-6">
                <label class="form-label">계약금액 (원)</label>
                <input type="number" class="form-control" v-model="newProject.contractAmount" />
              </div>
              <div class="col-md-6">
                <label class="form-label">시작일</label>
                <input type="date" class="form-control" v-model="newProject.startDate" />
              </div>
              <div class="col-md-6">
                <label class="form-label">종료일</label>
                <input type="date" class="form-control" v-model="newProject.endDate" />
              </div>
              <div class="col-12">
                <label class="form-label">설명</label>
                <textarea class="form-control" v-model="newProject.projectDescription" rows="3"></textarea>
              </div>
            </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="createProject">
              <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 projects = ref<any[]>([])
const searchKeyword = ref('')
const filterStatus = ref('')
const showCreateModal = ref(false)

const newProject = ref({
  projectCode: '',
  projectName: '',
  clientName: '',
  contractAmount: null,
  startDate: '',
  endDate: '',
  projectDescription: ''
})

const filteredProjects = computed(() => {
  let list = projects.value
  
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    list = list.filter(p => 
      p.projectName?.toLowerCase().includes(keyword) ||
      p.projectCode?.toLowerCase().includes(keyword)
    )
  }
  
  if (filterStatus.value) {
    list = list.filter(p => p.projectStatus === filterStatus.value)
  }
  
  return list
})

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

async function loadProjects() {
  try {
    const res = await $fetch<{ projects: any[] }>('/api/project/list')
    projects.value = res.projects || []
  } catch (e) {
    console.error('Load projects error:', e)
  }
}

async function createProject() {
  if (!newProject.value.projectName) {
    alert('프로젝트명은 필수입니다.')
    return
  }
  
  try {
    await $fetch('/api/project/create', {
      method: 'POST',
      body: newProject.value
    })
    showCreateModal.value = false
    newProject.value = {
      projectCode: '',
      projectName: '',
      clientName: '',
      contractAmount: null,
      startDate: '',
      endDate: '',
      projectDescription: ''
    }
    await loadProjects()
  } catch (e: any) {
    alert(e.data?.message || e.message || '등록에 실패했습니다.')
  }
}

function getStatusBadgeClass(status: string) {
  const classes: Record<string, string> = {
    'ACTIVE': 'badge bg-success',
    'COMPLETED': 'badge bg-secondary',
    'HOLD': 'badge bg-warning',
    'CANCELLED': 'badge bg-danger'
  }
  return classes[status] || 'badge bg-secondary'
}

function getStatusText(status: string) {
  const texts: Record<string, string> = {
    'ACTIVE': '진행중',
    'COMPLETED': '완료',
    'HOLD': '보류',
    'CANCELLED': '취소'
  }
  return texts[status] || status
}

function formatDate(dateStr: string) {
  if (!dateStr) return ''
  const d = new Date(dateStr)
  return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`
}
</script>

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