<template>
  <div>
    <AppHeader />
    
    <div class="container-fluid py-4">
      <div class="d-flex justify-content-between align-items-center mb-4">
        <h4 class="mb-0">
          <NuxtLink to="/project" class="text-decoration-none text-muted me-2"><i class="bi bi-arrow-left"></i></NuxtLink>
          <i class="bi bi-folder me-2"></i>{{ project?.projectName || '프로젝트 상세' }}
        </h4>
        <div v-if="project">
          <button class="btn btn-outline-primary me-2" @click="toggleEdit" v-if="!isEditing">
            <i class="bi bi-pencil me-1"></i>수정
          </button>
          <button class="btn btn-secondary me-2" @click="toggleEdit" v-else>취소</button>
          <button class="btn btn-primary" @click="saveProject" v-if="isEditing" :disabled="isSaving">
            <span v-if="isSaving"><span class="spinner-border spinner-border-sm me-1"></span></span>
            <i class="bi bi-check-lg me-1" v-else></i>저장
          </button>
        </div>
      </div>

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

      <div v-else-if="project" class="row">
        <div class="col-md-8">
          <!-- 프로젝트 기본 정보 -->
          <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
              <strong>프로젝트 정보</strong>
              <span :class="getStatusBadgeClass(project.projectStatus)">{{ getStatusText(project.projectStatus) }}</span>
            </div>
            <div class="card-body">
              <!-- 보기 모드 -->
              <div v-if="!isEditing">
                <div class="row g-3">
                  <div class="col-md-4">
                    <label class="text-muted small">프로젝트 코드</label>
                    <p class="mb-0"><code>{{ project.projectCode || '-' }}</code></p>
                  </div>
                  <div class="col-md-4">
                    <label class="text-muted small">유형</label>
                    <p class="mb-0"><span :class="getTypeBadgeClass(project.projectType)">{{ project.projectType || 'SI' }}</span></p>
                  </div>
                  <div class="col-md-4">
                    <label class="text-muted small">상태</label>
                    <p class="mb-0"><span :class="getStatusBadgeClass(project.projectStatus)">{{ getStatusText(project.projectStatus) }}</span></p>
                  </div>
                  <div class="col-md-6">
                    <label class="text-muted small">소속 사업</label>
                    <p class="mb-0">
                      <NuxtLink v-if="project.businessId" :to="`/business/${project.businessId}`" class="text-decoration-none">
                        {{ project.businessName }}
                      </NuxtLink>
                      <span v-else>-</span>
                    </p>
                  </div>
                  <div class="col-md-6">
                    <label class="text-muted small">발주처</label>
                    <p class="mb-0">{{ project.clientName || '-' }}</p>
                  </div>
                  <div class="col-md-6">
                    <label class="text-muted small">기간</label>
                    <p class="mb-0">{{ project.startDate ? formatDate(project.startDate) : '-' }} ~ {{ project.endDate ? formatDate(project.endDate) : '진행중' }}</p>
                  </div>
                  <div class="col-md-6">
                    <label class="text-muted small">계약금액</label>
                    <p class="mb-0">{{ formatMoney(project.contractAmount) }}</p>
                  </div>
                  <div class="col-12" v-if="project.projectDescription">
                    <label class="text-muted small">설명</label>
                    <p class="mb-0" style="white-space: pre-wrap;">{{ project.projectDescription }}</p>
                  </div>
                </div>
              </div>
              <!-- 수정 모드 -->
              <div v-else>
                <div class="row g-3">
                  <div class="col-md-8">
                    <label class="form-label">프로젝트명</label>
                    <input type="text" class="form-control" v-model="form.projectName" />
                  </div>
                  <div class="col-md-4">
                    <label class="form-label">유형</label>
                    <select class="form-select" v-model="form.projectType">
                      <option value="SI">SI</option>
                      <option value="SM">SM</option>
                    </select>
                  </div>
                  <div class="col-md-6">
                    <label class="form-label">소속 사업</label>
                    <select class="form-select" v-model="form.businessId">
                      <option value="">선택 안함</option>
                      <option v-for="b in businesses" :key="b.businessId" :value="b.businessId">{{ b.businessName }}</option>
                    </select>
                  </div>
                  <div class="col-md-6">
                    <label class="form-label">발주처</label>
                    <input type="text" class="form-control" v-model="form.clientName" />
                  </div>
                  <div class="col-md-4">
                    <label class="form-label">시작일</label>
                    <input type="date" class="form-control" v-model="form.startDate" />
                  </div>
                  <div class="col-md-4">
                    <label class="form-label">종료일</label>
                    <input type="date" class="form-control" v-model="form.endDate" />
                  </div>
                  <div class="col-md-4">
                    <label class="form-label">상태</label>
                    <select class="form-select" v-model="form.projectStatus">
                      <option value="ACTIVE">진행중</option>
                      <option value="COMPLETED">완료</option>
                      <option value="HOLD">보류</option>
                    </select>
                  </div>
                  <div class="col-md-6">
                    <label class="form-label">계약금액</label>
                    <input type="number" class="form-control" v-model="form.contractAmount" />
                  </div>
                  <div class="col-12">
                    <label class="form-label">설명</label>
                    <textarea class="form-control" v-model="form.projectDescription" rows="3"></textarea>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- PM/PL 이력 -->
          <div class="card">
            <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 table-bordered 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>

        <div class="col-md-4">
          <!-- 현재 담당자 -->
          <div class="card mb-4">
            <div class="card-header"><strong>현재 담당자</strong></div>
            <ul class="list-group list-group-flush">
              <li class="list-group-item d-flex justify-content-between">
                <span>PM</span>
                <strong>{{ project.currentPm?.employeeName || '-' }}</strong>
              </li>
              <li class="list-group-item d-flex justify-content-between">
                <span>PL</span>
                <strong>{{ project.currentPl?.employeeName || '-' }}</strong>
              </li>
            </ul>
          </div>

          <!-- 등록 정보 -->
          <div class="card">
            <div class="card-header"><strong>등록 정보</strong></div>
            <ul class="list-group list-group-flush">
              <li class="list-group-item d-flex justify-content-between">
                <span class="text-muted">등록일</span>
                <span>{{ formatDateTime(project.createdAt) }}</span>
              </li>
              <li class="list-group-item d-flex justify-content-between">
                <span class="text-muted">수정일</span>
                <span>{{ formatDateTime(project.updatedAt) }}</span>
              </li>
            </ul>
          </div>
        </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 }}</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()

interface Business { businessId: number; businessName: string }

const project = ref<any>(null)
const businesses = ref<Business[]>([])
const managers = ref<any[]>([])
const employees = ref<any[]>([])
const isLoading = ref(true)
const isEditing = ref(false)
const isSaving = ref(false)
const showAssignModal = ref(false)

const form = ref({
  projectName: '',
  projectType: 'SI',
  businessId: '',
  clientName: '',
  startDate: '',
  endDate: '',
  contractAmount: null as number | null,
  projectStatus: 'ACTIVE',
  projectDescription: ''
})

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(), loadBusinesses(), loadEmployees()])
})

async function loadProject() {
  isLoading.value = true
  try {
    const res = await $fetch<{ project: any }>(`/api/project/${route.params.id}/detail`)
    project.value = res.project
    const mgRes = await $fetch<{ managers: any[] }>(`/api/project/${route.params.id}/manager-history`)
    managers.value = mgRes.managers || []
  } catch (e: any) {
    alert('프로젝트를 불러오는데 실패했습니다.')
    router.push('/project')
  } finally {
    isLoading.value = false
  }
}

async function loadBusinesses() {
  try {
    const res = await $fetch<{ businesses: Business[] }>('/api/business/list')
    businesses.value = res.businesses || []
  } catch (e) { console.error(e) }
}

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

function toggleEdit() {
  if (!isEditing.value) {
    form.value = {
      projectName: project.value.projectName || '',
      projectType: project.value.projectType || 'SI',
      businessId: project.value.businessId?.toString() || '',
      clientName: project.value.clientName || '',
      startDate: project.value.startDate?.split('T')[0] || '',
      endDate: project.value.endDate?.split('T')[0] || '',
      contractAmount: project.value.contractAmount,
      projectStatus: project.value.projectStatus || 'ACTIVE',
      projectDescription: project.value.projectDescription || ''
    }
  }
  isEditing.value = !isEditing.value
}

async function saveProject() {
  isSaving.value = true
  try {
    await $fetch(`/api/project/${route.params.id}/update`, {
      method: 'PUT',
      body: {
        ...form.value,
        businessId: form.value.businessId ? Number(form.value.businessId) : null
      }
    })
    isEditing.value = false
    await loadProject()
  } catch (e: any) {
    alert(e.data?.message || '저장에 실패했습니다.')
  } finally {
    isSaving.value = false
  }
}

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 || '지정에 실패했습니다.')
  }
}

function getTypeBadgeClass(type: string) { return type === 'SM' ? 'badge bg-info' : 'badge bg-primary' }
function getStatusBadgeClass(status: string) {
  return { 'ACTIVE': 'badge bg-success', 'COMPLETED': 'badge bg-secondary', 'HOLD': 'badge bg-warning' }[status] || 'badge bg-secondary'
}
function getStatusText(status: string) {
  return { 'ACTIVE': '진행중', 'COMPLETED': '완료', 'HOLD': '보류' }[status] || status
}
function formatDate(d: string) {
  if (!d) return ''
  return new Date(d).toISOString().split('T')[0]
}
function formatDateTime(d: string) {
  if (!d) return '-'
  const dt = new Date(d)
  return `${dt.getFullYear()}-${String(dt.getMonth()+1).padStart(2,'0')}-${String(dt.getDate()).padStart(2,'0')} ${String(dt.getHours()).padStart(2,'0')}:${String(dt.getMinutes()).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>
