<template>
  <div>
    <AppHeader />
    
    <div class="container-fluid py-4">
      <div class="mb-4">
        <NuxtLink to="/report/summary" class="text-decoration-none">
          <i class="bi bi-arrow-left me-1"></i> 목록으로
        </NuxtLink>
      </div>

      <div v-if="weekInfo">
        <!-- 주차 헤더 -->
        <div class="card mb-4">
          <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
            <h5 class="mb-0">
              <i class="bi bi-calendar-week me-2"></i>
              {{ weekInfo.reportYear }}년 {{ weekInfo.reportWeek }}주차 취합 보고서
            </h5>
            <button class="btn btn-light btn-sm" @click="doReaggregate" :disabled="isReaggregating">
              <span v-if="isReaggregating">
                <span class="spinner-border spinner-border-sm me-1"></span>처리중...
              </span>
              <span v-else>
                <i class="bi bi-arrow-repeat me-1"></i>취합 다시하기
              </span>
            </button>
          </div>
          <div class="card-body">
            <div class="row">
              <div class="col-md-3">
                <label class="form-label text-muted small">기간</label>
                <p class="mb-0 fw-bold">{{ formatDate(weekInfo.weekStartDate) }} ~ {{ formatDate(weekInfo.weekEndDate) }}</p>
              </div>
              <div class="col-md-3">
                <label class="form-label text-muted small">프로젝트</label>
                <p class="mb-0 fw-bold">{{ weekInfo.totalProjects }}개</p>
              </div>
              <div class="col-md-3">
                <label class="form-label text-muted small">총 투입시간</label>
                <p class="mb-0 fw-bold">{{ formatHours(weekInfo.totalWorkHours) }}</p>
              </div>
              <div class="col-md-3 text-end">
                <button class="btn btn-outline-primary btn-sm" @click="exportToExcel">
                  <i class="bi bi-file-earmark-excel me-1"></i>Excel 다운로드
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 프로젝트별 실적/계획 테이블 -->
        <div class="card mb-4">
          <div class="card-header">
            <i class="bi bi-table me-2"></i>프로젝트별 주간보고
          </div>
          <div class="table-responsive">
            <table class="table table-bordered mb-0 summary-table">
              <thead class="table-light">
                <tr>
                  <th style="width: 280px; min-width: 280px;" class="align-middle text-center">프로젝트</th>
                  <th class="align-middle text-center">
                    금주 실적
                    <i class="bi bi-robot text-info ms-1" title="AI 요약"></i>
                  </th>
                  <th class="align-middle text-center">
                    차주 계획
                    <i class="bi bi-robot text-info ms-1" title="AI 요약"></i>
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="proj in projects" :key="proj.projectId">
                  <td class="project-cell">
                    <div class="fw-bold text-primary mb-2">{{ proj.projectName }}</div>
                    <!-- 인원별 실적/계획 미니 테이블 -->
                    <table class="table table-sm table-bordered mb-0 mini-table" v-if="proj.memberHours?.length > 0">
                      <thead>
                        <tr class="table-secondary">
                          <th class="text-center" style="width: 40%">개발자</th>
                          <th class="text-center" style="width: 30%">실적</th>
                          <th class="text-center" style="width: 30%">계획</th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr v-for="(mh, idx) in proj.memberHours" :key="idx">
                          <td class="small">{{ mh.name }}</td>
                          <td class="text-center">
                            <span class="badge bg-primary">{{ formatMemberHours(mh.workHours) }}</span>
                          </td>
                          <td class="text-center">
                            <span class="badge bg-info">{{ formatMemberHours(mh.planHours) }}</span>
                          </td>
                        </tr>
                      </tbody>
                      <tfoot>
                        <tr class="table-light fw-bold">
                          <td class="text-center small">합계</td>
                          <td class="text-center">
                            <span class="badge bg-primary">{{ formatMemberHours(sumHours(proj.memberHours, 'workHours')) }}</span>
                          </td>
                          <td class="text-center">
                            <span class="badge bg-info">{{ formatMemberHours(sumHours(proj.memberHours, 'planHours')) }}</span>
                          </td>
                        </tr>
                      </tfoot>
                    </table>
                  </td>
                  <!-- 금주 실적 -->
                  <td class="task-cell">
                    <div v-if="!showRaw[proj.projectId]?.work">
                      <div class="ai-badge mb-2">
                        <i class="bi bi-robot me-1"></i>AI 요약
                      </div>
                      <div class="ai-content" v-html="renderMarkdown(proj.aiWorkSummary || '요약 없음')"></div>
                      <button class="btn btn-sm btn-link p-0 mt-2" @click="toggleRaw(proj.projectId, 'work')">
                        <i class="bi bi-list-ul me-1"></i>원문보기 ({{ proj.workTasks.length }}건)
                      </button>
                    </div>
                    <div v-else>
                      <button class="btn btn-sm btn-link p-0 mb-2" @click="toggleRaw(proj.projectId, 'work')">
                        <i class="bi bi-robot me-1"></i>AI 요약보기
                      </button>
                      <div v-if="proj.workTasks.length > 0">
                        <div v-for="(task, idx) in proj.workTasks" :key="'w'+idx" class="task-item">
                          <span class="badge me-1" :class="task.isCompleted ? 'bg-success' : 'bg-warning'">
                            {{ task.isCompleted ? '완료' : '진행' }}
                          </span>
                          <span class="task-desc">{{ task.description }}</span>
                          <span class="text-muted small ms-1">({{ task.authorName }}, {{ task.hours }}h)</span>
                        </div>
                      </div>
                      <div v-else class="text-muted">-</div>
                    </div>
                  </td>
                  <!-- 차주 계획 -->
                  <td class="task-cell">
                    <div v-if="!showRaw[proj.projectId]?.plan">
                      <div class="ai-badge mb-2">
                        <i class="bi bi-robot me-1"></i>AI 요약
                      </div>
                      <div class="ai-content" v-html="renderMarkdown(proj.aiPlanSummary || '요약 없음')"></div>
                      <button class="btn btn-sm btn-link p-0 mt-2" @click="toggleRaw(proj.projectId, 'plan')">
                        <i class="bi bi-list-ul me-1"></i>원문보기 ({{ proj.planTasks.length }}건)
                      </button>
                    </div>
                    <div v-else>
                      <button class="btn btn-sm btn-link p-0 mb-2" @click="toggleRaw(proj.projectId, 'plan')">
                        <i class="bi bi-robot me-1"></i>AI 요약보기
                      </button>
                      <div v-if="proj.planTasks.length > 0">
                        <div v-for="(task, idx) in proj.planTasks" :key="'p'+idx" class="task-item">
                          <span class="task-desc">{{ task.description }}</span>
                          <span class="text-muted small ms-1">({{ task.authorName }}, {{ task.hours }}h)</span>
                        </div>
                      </div>
                      <div v-else class="text-muted">-</div>
                    </div>
                  </td>
                </tr>
                <tr v-if="projects.length === 0">
                  <td colspan="3" class="text-center py-5 text-muted">
                    데이터가 없습니다.
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <!-- 인원별 시간 현황 -->
        <div class="card">
          <div class="card-header">
            <i class="bi bi-people me-2"></i>인원별 시간 현황
          </div>
          <div class="table-responsive">
            <table class="table table-hover mb-0">
              <thead class="table-light">
                <tr>
                  <th>이름</th>
                  <th class="text-center" style="width: 120px">금주 수행</th>
                  <th class="text-center" style="width: 120px">차주 계획</th>
                  <th class="text-center" style="width: 150px">차주 여유</th>
                  <th style="width: 200px">여유율</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="m in members" :key="m.employeeId">
                  <td>
                    <i class="bi bi-person me-1"></i>{{ m.employeeName }}
                  </td>
                  <td class="text-center">
                    <span class="badge bg-primary">{{ formatMemberHours(m.workHours) }}</span>
                  </td>
                  <td class="text-center">
                    <span class="badge bg-info">{{ formatMemberHours(m.planHours) }}</span>
                  </td>
                  <td class="text-center">
                    <span class="badge" :class="getAvailableClass(m.availableHours)">
                      {{ formatMemberHours(m.availableHours) }}
                    </span>
                  </td>
                  <td>
                    <div class="progress" style="height: 20px;">
                      <div 
                        class="progress-bar" 
                        :class="getProgressClass(m.planHours)"
                        :style="{ width: Math.min(100, (m.planHours / 40) * 100) + '%' }"
                      >
                        {{ Math.round((m.planHours / 40) * 100) }}%
                      </div>
                    </div>
                  </td>
                </tr>
                <tr v-if="members.length === 0">
                  <td colspan="5" class="text-center py-3 text-muted">
                    데이터가 없습니다.
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <div class="text-center py-5" v-else-if="isLoading">
        <div class="spinner-border text-primary"></div>
        <p class="mt-2 text-muted">로딩중...</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'

const router = useRouter()
const route = useRoute()
const { fetchCurrentUser } = useAuth()

const weekInfo = ref<any>(null)
const projects = ref<any[]>([])
const members = ref<any[]>([])
const isLoading = ref(true)
const isReaggregating = ref(false)
const showRaw = reactive<Record<number, { work: boolean, plan: boolean }>>({})

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

async function loadData() {
  isLoading.value = true
  try {
    const year = route.params.year
    const week = route.params.week
    
    const res = await $fetch<{ weekInfo: any; projects: any[]; members: any[] }>('/api/report/summary/week/detail', {
      query: { year, week }
    })
    
    weekInfo.value = res.weekInfo
    projects.value = res.projects || []
    members.value = res.members || []
    
    for (const p of projects.value) {
      showRaw[p.projectId] = { work: false, plan: false }
    }
  } catch (e: any) {
    alert(e.data?.message || '데이터를 불러오는데 실패했습니다.')
    router.push('/report/summary')
  } finally {
    isLoading.value = false
  }
}

async function doReaggregate() {
  if (!confirm('해당 주차의 모든 프로젝트를 다시 취합하시겠습니까?\nAI 요약이 새로 생성됩니다.')) {
    return
  }
  
  isReaggregating.value = true
  try {
    const projectIds = projects.value.map(p => p.projectId)
    
    await $fetch('/api/report/summary/aggregate', {
      method: 'POST',
      body: {
        projectIds,
        reportYear: weekInfo.value.reportYear,
        reportWeek: weekInfo.value.reportWeek
      }
    })
    
    alert('취합이 완료되었습니다.')
    await loadData()
  } catch (e: any) {
    alert(e.data?.message || '취합에 실패했습니다.')
  } finally {
    isReaggregating.value = false
  }
}

function toggleRaw(projectId: number, type: 'work' | 'plan') {
  if (!showRaw[projectId]) {
    showRaw[projectId] = { work: false, plan: false }
  }
  showRaw[projectId][type] = !showRaw[projectId][type]
}

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

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

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

function sumHours(members: any[], key: string): number {
  if (!members || members.length === 0) return 0
  return members.reduce((sum, m) => sum + (m[key] || 0), 0)
}

function renderMarkdown(text: string): string {
  if (!text) return ''
  return text
    .replace(/^### (.+)$/gm, '<strong>$1</strong><br>')
    .replace(/^## (.+)$/gm, '<strong>$1</strong><br>')
    .replace(/^# (.+)$/gm, '<strong>$1</strong><br>')
    .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.+?)\*/g, '<em>$1</em>')
    .replace(/^- (.+)$/gm, '• $1<br>')
    .replace(/\n/g, '<br>')
}

function getAvailableClass(hours: number): string {
  if (hours >= 16) return 'bg-success'
  if (hours >= 8) return 'bg-warning text-dark'
  return 'bg-danger'
}

function getProgressClass(planHours: number): string {
  const percent = (planHours / 40) * 100
  if (percent >= 100) return 'bg-danger'
  if (percent >= 80) return 'bg-warning'
  return 'bg-success'
}

function exportToExcel() {
  alert('Excel 다운로드 기능은 준비 중입니다.')
}
</script>

<style scoped>
.summary-table {
  table-layout: fixed;
}
.project-cell {
  vertical-align: top;
  background-color: #f8f9fa;
  padding: 0.75rem;
}
.task-cell {
  vertical-align: top;
  padding: 0.75rem;
}
.task-item {
  padding: 0.25rem 0;
  border-bottom: 1px dashed #eee;
}
.task-item:last-child {
  border-bottom: none;
}
.task-desc {
  white-space: pre-wrap;
  word-break: break-word;
}
.ai-badge {
  display: inline-block;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 0.15rem 0.5rem;
  border-radius: 4px;
  font-size: 0.75rem;
}
.ai-content {
  font-size: 0.9rem;
  line-height: 1.6;
  color: #333;
}
.mini-table {
  font-size: 0.8rem;
}
.mini-table th {
  padding: 0.25rem 0.5rem;
  font-weight: 600;
}
.mini-table td {
  padding: 0.2rem 0.4rem;
}
.mini-table .badge {
  font-size: 0.7rem;
}
</style>
