<template>
  <div>
    <AppHeader />
    
    <div class="container py-4">
      <h4 class="mb-4">
        <i class="bi bi-pencil-square me-2"></i>주간보고 작성
      </h4>
      
      <form @submit.prevent="handleSubmit">
        <!-- 주차 정보 -->
        <div class="card mb-4">
          <div class="card-header"><strong>보고 주차</strong></div>
          <div class="card-body">
            <div class="row align-items-end">
              <div class="col-auto">
                <div class="input-group">
                  <button type="button" class="btn btn-outline-secondary" @click="changeWeek(-1)">
                    <i class="bi bi-chevron-left"></i>
                  </button>
                  <span class="input-group-text bg-white" style="min-width: 160px;">
                    <strong>{{ form.reportYear }}년 {{ form.reportWeek }}주차</strong>
                  </span>
                  <button type="button" class="btn btn-outline-secondary" @click="changeWeek(1)">
                    <i class="bi bi-chevron-right"></i>
                  </button>
                </div>
              </div>
              <div class="col-auto">
                <div class="input-group">
                  <input type="date" class="form-control" v-model="form.weekStartDate" @change="updateWeekFromDate" />
                  <span class="input-group-text">~</span>
                  <input type="date" class="form-control" v-model="form.weekEndDate" readonly />
                </div>
              </div>
              <div class="col-auto">
                <button type="button" class="btn btn-outline-primary btn-sm" @click="setLastWeek">지난주</button>
                <button type="button" class="btn btn-outline-secondary btn-sm ms-1" @click="setThisWeek">이번주</button>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 프로젝트별 Task -->
        <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-if="projectGroups.length === 0" class="text-center text-muted py-4">
              프로젝트를 추가해주세요.
            </div>
            
            <div v-for="(group, gIdx) in projectGroups" :key="group.projectId" class="border rounded mb-4">
              <div class="card-header bg-light d-flex justify-content-between align-items-center">
                <span>
                  <i class="bi bi-folder2 me-2"></i>
                  <strong>{{ group.projectName }}</strong>
                  <small class="text-muted ms-2">({{ group.projectCode }})</small>
                </span>
                <button type="button" class="btn btn-sm btn-outline-danger" @click="removeProjectGroup(gIdx)">
                  <i class="bi bi-x"></i>
                </button>
              </div>
              <div class="card-body">
                <div class="row">
                  <!-- 금주 실적 -->
                  <div class="col-md-6">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                      <label class="form-label mb-0 fw-bold text-primary">
                        <i class="bi bi-check2-square me-1"></i>금주 실적
                        <span class="badge bg-primary ms-1">{{ formatHoursDisplay(getGroupWorkHours(group)) }}</span>
                      </label>
                      <button type="button" class="btn btn-sm btn-outline-primary" @click="addTask(group.projectId, 'WORK')">
                        <i class="bi bi-plus"></i>
                      </button>
                    </div>
                    <div v-for="(task, tIdx) in getWorkTasks(group.projectId)" :key="'work-'+tIdx" class="mb-2">
                      <div class="d-flex gap-2 align-items-start">
                        <div class="form-check pt-1">
                          <input type="checkbox" class="form-check-input" v-model="task.isCompleted" 
                            :id="'work-chk-'+group.projectId+'-'+tIdx" />
                          <label class="form-check-label small" :for="'work-chk-'+group.projectId+'-'+tIdx"
                            :class="task.isCompleted ? 'text-success' : 'text-warning'">
                            {{ task.isCompleted ? '완료' : '진행' }}
                          </label>
                        </div>
                        <textarea class="form-control form-control-sm" v-model="task.description" rows="2" placeholder="작업 내용"></textarea>
                        <div class="text-nowrap">
                          <input type="number" class="form-control form-control-sm text-end mb-1" style="width: 70px;" 
                            v-model.number="task.hours" min="0" step="0.5" placeholder="h" />
                          <div class="small text-muted text-end">{{ formatHours(task.hours) }}</div>
                        </div>
                        <button type="button" class="btn btn-sm btn-outline-danger" @click="removeTask(group.projectId, 'WORK', tIdx)">
                          <i class="bi bi-x"></i>
                        </button>
                      </div>
                    </div>
                  </div>
                  
                  <!-- 차주 계획 -->
                  <div class="col-md-6">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                      <label class="form-label mb-0 fw-bold text-success">
                        <i class="bi bi-calendar-check me-1"></i>차주 계획
                        <span class="badge bg-success ms-1">{{ formatHoursDisplay(getGroupPlanHours(group)) }}</span>
                      </label>
                      <button type="button" class="btn btn-sm btn-outline-success" @click="addTask(group.projectId, 'PLAN')">
                        <i class="bi bi-plus"></i>
                      </button>
                    </div>
                    <div v-for="(task, tIdx) in getPlanTasks(group.projectId)" :key="'plan-'+tIdx" class="mb-2">
                      <div class="d-flex gap-2 align-items-start">
                        <textarea class="form-control form-control-sm" v-model="task.description" rows="2" placeholder="계획 내용"></textarea>
                        <div class="text-nowrap">
                          <input type="number" class="form-control form-control-sm text-end mb-1" style="width: 70px;" 
                            v-model.number="task.hours" min="0" step="0.5" placeholder="h" />
                          <div class="small text-muted text-end">{{ formatHours(task.hours) }}</div>
                        </div>
                        <button type="button" class="btn btn-sm btn-outline-danger" @click="removeTask(group.projectId, 'PLAN', tIdx)">
                          <i class="bi bi-x"></i>
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 총계 -->
        <div class="card mb-4 border-primary" v-if="form.tasks.length > 0">
          <div class="card-body py-2">
            <div class="row text-center">
              <div class="col">
                <span class="text-muted">금주 실적 합계</span>
                <h5 class="mb-0 text-primary">{{ formatHoursDisplay(totalWorkHours) }}</h5>
              </div>
              <div class="col">
                <span class="text-muted">차주 계획 합계</span>
                <h5 class="mb-0 text-success">{{ formatHoursDisplay(totalPlanHours) }}</h5>
              </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">이슈/리스크</label>
                <textarea class="form-control" rows="3" v-model="form.issueDescription"></textarea>
              </div>
              <div class="col-md-4 mb-3">
                <label class="form-label">휴가일정</label>
                <textarea class="form-control" rows="3" v-model="form.vacationDescription"></textarea>
              </div>
              <div class="col-md-4 mb-3">
                <label class="form-label">기타사항</label>
                <textarea class="form-control" rows="3" v-model="form.remarkDescription"></textarea>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 버튼 -->
        <div class="d-flex justify-content-end gap-2">
          <NuxtLink to="/report/weekly" class="btn btn-secondary">취소</NuxtLink>
          <button type="submit" class="btn btn-primary" :disabled="isSaving || !canSubmit">
            <span v-if="isSaving" class="spinner-border spinner-border-sm me-1"></span>
            저장
          </button>
        </div>
      </form>
    </div>
    
    <!-- 프로젝트 선택 모달 -->
    <div class="modal fade" :class="{ show: showProjectModal }" :style="{ display: showProjectModal ? 'block' : 'none' }">
      <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="addProjectGroup(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 { fetchCurrentUser } = useAuth()
const router = useRouter()

interface TaskItem {
  projectId: number
  taskType: 'WORK' | 'PLAN'
  description: string
  hours: number
  isCompleted: boolean
}

interface ProjectGroup {
  projectId: number
  projectCode: string
  projectName: string
}

const allProjects = ref<any[]>([])
const showProjectModal = ref(false)
const isSaving = ref(false)

const form = ref({
  reportYear: new Date().getFullYear(),
  reportWeek: 1,
  weekStartDate: '',
  weekEndDate: '',
  tasks: [] as TaskItem[],
  issueDescription: '',
  vacationDescription: '',
  remarkDescription: ''
})

const projectGroups = computed<ProjectGroup[]>(() => {
  const projectIds = [...new Set(form.value.tasks.map(t => t.projectId))]
  return projectIds.map(pid => {
    const proj = allProjects.value.find(p => p.projectId === pid)
    return {
      projectId: pid,
      projectCode: proj?.projectCode || '',
      projectName: proj?.projectName || ''
    }
  })
})

const availableProjects = computed(() => {
  const usedIds = projectGroups.value.map(g => g.projectId)
  return allProjects.value.filter(p => !usedIds.includes(p.projectId))
})

const totalWorkHours = computed(() => 
  form.value.tasks.filter(t => t.taskType === 'WORK').reduce((sum, t) => sum + (t.hours || 0), 0)
)

const totalPlanHours = computed(() => 
  form.value.tasks.filter(t => t.taskType === 'PLAN').reduce((sum, t) => sum + (t.hours || 0), 0)
)

const canSubmit = computed(() => form.value.tasks.some(t => t.description.trim()))

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

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

// 주차 관련 함수들
function getMonday(date: Date): Date {
  const d = new Date(date)
  const day = d.getDay()
  const diff = d.getDate() - day + (day === 0 ? -6 : 1)
  d.setDate(diff)
  return d
}

function getSunday(monday: Date): Date {
  const d = new Date(monday)
  d.setDate(d.getDate() + 6)
  return d
}

function formatDate(date: Date): string {
  return date.toISOString().split('T')[0]
}

function getWeekNumber(date: Date): { year: number; week: number } {
  const d = new Date(date)
  d.setHours(0, 0, 0, 0)
  d.setDate(d.getDate() + 3 - (d.getDay() + 6) % 7)
  const week1 = new Date(d.getFullYear(), 0, 4)
  const weekNum = 1 + Math.round(((d.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7)
  return { year: d.getFullYear(), week: weekNum }
}

function setWeekDates(monday: Date) {
  const sunday = getSunday(monday)
  const weekInfo = getWeekNumber(monday)
  
  form.value.weekStartDate = formatDate(monday)
  form.value.weekEndDate = formatDate(sunday)
  form.value.reportYear = weekInfo.year
  form.value.reportWeek = weekInfo.week
}

function changeWeek(delta: number) {
  const currentMonday = new Date(form.value.weekStartDate)
  currentMonday.setDate(currentMonday.getDate() + (delta * 7))
  setWeekDates(currentMonday)
}

function setLastWeek() {
  const today = new Date()
  const lastWeekMonday = getMonday(today)
  lastWeekMonday.setDate(lastWeekMonday.getDate() - 7)
  setWeekDates(lastWeekMonday)
}

function setThisWeek() {
  const today = new Date()
  const thisWeekMonday = getMonday(today)
  setWeekDates(thisWeekMonday)
}

function updateWeekFromDate() {
  const startDate = new Date(form.value.weekStartDate)
  const monday = getMonday(startDate)
  setWeekDates(monday)
}

// Task 관련 함수들
function getWorkTasks(projectId: number) {
  return form.value.tasks.filter(t => t.projectId === projectId && t.taskType === 'WORK')
}

function getPlanTasks(projectId: number) {
  return form.value.tasks.filter(t => t.projectId === projectId && t.taskType === 'PLAN')
}

function getGroupWorkHours(group: ProjectGroup) {
  return getWorkTasks(group.projectId).reduce((sum, t) => sum + (t.hours || 0), 0)
}

function getGroupPlanHours(group: ProjectGroup) {
  return getPlanTasks(group.projectId).reduce((sum, t) => sum + (t.hours || 0), 0)
}

function addProjectGroup(project: any) {
  // 기본 Task 1개씩 추가
  form.value.tasks.push({
    projectId: project.projectId,
    taskType: 'WORK',
    description: '',
    hours: 0,
    isCompleted: true
  })
  form.value.tasks.push({
    projectId: project.projectId,
    taskType: 'PLAN',
    description: '',
    hours: 0,
    isCompleted: true
  })
  showProjectModal.value = false
}

function removeProjectGroup(gIdx: number) {
  const group = projectGroups.value[gIdx]
  form.value.tasks = form.value.tasks.filter(t => t.projectId !== group.projectId)
}

function addTask(projectId: number, taskType: 'WORK' | 'PLAN') {
  form.value.tasks.push({ projectId, taskType, description: '', hours: 0, isCompleted: true })
}

function removeTask(projectId: number, taskType: 'WORK' | 'PLAN', idx: number) {
  const tasks = form.value.tasks.filter(t => t.projectId === projectId && t.taskType === taskType)
  if (tasks.length <= 1) return // 최소 1개는 유지
  
  const targetTask = tasks[idx]
  const targetIndex = form.value.tasks.indexOf(targetTask)
  if (targetIndex > -1) {
    form.value.tasks.splice(targetIndex, 1)
  }
}

// 시간 표시 함수
function formatHours(hours: number): string {
  if (!hours || hours <= 0) return '-'
  const days = Math.floor(hours / 8)
  const remainHours = hours % 8
  
  if (days === 0) return `${remainHours}h`
  if (remainHours === 0) return `${days}일`
  return `${days}일 ${remainHours}h`
}

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

async function handleSubmit() {
  const validTasks = form.value.tasks.filter(t => t.description.trim())
  if (validTasks.length === 0) {
    alert('최소 1개 이상의 Task를 입력해주세요.')
    return
  }
  
  isSaving.value = true
  try {
    await $fetch('/api/report/weekly/create', {
      method: 'POST',
      body: {
        reportYear: form.value.reportYear,
        reportWeek: form.value.reportWeek,
        weekStartDate: form.value.weekStartDate,
        weekEndDate: form.value.weekEndDate,
        tasks: validTasks.map(t => ({
          projectId: t.projectId,
          taskType: t.taskType,
          taskDescription: t.description,
          taskHours: t.hours || 0,
          isCompleted: t.taskType === 'WORK' ? t.isCompleted : undefined
        })),
        issueDescription: form.value.issueDescription,
        vacationDescription: form.value.vacationDescription,
        remarkDescription: form.value.remarkDescription
      }
    })
    alert('주간보고가 작성되었습니다.')
    router.push('/report/weekly')
  } catch (e: any) {
    alert(e.data?.message || '저장에 실패했습니다.')
  } finally {
    isSaving.value = false
  }
}
</script>

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