<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="summary">
        <!-- 취합 보고서 헤더 -->
        <div class="card mb-4">
          <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">
              <i class="bi bi-collection me-2"></i>
              {{ summary.projectName }} - {{ summary.reportYear }}-W{{ String(summary.reportWeek).padStart(2, '0') }}
            </h5>
            <span :class="getStatusBadgeClass(summary.summaryStatus)">
              {{ getStatusText(summary.summaryStatus) }}
            </span>
          </div>
          <div class="card-body">
            <div class="row">
              <div class="col-md-3">
                <label class="form-label text-muted">기간</label>
                <p class="mb-0">{{ formatDate(summary.weekStartDate) }} ~ {{ formatDate(summary.weekEndDate) }}</p>
              </div>
              <div class="col-md-2">
                <label class="form-label text-muted">참여 인원</label>
                <p class="mb-0">{{ summary.memberCount }}명</p>
              </div>
              <div class="col-md-2">
                <label class="form-label text-muted">총 투입시간</label>
                <p class="mb-0">{{ summary.totalWorkHours ? summary.totalWorkHours + '시간' : '-' }}</p>
              </div>
              <div class="col-md-3">
                <label class="form-label text-muted">취합일시</label>
                <p class="mb-0">{{ formatDateTime(summary.aggregatedAt) }}</p>
              </div>
            </div>
          </div>
        </div>

        <!-- AI 요약 -->
        <div class="card mb-4" v-if="summary.aiSummary">
          <div class="card-header bg-primary bg-opacity-10">
            <i class="bi bi-robot me-2"></i><strong>AI 요약</strong>
            <small class="text-muted ms-2" v-if="summary.aiSummaryAt">
              ({{ formatDateTime(summary.aiSummaryAt) }})
            </small>
          </div>
          <div class="card-body">
            <div class="ai-summary" v-html="renderMarkdown(summary.aiSummary)"></div>
          </div>
        </div>

        <!-- PM 검토 영역 -->
        <div class="card mb-4">
          <div class="card-header">
            <i class="bi bi-chat-square-text me-2"></i>PM 검토
          </div>
          <div class="card-body">
            <div v-if="summary.reviewerComment" class="mb-3">
              <div class="d-flex justify-content-between mb-2">
                <span class="text-muted">
                  <i class="bi bi-person me-1"></i>{{ summary.reviewerName || '검토자' }}
                </span>
                <small class="text-muted">{{ formatDateTime(summary.reviewedAt) }}</small>
              </div>
              <div class="p-3 bg-success bg-opacity-10 rounded">
                <pre class="mb-0" style="white-space: pre-wrap;">{{ summary.reviewerComment }}</pre>
              </div>
            </div>
            
            <div class="mt-3">
              <label class="form-label">코멘트 작성</label>
              <textarea 
                class="form-control" 
                v-model="reviewComment" 
                rows="3"
                placeholder="PM 코멘트를 입력하세요..."
              ></textarea>
              <button 
                class="btn btn-primary mt-2" 
                @click="submitReview"
                :disabled="isSubmitting"
              >
                <i class="bi bi-check-lg me-1"></i> 검토 완료
              </button>
            </div>
          </div>
        </div>

        <!-- 개별 보고서 목록 -->
        <div class="card">
          <div class="card-header">
            <i class="bi bi-list-ul me-2"></i>개별 보고서 ({{ reports.length }}건)
          </div>
          <div class="accordion accordion-flush" id="reportsAccordion">
            <div 
              v-for="(report, index) in reports" 
              :key="report.reportId" 
              class="accordion-item"
            >
              <h2 class="accordion-header">
                <button 
                  class="accordion-button collapsed" 
                  type="button" 
                  :data-bs-toggle="'collapse'" 
                  :data-bs-target="`#report-${report.reportId}`"
                >
                  <div class="d-flex justify-content-between w-100 me-3">
                    <span>
                      <i class="bi bi-person me-2"></i>
                      <strong>{{ report.authorName }}</strong>
                    </span>
                    <small class="text-muted">
                      {{ report.workHours ? report.workHours + 'h' : '' }}
                    </small>
                  </div>
                </button>
              </h2>
              <div 
                :id="`report-${report.reportId}`" 
                class="accordion-collapse collapse"
                data-bs-parent="#reportsAccordion"
              >
                <div class="accordion-body">
                  <!-- 금주 실적 -->
                  <div class="mb-3">
                    <label class="form-label text-muted small">
                      <i class="bi bi-check-circle me-1"></i>금주 실적
                    </label>
                    <div class="p-2 bg-light rounded">
                      <div v-if="report.workTasks && report.workTasks.length > 0">
                        <div v-for="(task, idx) in report.workTasks" :key="idx" class="mb-1">
                          <span class="badge me-1" :class="task.isCompleted ? 'bg-success' : 'bg-warning'">
                            {{ task.isCompleted ? '완료' : '진행' }}
                          </span>
                          <span class="small" style="white-space: pre-wrap;">{{ task.description }}</span>
                          <span class="text-muted small ms-1">({{ task.hours }}h)</span>
                        </div>
                      </div>
                      <div v-else class="small text-muted">-</div>
                    </div>
                  </div>
                  
                  <!-- 차주 계획 -->
                  <div class="mb-3" v-if="report.planTasks && report.planTasks.length > 0">
                    <label class="form-label text-muted small">
                      <i class="bi bi-calendar-event me-1"></i>차주 계획
                    </label>
                    <div class="p-2 bg-light rounded">
                      <div v-for="(task, idx) in report.planTasks" :key="idx" class="mb-1">
                        <span class="small" style="white-space: pre-wrap;">{{ task.description }}</span>
                        <span class="text-muted small ms-1">({{ task.hours }}h)</span>
                      </div>
                    </div>
                  </div>
                  
                  <!-- 이슈 -->
                  <div class="mb-3" v-if="report.issueDescription">
                    <label class="form-label text-muted small">
                      <i class="bi bi-exclamation-triangle me-1"></i>이슈/리스크
                    </label>
                    <div class="p-2 bg-warning bg-opacity-10 rounded">
                      <pre class="mb-0 small" style="white-space: pre-wrap;">{{ report.issueDescription }}</pre>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </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">
const { fetchCurrentUser, currentUser } = useAuth()
const router = useRouter()
const route = useRoute()

const summary = ref<any>(null)
const reports = ref<any[]>([])
const reviewComment = ref('')
const isLoading = ref(true)
const isSubmitting = ref(false)

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

async function loadSummary() {
  isLoading.value = true
  try {
    const res = await $fetch<{ summary: any; reports: any[] }>(`/api/report/summary/${route.params.id}/detail`)
    summary.value = res.summary
    reports.value = res.reports || []
    reviewComment.value = res.summary?.reviewerComment || ''
  } catch (e: any) {
    alert('취합 보고서를 불러오는데 실패했습니다.')
    router.push('/report/summary')
  } finally {
    isLoading.value = false
  }
}

async function submitReview() {
  isSubmitting.value = true
  try {
    await $fetch(`/api/report/summary/${route.params.id}/review`, {
      method: 'PUT',
      body: { comment: reviewComment.value }
    })
    await loadSummary()
    alert('검토가 완료되었습니다.')
  } catch (e: any) {
    alert(e.data?.message || e.message || '검토 저장에 실패했습니다.')
  } finally {
    isSubmitting.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 formatDate(dateStr: string) {
  const d = new Date(dateStr)
  return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`
}

function formatDateTime(dateStr: string) {
  if (!dateStr) return '-'
  const d = new Date(dateStr)
  return d.toLocaleString('ko-KR')
}

// 간단한 마크다운 렌더링
function renderMarkdown(text: string): string {
  if (!text) return ''
  return text
    // 헤더
    .replace(/^### (.+)$/gm, '<h5 class="mt-3 mb-2">$1</h5>')
    .replace(/^## (.+)$/gm, '<h4 class="mt-3 mb-2">$1</h4>')
    .replace(/^# (.+)$/gm, '<h3 class="mt-3 mb-2">$1</h3>')
    // 볼드
    .replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
    // 이탤릭
    .replace(/\*(.+?)\*/g, '<em>$1</em>')
    // 리스트
    .replace(/^- (.+)$/gm, '<li>$1</li>')
    .replace(/(<li>.*<\/li>\n?)+/g, '<ul class="mb-2">$&</ul>')
    // 줄바꿈
    .replace(/\n/g, '<br>')
}
</script>

<style scoped>
.ai-summary {
  line-height: 1.7;
}
.ai-summary h3, .ai-summary h4, .ai-summary h5 {
  color: #333;
}
.ai-summary ul {
  padding-left: 1.5rem;
}
.ai-summary li {
  margin-bottom: 0.25rem;
}
</style>
