<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 align-items-end">
            <div class="col-md-2">
              <label class="form-label">연도</label>
              <select class="form-select" v-model="filter.year" @change="loadWeeklyList">
                <option v-for="y in years" :key="y" :value="y">{{ y }}년</option>
              </select>
            </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: 120px">주차</th>
                <th style="width: 180px">기간</th>
                <th>프로젝트</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="week in weeklyList" :key="week.reportWeek">
                <td>
                  <strong class="text-primary">{{ week.reportWeek }}주차</strong>
                </td>
                <td>
                  <small>{{ formatDateRange(week.weekStartDate, week.weekEndDate) }}</small>
                </td>
                <td>
                  <span class="badge bg-secondary me-1" v-for="p in week.projects.slice(0, 3)" :key="p">
                    {{ p }}
                  </span>
                  <span v-if="week.projects.length > 3" class="text-muted small">
                    +{{ week.projects.length - 3 }}개
                  </span>
                </td>
                <td>
                  <span class="badge bg-primary">{{ week.totalMembers }}명</span>
                </td>
                <td>
                  {{ week.totalWorkHours ? formatHours(week.totalWorkHours) : '-' }}
                </td>
                <td>
                  <small>{{ formatDateTime(week.latestAggregatedAt) }}</small>
                </td>
                <td>
                  <NuxtLink 
                    :to="`/report/summary/${filter.year}/${week.reportWeek}`" 
                    class="btn btn-sm btn-outline-primary"
                  >
                    <i class="bi bi-eye"></i>
                  </NuxtLink>
                </td>
              </tr>
              <tr v-if="weeklyList.length === 0">
                <td colspan="7" 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 modal-lg">
        <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="row mb-3">
              <div class="col-4">
                <label class="form-label">연도 <span class="text-danger">*</span></label>
                <select class="form-select" v-model="aggregateForm.reportYear" @change="loadAvailableProjects">
                  <option v-for="y in years" :key="y" :value="y">{{ y }}년</option>
                </select>
              </div>
              <div class="col-8">
                <label class="form-label">주차 <span class="text-danger">*</span></label>
                <select class="form-select" v-model="aggregateForm.reportWeek" @change="loadAvailableProjects">
                  <option v-for="w in 53" :key="w" :value="w">
                    {{ w }}주차 ({{ getWeekDateRange(aggregateForm.reportYear, w) }})
                  </option>
                </select>
              </div>
            </div>
            
            <!-- 프로젝트 선택 -->
            <div class="mb-3">
              <div class="d-flex justify-content-between align-items-center mb-2">
                <label class="form-label mb-0">프로젝트 선택 <span class="text-danger">*</span></label>
                <div>
                  <button type="button" class="btn btn-sm btn-outline-primary me-1" @click="selectAllAvailable">전체 선택</button>
                  <button type="button" class="btn btn-sm btn-outline-secondary" @click="deselectAllAvailable">전체 해제</button>
                </div>
              </div>
              
              <div v-if="isLoadingProjects" class="text-center py-3">
                <span class="spinner-border spinner-border-sm me-1"></span> 프로젝트 조회 중...
              </div>
              
              <div v-else-if="availableProjects.length === 0" class="alert alert-warning mb-0">
                <i class="bi bi-exclamation-triangle me-2"></i>
                해당 주차에 제출된 주간보고가 없습니다.
              </div>
              
              <div v-else class="border rounded p-3" style="max-height: 300px; overflow-y: auto;">
                <div class="row">
                  <div class="col-md-6" v-for="proj in availableProjects" :key="proj.projectId">
                    <div class="form-check mb-2">
                      <input type="checkbox" class="form-check-input" 
                        :id="'agg-proj-' + proj.projectId"
                        :value="proj.projectId"
                        v-model="aggregateForm.selectedProjectIds" />
                      <label class="form-check-label" :for="'agg-proj-' + proj.projectId">
                        {{ proj.projectName }}
                        <small class="text-muted">({{ proj.reportCount }}건)</small>
                      </label>
                    </div>
                  </div>
                </div>
              </div>
              
              <div class="text-muted small mt-2" v-if="availableProjects.length > 0">
                {{ aggregateForm.selectedProjectIds.length }} / {{ availableProjects.length }} 프로젝트 선택됨
              </div>
            </div>
            
            <div class="alert alert-info mb-0" v-if="aggregateForm.selectedProjectIds.length > 0">
              <i class="bi bi-info-circle me-2"></i>
              {{ aggregateForm.reportYear }}년 {{ aggregateForm.reportWeek }}주차, 
              {{ aggregateForm.selectedProjectIds.length }}개 프로젝트의 보고서를 취합합니다.
            </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 || aggregateForm.selectedProjectIds.length === 0">
              <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">
import { ref, watch, onMounted } from 'vue'

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({
  year: currentYear
})

const weeklyList = ref<any[]>([])

// 취합 모달
const showAggregateModal = ref(false)
const isAggregating = ref(false)
const isLoadingProjects = ref(false)
const availableProjects = ref<any[]>([])
const aggregateForm = ref({
  reportYear: currentYear,
  reportWeek: currentWeek.week > 1 ? currentWeek.week - 1 : 1,
  selectedProjectIds: [] as number[]
})

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

async function loadWeeklyList() {
  try {
    const res = await $fetch<{ weeks: any[] }>('/api/report/summary/weekly-list', {
      query: { year: filter.value.year }
    })
    weeklyList.value = res.weeks || []
  } catch (e) {
    console.error('Load weekly list error:', e)
  }
}

async function loadAvailableProjects() {
  isLoadingProjects.value = true
  try {
    const res = await $fetch<{ projects: any[] }>('/api/report/summary/available-projects', {
      query: {
        year: aggregateForm.value.reportYear,
        week: aggregateForm.value.reportWeek
      }
    })
    availableProjects.value = res.projects || []
    aggregateForm.value.selectedProjectIds = availableProjects.value.map(p => p.projectId)
  } catch (e) {
    console.error('Load available projects error:', e)
    availableProjects.value = []
  } finally {
    isLoadingProjects.value = false
  }
}

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

function selectAllAvailable() {
  aggregateForm.value.selectedProjectIds = availableProjects.value.map(p => p.projectId)
}

function deselectAllAvailable() {
  aggregateForm.value.selectedProjectIds = []
}

watch(showAggregateModal, (val) => {
  if (val) {
    loadAvailableProjects()
  }
})

function getWeekDateRange(year: number, week: number): string {
  const jan4 = new Date(year, 0, 4)
  const jan4Day = jan4.getDay() || 7
  const week1Monday = new Date(jan4)
  week1Monday.setDate(jan4.getDate() - jan4Day + 1)
  
  const monday = new Date(week1Monday)
  monday.setDate(week1Monday.getDate() + (week - 1) * 7)
  
  const sunday = new Date(monday)
  sunday.setDate(monday.getDate() + 6)
  
  const fmt = (d: Date) => `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`
  return `${fmt(monday)}~${fmt(sunday)}`
}

function formatDateRange(start: string, end: string) {
  if (!start || !end) return '-'
  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' })
}

function formatHours(hours: number): string {
  if (!hours || hours <= 0) return '0h'
  const days = Math.floor(hours / 8)
  const remain = hours % 8
  if (days === 0) return `${remain}h`
  if (remain === 0) return `${days}일`
  return `${days}일 ${remain}h`
}
</script>

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