<template>
  <div>
    <AppHeader />
    
    <div class="container-fluid py-4">
      <div class="mb-4">
        <h4><i class="bi bi-collection me-2"></i>취합 보고서</h4>
        <p class="text-muted mb-0">프로젝트별 주간보고 취합 목록</p>
      </div>

      <!-- 필터 -->
      <div class="card mb-4">
        <div class="card-body">
          <div class="row g-3">
            <div class="col-md-4">
              <label class="form-label">프로젝트</label>
              <select class="form-select" v-model="filter.projectId">
                <option value="">전체</option>
                <option v-for="p in projects" :key="p.projectId" :value="p.projectId">
                  {{ p.projectName }}
                </option>
              </select>
            </div>
            <div class="col-md-2">
              <label class="form-label">연도</label>
              <select class="form-select" v-model="filter.year">
                <option v-for="y in years" :key="y" :value="y">{{ y }}년</option>
              </select>
            </div>
            <div class="col-md-2 d-flex align-items-end">
              <button class="btn btn-outline-secondary" @click="loadSummaries">
                <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: 80px">주차</th>
                <th>프로젝트</th>
                <th style="width: 150px">기간</th>
                <th style="width: 100px">참여인원</th>
                <th style="width: 100px">총 시간</th>
                <th style="width: 100px">상태</th>
                <th style="width: 150px">취합일시</th>
                <th style="width: 80px">상세</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="summary in summaries" :key="summary.summaryId">
                <td>
                  <strong>W{{ String(summary.reportWeek).padStart(2, '0') }}</strong>
                </td>
                <td>{{ summary.projectName }}</td>
                <td>
                  <small>{{ formatDateRange(summary.weekStartDate, summary.weekEndDate) }}</small>
                </td>
                <td>
                  <span class="badge bg-primary">{{ summary.memberCount }}명</span>
                </td>
                <td>
                  {{ summary.totalWorkHours ? summary.totalWorkHours + 'h' : '-' }}
                </td>
                <td>
                  <span :class="getStatusBadgeClass(summary.summaryStatus)">
                    {{ getStatusText(summary.summaryStatus) }}
                  </span>
                </td>
                <td>
                  <small>{{ formatDateTime(summary.aggregatedAt) }}</small>
                </td>
                <td>
                  <NuxtLink 
                    :to="`/report/summary/${summary.summaryId}`" 
                    class="btn btn-sm btn-outline-primary"
                  >
                    <i class="bi bi-eye"></i>
                  </NuxtLink>
                </td>
              </tr>
              <tr v-if="summaries.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>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

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

const currentYear = new Date().getFullYear()
const years = [currentYear, currentYear - 1, currentYear - 2]

const filter = ref({
  projectId: '',
  year: currentYear
})

const summaries = ref<any[]>([])
const projects = ref<any[]>([])

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

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 loadSummaries() {
  try {
    const query: Record<string, any> = { year: filter.value.year }
    if (filter.value.projectId) query.projectId = filter.value.projectId
    
    const res = await $fetch<{ summaries: any[] }>('/api/report/summary/list', { query })
    summaries.value = res.summaries || []
  } catch (e) {
    console.error('Load summaries error:', e)
  }
}

function getStatusBadgeClass(status: string) {
  const classes: Record<string, string> = {
    'AGGREGATED': 'badge bg-info',
    'REVIEWED': 'badge bg-success'
  }
  return classes[status] || 'badge bg-secondary'
}

function getStatusText(status: string) {
  const texts: Record<string, string> = {
    'AGGREGATED': '취합완료',
    'REVIEWED': '검토완료'
  }
  return texts[status] || status
}

function formatDateRange(start: string, end: string) {
  const s = new Date(start)
  const e = new Date(end)
  return `${s.getMonth()+1}/${s.getDate()} ~ ${e.getMonth()+1}/${e.getDate()}`
}

function formatDateTime(dateStr: string) {
  if (!dateStr) return '-'
  const d = new Date(dateStr)
  return d.toLocaleString('ko-KR', { 
    month: '2-digit', day: '2-digit', 
    hour: '2-digit', minute: '2-digit' 
  })
}
</script>
