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

      <div v-if="project">
        <!-- 프로젝트 기본 정보 -->
        <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-folder me-2"></i>{{ project.projectName }}
            </h5>
            <span :class="getStatusBadgeClass(project.projectStatus)">
              {{ getStatusText(project.projectStatus) }}
            </span>
          </div>
          <div class="card-body">
            <div class="row g-4">
              <div class="col-md-3">
                <label class="form-label text-muted">프로젝트 코드</label>
                <p class="mb-0"><code>{{ project.projectCode || '-' }}</code></p>
              </div>
              <div class="col-md-3">
                <label class="form-label text-muted">발주처</label>
                <p class="mb-0">{{ project.clientName || '-' }}</p>
              </div>
              <div class="col-md-3">
                <label class="form-label text-muted">계약금액</label>
                <p class="mb-0">{{ formatMoney(project.contractAmount) }}</p>
              </div>
              <div class="col-md-3">
                <label class="form-label text-muted">기간</label>
                <p class="mb-0">
                  {{ project.startDate ? formatDate(project.startDate) : '-' }} ~
                  {{ project.endDate ? formatDate(project.endDate) : '진행중' }}
                </p>
              </div>
              <div class="col-12" v-if="project.projectDescription">
                <label class="form-label text-muted">설명</label>
                <p class="mb-0">{{ project.projectDescription }}</p>
              </div>
            </div>
          </div>
        </div>

        <!-- PM/PL 이력 -->
        <div class="card mb-4">
          <div class="card-header d-flex justify-content-between align-items-center">
            <span><i class="bi bi-person-badge me-2"></i>PM/PL 담당 이력</span>
            <button class="btn btn-sm btn-primary" @click="showAssignModal = true">
              <i class="bi bi-plus"></i> 담당자 지정
            </button>
          </div>
          <div class="table-responsive">
            <table class="table table-sm mb-0">
              <thead class="table-light">
                <tr>
                  <th style="width: 80px">역할</th>
                  <th>담당자</th>
                  <th style="width: 200px">기간</th>
                  <th>비고</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="m in managers" :key="m.historyId">
                  <td>
                    <span :class="m.roleType === 'PM' ? 'badge bg-primary' : 'badge bg-info'">
                      {{ m.roleType }}
                    </span>
                  </td>
                  <td>{{ m.employeeName }}</td>
                  <td>
                    {{ formatDate(m.startDate) }} ~
                    {{ m.endDate ? formatDate(m.endDate) : '현재' }}
                  </td>
                  <td>{{ m.changeReason || '-' }}</td>
                </tr>
                <tr v-if="managers.length === 0">
                  <td colspan="4" class="text-center text-muted py-3">
                    담당자 이력이 없습니다.
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <!-- 참여자 통계 (주간보고 작성 기준) -->
        <div class="card">
          <div class="card-header">
            <i class="bi bi-people me-2"></i>참여자 현황
          </div>
          <div class="card-body">
            <div class="row g-3">
              <div class="col-md-3" v-for="member in members" :key="member.employeeId">
                <div class="p-3 border rounded">
                  <strong>{{ member.employeeName }}</strong>
                  <br />
                  <small class="text-muted">{{ member.reportCount }}건 보고</small>
                </div>
              </div>
              <div class="col-12 text-center text-muted py-3" v-if="members.length === 0">
                아직 주간보고를 작성한 참여자가 없습니다.
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="text-center py-5" v-else-if="isLoading">
        <div class="spinner-border text-primary"></div>
      </div>
    </div>

    <!-- 담당자 지정 모달 -->
    <div class="modal fade" :class="{ show: showAssignModal }" :style="{ display: showAssignModal ? 'block' : 'none' }">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">PM/PL 담당자 지정</h5>
            <button type="button" class="btn-close" @click="showAssignModal = false"></button>
          </div>
          <div class="modal-body">
            <div class="mb-3">
              <label class="form-label">역할 <span class="text-danger">*</span></label>
              <select class="form-select" v-model="assignForm.roleType">
                <option value="PM">PM</option>
                <option value="PL">PL</option>
              </select>
            </div>
            <div class="mb-3">
              <label class="form-label">담당자 <span class="text-danger">*</span></label>
              <select class="form-select" v-model="assignForm.employeeId">
                <option value="">선택하세요</option>
                <option v-for="e in employees" :key="e.employeeId" :value="e.employeeId">
                  {{ e.employeeName }} ({{ e.employeeEmail }})
                </option>
              </select>
            </div>
            <div class="mb-3">
              <label class="form-label">시작일 <span class="text-danger">*</span></label>
              <input type="date" class="form-control" v-model="assignForm.startDate" />
            </div>
            <div class="mb-3">
              <label class="form-label">변경 사유</label>
              <input type="text" class="form-control" v-model="assignForm.changeReason" />
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" @click="showAssignModal = false">취소</button>
            <button type="button" class="btn btn-primary" @click="assignManager">
              <i class="bi bi-check-lg me-1"></i> 지정
            </button>
          </div>
        </div>
      </div>
    </div>
    <div class="modal-backdrop fade show" v-if="showAssignModal"></div>
  </div>
</template>

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

const project = ref<any>(null)
const managers = ref<any[]>([])
const members = ref<any[]>([])
const employees = ref<any[]>([])
const isLoading = ref(true)
const showAssignModal = ref(false)

const assignForm = ref({
  roleType: 'PM',
  employeeId: '',
  startDate: new Date().toISOString().split('T')[0],
  changeReason: ''
})

onMounted(async () => {
  const user = await fetchCurrentUser()
  if (!user) {
    router.push('/login')
    return
  }
  
  await Promise.all([loadProject(), loadEmployees()])
})

async function loadProject() {
  isLoading.value = true
  try {
    const res = await $fetch<{ project: any }>(`/api/project/${route.params.id}/detail`)
    project.value = res.project
    
    // PM/PL 이력 로드
    const mgRes = await $fetch<{ managers: any[] }>(`/api/project/${route.params.id}/manager-history`)
    managers.value = mgRes.managers || []
    
    // 참여자 현황 (주간보고 기준) - 별도 API 필요하면 추가
    // 임시로 빈 배열
    members.value = []
  } catch (e: any) {
    alert('프로젝트를 불러오는데 실패했습니다.')
    router.push('/project')
  } finally {
    isLoading.value = false
  }
}

async function loadEmployees() {
  try {
    const res = await $fetch<{ employees: any[] }>('/api/employee/list')
    employees.value = res.employees || []
  } catch (e) {
    console.error('Load employees error:', e)
  }
}

async function assignManager() {
  if (!assignForm.value.employeeId || !assignForm.value.startDate) {
    alert('담당자와 시작일은 필수입니다.')
    return
  }
  
  try {
    await $fetch(`/api/project/${route.params.id}/manager-assign`, {
      method: 'POST',
      body: assignForm.value
    })
    showAssignModal.value = false
    assignForm.value = {
      roleType: 'PM',
      employeeId: '',
      startDate: new Date().toISOString().split('T')[0],
      changeReason: ''
    }
    await loadProject()
  } catch (e: any) {
    alert(e.data?.message || e.message || '지정에 실패했습니다.')
  }
}

function getStatusBadgeClass(status: string) {
  const classes: Record<string, string> = {
    'ACTIVE': 'badge bg-success',
    'COMPLETED': 'badge bg-secondary',
    'HOLD': 'badge bg-warning'
  }
  return classes[status] || 'badge bg-secondary'
}

function getStatusText(status: string) {
  const texts: Record<string, string> = {
    'ACTIVE': '진행중',
    'COMPLETED': '완료',
    'HOLD': '보류'
  }
  return texts[status] || status
}

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 formatMoney(amount: number | null) {
  if (!amount) return '-'
  return new Intl.NumberFormat('ko-KR').format(amount) + '원'
}
</script>

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