<template>
  <div>
    <AppHeader />
    
    <div class="container-fluid py-4">
      <div class="d-flex justify-content-between align-items-center mb-4">
        <h4 class="mb-0"><i class="bi bi-folder me-2"></i>프로젝트 관리</h4>
        <button class="btn btn-primary" @click="showCreateModal = true">
          <i class="bi bi-plus-lg me-1"></i> 새 프로젝트
        </button>
      </div>

      <!-- 필터 -->
      <div class="card mb-3">
        <div class="card-body py-2">
          <div class="row g-2 align-items-center">
            <div class="col-1 text-end"><label class="col-form-label">프로젝트</label></div>
            <div class="col-2">
              <input type="text" class="form-control form-control-sm" v-model="searchKeyword" placeholder="프로젝트명/코드" @keyup.enter="loadProjects" />
            </div>
            <div class="col-1 text-end"><label class="col-form-label">사업</label></div>
            <div class="col-2">
              <select class="form-select form-select-sm" v-model="filterBusinessId" @change="loadProjects">
                <option value="">전체</option>
                <option v-for="b in businesses" :key="b.businessId" :value="b.businessId">{{ b.businessName }}</option>
              </select>
            </div>
            <div class="col-1 text-end"><label class="col-form-label">유형</label></div>
            <div class="col-1">
              <select class="form-select form-select-sm" v-model="filterType" @change="loadProjects">
                <option value="">전체</option>
                <option value="SI">SI</option>
                <option value="SM">SM</option>
              </select>
            </div>
            <div class="col-1 text-end"><label class="col-form-label">상태</label></div>
            <div class="col-2">
              <div class="btn-group" role="group">
                <input type="radio" class="btn-check" name="status" id="statusAll" value="" v-model="filterStatus" @change="loadProjects">
                <label class="btn btn-outline-secondary btn-sm" for="statusAll">전체</label>
                <input type="radio" class="btn-check" name="status" id="statusActive" value="ACTIVE" v-model="filterStatus" @change="loadProjects">
                <label class="btn btn-outline-secondary btn-sm" for="statusActive">진행</label>
                <input type="radio" class="btn-check" name="status" id="statusCompleted" value="COMPLETED" v-model="filterStatus" @change="loadProjects">
                <label class="btn btn-outline-secondary btn-sm" for="statusCompleted">완료</label>
              </div>
            </div>
            <div class="col-1">
              <button class="btn btn-outline-secondary btn-sm" @click="resetSearch">
                <i class="bi bi-arrow-counterclockwise"></i>
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 프로젝트 목록 -->
      <div class="card">
        <div class="card-header">
          프로젝트 목록 총 <strong>{{ filteredProjects.length }}</strong>건
        </div>
        <div class="table-responsive">
          <table class="table table-hover table-bordered mb-0">
            <thead class="table-light">
              <tr>
                <th style="width: 50px" class="text-center">No</th>
                <th style="width: 100px">코드</th>
                <th>프로젝트명</th>
                <th style="width: 120px">사업</th>
                <th style="width: 60px" class="text-center">유형</th>
                <th style="width: 120px">발주처</th>
                <th style="width: 180px">기간</th>
                <th style="width: 80px" class="text-center">상태</th>
              </tr>
            </thead>
            <tbody>
              <tr v-if="isLoading">
                <td colspan="8" class="text-center py-4">
                  <span class="spinner-border spinner-border-sm me-2"></span>로딩 중...
                </td>
              </tr>
              <tr v-else-if="filteredProjects.length === 0">
                <td colspan="8" class="text-center py-5 text-muted">
                  <i class="bi bi-inbox display-4"></i>
                  <p class="mt-2 mb-0">프로젝트가 없습니다.</p>
                </td>
              </tr>
              <tr v-else v-for="(project, idx) in filteredProjects" :key="project.projectId">
                <td class="text-center">{{ idx + 1 }}</td>
                <td><code>{{ project.projectCode || '-' }}</code></td>
                <td>
                  <NuxtLink :to="`/project/${project.projectId}`" class="text-decoration-none">
                    {{ project.projectName }}
                  </NuxtLink>
                </td>
                <td>{{ project.businessName || '-' }}</td>
                <td class="text-center">
                  <span :class="getTypeBadgeClass(project.projectType)">{{ project.projectType || 'SI' }}</span>
                </td>
                <td>{{ project.clientName || '-' }}</td>
                <td>
                  <small v-if="project.startDate">
                    {{ formatDate(project.startDate) }} ~ {{ formatDate(project.endDate) || '진행중' }}
                  </small>
                  <span v-else>-</span>
                </td>
                <td class="text-center">
                  <span :class="getStatusBadgeClass(project.projectStatus)">{{ getStatusText(project.projectStatus) }}</span>
                </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-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-4">
                <label class="form-label">프로젝트 유형 <span class="text-danger">*</span></label>
                <select class="form-select" v-model="newProject.projectType">
                  <option value="SI">SI (시스템 구축)</option>
                  <option value="SM">SM (시스템 유지보수)</option>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label">소속 사업</label>
                <select class="form-select" v-model="newProject.businessId">
                  <option value="">선택 안함</option>
                  <option v-for="b in businesses" :key="b.businessId" :value="b.businessId">{{ b.businessName }}</option>
                </select>
              </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-4">
                <label class="form-label">계약금액 (원)</label>
                <input type="number" class="form-control" v-model="newProject.contractAmount" />
              </div>
              <div class="col-md-4">
                <label class="form-label">시작일</label>
                <input type="date" class="form-control" v-model="newProject.startDate" />
              </div>
              <div class="col-md-4">
                <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" :disabled="isCreating">
              <span v-if="isCreating"><span class="spinner-border spinner-border-sm me-1"></span>등록 중...</span>
              <span v-else><i class="bi bi-check-lg me-1"></i>등록</span>
            </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()

interface Business { businessId: number; businessName: string }

const projects = ref<any[]>([])
const businesses = ref<Business[]>([])
const searchKeyword = ref('')
const filterBusinessId = ref('')
const filterType = ref('')
const filterStatus = ref('')
const showCreateModal = ref(false)
const isCreating = ref(false)
const isLoading = ref(false)

const newProject = ref({
  projectName: '',
  projectType: 'SI',
  businessId: '',
  clientName: '',
  contractAmount: null as number | 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 (filterType.value) {
    list = list.filter(p => p.projectType === filterType.value)
  }
  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 loadBusinesses()
  await loadProjects()
})

async function loadBusinesses() {
  try {
    const res = await $fetch<{ businesses: Business[] }>('/api/business/list')
    businesses.value = res.businesses || []
  } catch (e) {
    console.error('Load businesses error:', e)
  }
}

async function loadProjects() {
  isLoading.value = true
  try {
    const res = await $fetch<{ projects: any[] }>('/api/project/list', {
      query: {
        businessId: filterBusinessId.value || undefined,
        status: filterStatus.value || undefined
      }
    })
    projects.value = res.projects || []
  } catch (e) {
    console.error('Load projects error:', e)
  } finally {
    isLoading.value = false
  }
}

function resetSearch() {
  searchKeyword.value = ''
  filterBusinessId.value = ''
  filterType.value = ''
  filterStatus.value = ''
  loadProjects()
}

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

function resetNewProject() {
  newProject.value = {
    projectName: '',
    projectType: 'SI',
    businessId: '',
    clientName: '',
    contractAmount: null,
    startDate: '',
    endDate: '',
    projectDescription: ''
  }
}

function getTypeBadgeClass(type: string) {
  return type === 'SM' ? 'badge bg-info' : 'badge bg-primary'
}

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

function getStatusText(status: string) {
  const texts: Record<string, string> = { 'ACTIVE': '진행중', 'COMPLETED': '완료', 'HOLD': '보류' }
  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>
