<template>
  <div>
    <AppHeader />
    
    <div class="container py-4">
      <div v-if="isLoading" class="text-center py-5">
        <span class="spinner-border"></span>
        <p class="mt-2">로딩 중...</p>
      </div>
      
      <div v-else-if="report">
        <div class="d-flex justify-content-between align-items-center mb-4">
          <div>
            <h4 class="mb-1">
              <i class="bi bi-journal-text me-2"></i>주간보고
              <span :class="getStatusBadgeClass(report.reportStatus)" class="ms-2">
                {{ getStatusText(report.reportStatus) }}
              </span>
            </h4>
            <p class="text-muted mb-0">
              {{ report.reportYear }}년 {{ report.reportWeek }}주차
              ({{ formatDate(report.weekStartDate) }} ~ {{ formatDate(report.weekEndDate) }})
            </p>
          </div>
          <div class="d-flex gap-2">
            <NuxtLink to="/report/weekly" class="btn btn-outline-secondary">목록</NuxtLink>
            <button v-if="canEdit" class="btn btn-primary" @click="isEditing = !isEditing">
              {{ isEditing ? '취소' : '수정' }}
            </button>
            <button v-if="canSubmit" class="btn btn-success" @click="handleSubmit" :disabled="isSubmitting">
              <span v-if="isSubmitting" class="spinner-border spinner-border-sm me-1"></span>
              제출
            </button>
          </div>
        </div>
        
        <!-- 보기 모드 -->
        <div v-if="!isEditing">
          <!-- 프로젝트별 실적 -->
          <div class="card mb-4">
            <div class="card-header">
              <strong><i class="bi bi-folder me-2"></i>프로젝트별 실적</strong>
              <span class="badge bg-secondary ms-2">{{ projects.length }}개</span>
            </div>
            <div class="card-body">
              <div v-for="(proj, idx) in projects" :key="proj.detailId" 
                :class="{ 'border-top pt-3 mt-3': idx > 0 }">
                <h6 class="mb-3">
                  <i class="bi bi-folder2 me-1"></i>
                  {{ proj.projectName }}
                  <small class="text-muted">({{ proj.projectCode }})</small>
                </h6>
                <div class="row">
                  <div class="col-md-6 mb-3">
                    <label class="form-label text-muted small">금주 실적</label>
                    <div class="bg-light rounded p-3" style="white-space: pre-wrap;">{{ proj.workDescription || '-' }}</div>
                  </div>
                  <div class="col-md-6 mb-3">
                    <label class="form-label text-muted small">차주 계획</label>
                    <div class="bg-light rounded p-3" style="white-space: pre-wrap;">{{ proj.planDescription || '-' }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 공통 사항 -->
          <div class="card mb-4">
            <div class="card-header">
              <strong><i class="bi bi-chat-left-text me-2"></i>공통 사항</strong>
            </div>
            <div class="card-body">
              <div class="row">
                <div class="col-md-4 mb-3">
                  <label class="form-label text-muted small">이슈/리스크</label>
                  <div class="bg-light rounded p-3" style="white-space: pre-wrap;">{{ report.issueDescription || '-' }}</div>
                </div>
                <div class="col-md-4 mb-3">
                  <label class="form-label text-muted small">휴가일정</label>
                  <div class="bg-light rounded p-3" style="white-space: pre-wrap;">{{ report.vacationDescription || '-' }}</div>
                </div>
                <div class="col-md-4 mb-3">
                  <label class="form-label text-muted small">기타사항</label>
                  <div class="bg-light rounded p-3" style="white-space: pre-wrap;">{{ report.remarkDescription || '-' }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 수정 모드 -->
        <form v-else @submit.prevent="handleUpdate">
          <!-- 프로젝트별 실적 -->
          <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
              <strong><i class="bi bi-folder me-2"></i>프로젝트별 실적</strong>
              <button type="button" class="btn btn-sm btn-outline-primary" @click="showProjectModal = true">
                <i class="bi bi-plus"></i> 프로젝트 추가
              </button>
            </div>
            <div class="card-body">
              <div v-for="(proj, idx) in editForm.projects" :key="idx" class="border rounded p-3 mb-3">
                <div class="d-flex justify-content-between align-items-start mb-3">
                  <div>
                    <strong>{{ proj.projectName }}</strong>
                    <small class="text-muted ms-2">({{ proj.projectCode }})</small>
                  </div>
                  <button type="button" class="btn btn-sm btn-outline-danger" @click="removeProject(idx)">
                    <i class="bi bi-x"></i> 삭제
                  </button>
                </div>
                <div class="mb-3">
                  <label class="form-label">금주 실적</label>
                  <textarea class="form-control" rows="3" v-model="proj.workDescription"></textarea>
                </div>
                <div>
                  <label class="form-label">차주 계획</label>
                  <textarea class="form-control" rows="3" v-model="proj.planDescription"></textarea>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 공통 사항 -->
          <div class="card mb-4">
            <div class="card-header">
              <strong><i class="bi bi-chat-left-text me-2"></i>공통 사항</strong>
            </div>
            <div class="card-body">
              <div class="mb-3">
                <label class="form-label">이슈/리스크</label>
                <textarea class="form-control" rows="3" v-model="editForm.issueDescription"></textarea>
              </div>
              <div class="mb-3">
                <label class="form-label">휴가일정</label>
                <textarea class="form-control" rows="2" v-model="editForm.vacationDescription"></textarea>
              </div>
              <div>
                <label class="form-label">기타사항</label>
                <textarea class="form-control" rows="2" v-model="editForm.remarkDescription"></textarea>
              </div>
            </div>
          </div>
          
          <div class="d-flex justify-content-end gap-2">
            <button type="button" class="btn btn-secondary" @click="isEditing = false">취소</button>
            <button type="submit" class="btn btn-primary" :disabled="isSaving">
              <span v-if="isSaving" class="spinner-border spinner-border-sm me-1"></span>
              저장
            </button>
          </div>
        </form>
      </div>
    </div>
    
    <!-- 프로젝트 선택 모달 -->
    <div class="modal fade" :class="{ show: showProjectModal }" :style="{ display: showProjectModal ? 'block' : 'none' }" tabindex="-1">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">프로젝트 선택</h5>
            <button type="button" class="btn-close" @click="showProjectModal = false"></button>
          </div>
          <div class="modal-body">
            <div v-if="availableProjects.length === 0" class="text-center text-muted py-4">
              추가할 수 있는 프로젝트가 없습니다.
            </div>
            <div v-else class="list-group">
              <button type="button" class="list-group-item list-group-item-action"
                v-for="p in availableProjects" :key="p.projectId"
                @click="addProject(p)">
                <strong>{{ p.projectName }}</strong>
                <small class="text-muted ms-2">({{ p.projectCode }})</small>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="modal-backdrop fade show" v-if="showProjectModal" @click="showProjectModal = false"></div>
  </div>
</template>

<script setup lang="ts">
const { currentUser, fetchCurrentUser } = useAuth()
const router = useRouter()
const route = useRoute()

const reportId = route.params.id as string

const report = ref<any>(null)
const projects = ref<any[]>([])
const allProjects = ref<any[]>([])
const isLoading = ref(true)
const isEditing = ref(false)
const isSaving = ref(false)
const isSubmitting = ref(false)
const showProjectModal = ref(false)

interface EditProjectItem {
  projectId: number
  projectCode: string
  projectName: string
  workDescription: string
  planDescription: string
}

const editForm = ref({
  projects: [] as EditProjectItem[],
  issueDescription: '',
  vacationDescription: '',
  remarkDescription: ''
})

const canEdit = computed(() => {
  if (!report.value || !currentUser.value) return false
  return report.value.authorId === currentUser.value.employeeId && report.value.reportStatus === 'DRAFT'
})

const canSubmit = computed(() => {
  if (!report.value || !currentUser.value) return false
  return report.value.authorId === currentUser.value.employeeId && report.value.reportStatus === 'DRAFT'
})

const availableProjects = computed(() => {
  const addedIds = editForm.value.projects.map(p => p.projectId)
  return allProjects.value.filter(p => !addedIds.includes(p.projectId))
})

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

async function loadReport() {
  isLoading.value = true
  try {
    const res = await $fetch<any>(`/api/report/weekly/${reportId}/detail`)
    report.value = res.report
    projects.value = res.projects
  } catch (e: any) {
    alert(e.data?.message || '보고서를 불러올 수 없습니다.')
    router.push('/report/weekly')
  } finally {
    isLoading.value = false
  }
}

async function loadAllProjects() {
  try {
    const res = await $fetch<any>('/api/project/list')
    allProjects.value = res.projects || []
  } catch (e) {
    console.error(e)
  }
}

watch(isEditing, (val) => {
  if (val) {
    editForm.value = {
      projects: projects.value.map(p => ({
        projectId: p.projectId,
        projectCode: p.projectCode,
        projectName: p.projectName,
        workDescription: p.workDescription || '',
        planDescription: p.planDescription || ''
      })),
      issueDescription: report.value.issueDescription || '',
      vacationDescription: report.value.vacationDescription || '',
      remarkDescription: report.value.remarkDescription || ''
    }
  }
})

function addProject(p: any) {
  editForm.value.projects.push({
    projectId: p.projectId,
    projectCode: p.projectCode,
    projectName: p.projectName,
    workDescription: '',
    planDescription: ''
  })
  showProjectModal.value = false
}

function removeProject(idx: number) {
  editForm.value.projects.splice(idx, 1)
}

async function handleUpdate() {
  if (editForm.value.projects.length === 0) {
    alert('최소 1개 이상의 프로젝트가 필요합니다.')
    return
  }
  
  isSaving.value = true
  try {
    await $fetch(`/api/report/weekly/${reportId}/update`, {
      method: 'PUT',
      body: {
        projects: editForm.value.projects.map(p => ({
          projectId: p.projectId,
          workDescription: p.workDescription,
          planDescription: p.planDescription
        })),
        issueDescription: editForm.value.issueDescription,
        vacationDescription: editForm.value.vacationDescription,
        remarkDescription: editForm.value.remarkDescription
      }
    })
    alert('저장되었습니다.')
    isEditing.value = false
    await loadReport()
  } catch (e: any) {
    alert(e.data?.message || '저장에 실패했습니다.')
  } finally {
    isSaving.value = false
  }
}

async function handleSubmit() {
  if (!confirm('제출하시겠습니까? 제출 후에는 수정할 수 없습니다.')) return
  
  isSubmitting.value = true
  try {
    await $fetch(`/api/report/weekly/${reportId}/submit`, { method: 'POST' })
    alert('제출되었습니다.')
    await loadReport()
  } catch (e: any) {
    alert(e.data?.message || '제출에 실패했습니다.')
  } finally {
    isSubmitting.value = false
  }
}

function formatDate(dateStr: string) {
  if (!dateStr) return ''
  return dateStr.split('T')[0]
}

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
}
</script>

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