<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-collection me-2"></i>취합 보고서</h4>
          <p class="text-muted mb-0">프로젝트별 주간보고 취합 목록</p>
        </div>
        <button class="btn btn-primary" @click="showAggregateModal = 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">
              <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 class="modal fade" :class="{ show: showAggregateModal }" 
         :style="{ display: showAggregateModal ? 'block' : 'none' }"
         tabindex="-1">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">
              <i class="bi bi-collection me-2"></i>주간보고 취합
            </h5>
            <button type="button" class="btn-close" @click="showAggregateModal = false"></button>
          </div>
          <div class="modal-body">
            <div class="mb-3">
              <label class="form-label">프로젝트 <span class="text-danger">*</span></label>
              <select class="form-select" v-model="aggregateForm.projectId">
                <option value="">선택하세요</option>
                <option v-for="p in projects" :key="p.projectId" :value="p.projectId">
                  {{ p.projectName }}
                </option>
              </select>
            </div>
            <div class="row">
              <div class="col-6">
                <label class="form-label">연도 <span class="text-danger">*</span></label>
                <select class="form-select" v-model="aggregateForm.reportYear">
                  <option v-for="y in years" :key="y" :value="y">{{ y }}년</option>
                </select>
              </div>
              <div class="col-6">
                <label class="form-label">주차 <span class="text-danger">*</span></label>
                <select class="form-select" v-model="aggregateForm.reportWeek">
                  <option v-for="w in 53" :key="w" :value="w">W{{ String(w).padStart(2, '0') }}</option>
                </select>
              </div>
            </div>
            <div class="alert alert-info mt-3 mb-0">
              <i class="bi bi-info-circle me-2"></i>
              선택한 프로젝트/주차의 제출된 보고서를 취합합니다.
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" @click="showAggregateModal = false">
              취소
            </button>
            <button type="button" class="btn btn-primary" @click="doAggregate" :disabled="isAggregating">
              <span v-if="isAggregating">
                <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="showAggregateModal"></div>
  </div>
</template>

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

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

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

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

// 취합 모달
const showAggregateModal = ref(false)
const isAggregating = ref(false)
const aggregateForm = ref({
  projectId: '',
  reportYear: currentYear,
  reportWeek: currentWeek.week > 1 ? currentWeek.week - 1 : 1  // 기본값: 지난주
})

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)
  }
}

async function doAggregate() {
  if (!aggregateForm.value.projectId) {
    alert('프로젝트를 선택해주세요.')
    return
  }
  
  isAggregating.value = true
  try {
    const res = await $fetch<{ success: boolean; memberCount: number }>('/api/report/summary/aggregate', {
      method: 'POST',
      body: {
        projectId: parseInt(aggregateForm.value.projectId as string),
        reportYear: aggregateForm.value.reportYear,
        reportWeek: aggregateForm.value.reportWeek
      }
    })
    
    alert(`취합 완료! (${res.memberCount}명의 보고서)`)
    showAggregateModal.value = false
    await loadSummaries()
  } catch (e: any) {
    alert(e.data?.message || '취합에 실패했습니다.')
  } finally {
    isAggregating.value = false
  }
}

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>

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