<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-journal-text me-2"></i>주간보고</h4>
          <p class="text-muted mb-0">내가 작성한 주간보고 목록</p>
        </div>
        <NuxtLink to="/report/weekly/write" class="btn btn-primary">
          <i class="bi bi-plus-lg me-1"></i> 새 보고서 작성
        </NuxtLink>
      </div>

      <!-- 필터 -->
      <div class="card mb-4">
        <div class="card-body">
          <div class="row g-3">
            <div class="col-md-3">
              <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">
              <label class="form-label">상태</label>
              <select class="form-select" v-model="filter.status">
                <option value="">전체</option>
                <option value="DRAFT">작성중</option>
                <option value="SUBMITTED">제출완료</option>
                <option value="AGGREGATED">취합완료</option>
              </select>
            </div>
            <div class="col-md-2 d-flex align-items-end">
              <button class="btn btn-outline-secondary" @click="loadReports">
                <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: 120px">기간</th>
                <th style="width: 100px">상태</th>
                <th style="width: 150px">작성일</th>
                <th style="width: 100px">작업</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="report in reports" :key="report.reportId">
                <td>
                  <strong>W{{ String(report.reportWeek).padStart(2, '0') }}</strong>
                </td>
                <td>{{ report.projectName }}</td>
                <td>
                  <small>{{ formatDateRange(report.weekStartDate, report.weekEndDate) }}</small>
                </td>
                <td>
                  <span :class="getStatusBadgeClass(report.reportStatus)">
                    {{ getStatusText(report.reportStatus) }}
                  </span>
                </td>
                <td>
                  <small>{{ formatDateTime(report.createdAt) }}</small>
                </td>
                <td>
                  <NuxtLink 
                    :to="`/report/weekly/${report.reportId}`" 
                    class="btn btn-sm btn-outline-primary"
                  >
                    <i class="bi bi-eye"></i>
                  </NuxtLink>
                  <button 
                    v-if="report.reportStatus === 'DRAFT'"
                    class="btn btn-sm btn-outline-success ms-1"
                    @click="submitReport(report.reportId)"
                  >
                    <i class="bi bi-send"></i>
                  </button>
                </td>
              </tr>
              <tr v-if="reports.length === 0">
                <td colspan="6" 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,
  status: ''
})

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

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

async function loadProjects() {
  try {
    const res = await $fetch<{ projects: any[] }>('/api/project/my-projects')
    projects.value = res.projects || []
  } catch (e) {
    console.error('Load projects error:', e)
  }
}

async function loadReports() {
  try {
    const query: Record<string, any> = { year: filter.value.year }
    if (filter.value.projectId) query.projectId = filter.value.projectId
    if (filter.value.status) query.status = filter.value.status
    
    const res = await $fetch<{ reports: any[] }>('/api/report/weekly/list', { query })
    reports.value = res.reports || []
  } catch (e) {
    console.error('Load reports error:', e)
  }
}

async function submitReport(reportId: number) {
  if (!confirm('보고서를 제출하시겠습니까?\n제출 후에는 수정이 제한됩니다.')) return
  
  try {
    await $fetch(`/api/report/weekly/${reportId}/submit`, { method: 'POST' })
    await loadReports()
  } catch (e: any) {
    alert(e.message || '제출에 실패했습니다.')
  }
}

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

function getStatusText(status: string) {
  const texts: Record<string, string> = {
    'DRAFT': '작성중',
    'SUBMITTED': '제출완료',
    'AGGREGATED': '취합완료'
  }
  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) {
  const d = new Date(dateStr)
  return d.toLocaleString('ko-KR', { 
    month: '2-digit', day: '2-digit', 
    hour: '2-digit', minute: '2-digit' 
  })
}
</script>
