<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">
          <i class="bi bi-tools me-2"></i>유지보수 업무 상세
        </h4>
        <div>
          <NuxtLink to="/maintenance" class="btn btn-outline-secondary me-2">
            <i class="bi bi-arrow-left me-1"></i>목록
          </NuxtLink>
          <button class="btn btn-danger" @click="deleteTask" v-if="!isEditing">
            <i class="bi bi-trash me-1"></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="task" class="row">
        <!-- 왼쪽: 기본 정보 -->
        <div class="col-md-8">
          <div class="card mb-3">
            <div class="card-header d-flex justify-content-between align-items-center">
              <strong>업무 정보</strong>
              <button 
                class="btn btn-sm" 
                :class="isEditing ? 'btn-secondary' : 'btn-outline-primary'"
                @click="toggleEdit"
              >
                <i :class="isEditing ? 'bi bi-x-lg' : 'bi bi-pencil'" class="me-1"></i>
                {{ isEditing ? '취소' : '수정' }}
              </button>
            </div>
            <div class="card-body">
              <!-- 보기 모드 -->
              <div v-if="!isEditing">
                <div class="row mb-3">
                  <div class="col-md-4">
                    <label class="text-muted small">프로젝트</label>
                    <p class="mb-0">{{ task.projectName || '-' }}</p>
                  </div>
                  <div class="col-md-4">
                    <label class="text-muted small">요청일</label>
                    <p class="mb-0">{{ formatDate(task.requestDate) }}</p>
                  </div>
                  <div class="col-md-4">
                    <label class="text-muted small">담당자</label>
                    <p class="mb-0">{{ task.assigneeName || '미배정' }}</p>
                  </div>
                </div>
                <div class="row mb-3">
                  <div class="col-md-8">
                    <label class="text-muted small">제목</label>
                    <p class="mb-0 fw-bold">{{ task.requestTitle }}</p>
                  </div>
                  <div class="col-md-2">
                    <label class="text-muted small">우선순위</label>
                    <p class="mb-0">
                      <span :class="getPriorityBadgeClass(task.priority)">{{ getPriorityText(task.priority) }}</span>
                    </p>
                  </div>
                  <div class="col-md-2">
                    <label class="text-muted small">상태</label>
                    <p class="mb-0">
                      <span :class="getStatusBadgeClass(task.status)">{{ getStatusText(task.status) }}</span>
                    </p>
                  </div>
                </div>
                <div class="row mb-3">
                  <div class="col-md-6">
                    <label class="text-muted small">요청자</label>
                    <p class="mb-0">{{ task.requesterName || '-' }} {{ task.requesterContact ? `(${task.requesterContact})` : '' }}</p>
                  </div>
                  <div class="col-md-6">
                    <label class="text-muted small">업무유형</label>
                    <p class="mb-0">{{ getTaskTypeText(task.taskType) }}</p>
                  </div>
                </div>
                <div class="mb-3" v-if="task.requestContent">
                  <label class="text-muted small">요청 내용</label>
                  <div class="border rounded p-3 bg-light" style="white-space: pre-wrap;">{{ task.requestContent }}</div>
                </div>
                <div class="mb-0" v-if="task.resolutionContent">
                  <label class="text-muted small">처리 내용</label>
                  <div class="border rounded p-3 bg-light" style="white-space: pre-wrap;">{{ task.resolutionContent }}</div>
                </div>
              </div>
              
              <!-- 수정 모드 -->
              <div v-else>
                <div class="row g-3">
                  <div class="col-md-4">
                    <label class="form-label">프로젝트</label>
                    <select class="form-select" v-model="form.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-4">
                    <label class="form-label">요청일</label>
                    <input type="date" class="form-control" v-model="form.requestDate" />
                  </div>
                  <div class="col-md-4">
                    <label class="form-label">담당자</label>
                    <select class="form-select" v-model="form.assigneeId">
                      <option value="">미배정</option>
                      <option v-for="e in employees" :key="e.employeeId" :value="e.employeeId">{{ e.employeeName }}</option>
                    </select>
                  </div>
                  <div class="col-md-6">
                    <label class="form-label">제목</label>
                    <input type="text" class="form-control" v-model="form.requestTitle" />
                  </div>
                  <div class="col-md-3">
                    <label class="form-label">우선순위</label>
                    <select class="form-select" v-model="form.priority">
                      <option value="HIGH">높음</option>
                      <option value="MEDIUM">보통</option>
                      <option value="LOW">낮음</option>
                    </select>
                  </div>
                  <div class="col-md-3">
                    <label class="form-label">상태</label>
                    <select class="form-select" v-model="form.status">
                      <option value="PENDING">미진행</option>
                      <option value="IN_PROGRESS">진행중</option>
                      <option value="COMPLETED">완료</option>
                    </select>
                  </div>
                  <div class="col-md-4">
                    <label class="form-label">요청자명</label>
                    <input type="text" class="form-control" v-model="form.requesterName" />
                  </div>
                  <div class="col-md-4">
                    <label class="form-label">요청자 연락처</label>
                    <input type="text" class="form-control" v-model="form.requesterContact" />
                  </div>
                  <div class="col-md-4">
                    <label class="form-label">업무유형</label>
                    <select class="form-select" v-model="form.taskType">
                      <option value="GENERAL">일반</option>
                      <option value="BUG">버그수정</option>
                      <option value="ENHANCEMENT">기능개선</option>
                      <option value="DATA">데이터</option>
                    </select>
                  </div>
                  <div class="col-12">
                    <label class="form-label">요청 내용</label>
                    <textarea class="form-control" v-model="form.requestContent" rows="4"></textarea>
                  </div>
                  <div class="col-12">
                    <label class="form-label">처리 내용</label>
                    <textarea class="form-control" v-model="form.resolutionContent" rows="4"></textarea>
                  </div>
                </div>
                <div class="mt-3 text-end">
                  <button class="btn btn-primary" @click="saveTask" :disabled="isSaving">
                    <span v-if="isSaving"><span class="spinner-border spinner-border-sm me-1"></span>저장 중...</span>
                    <span v-else><i class="bi bi-check-lg me-1"></i>저장</span>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 오른쪽: 반영 상태 + 메타 -->
        <div class="col-md-4">
          <!-- 상태 변경 -->
          <div class="card mb-3">
            <div class="card-header"><strong>상태 변경</strong></div>
            <div class="card-body">
              <div class="btn-group w-100" role="group">
                <button 
                  v-for="s in statusOptions" 
                  :key="s.value"
                  class="btn"
                  :class="task.status === s.value ? 'btn-primary' : 'btn-outline-secondary'"
                  @click="changeStatus(s.value)"
                  :disabled="isChangingStatus"
                >
                  {{ s.label }}
                </button>
              </div>
            </div>
          </div>

          <!-- 반영 체크 -->
          <div class="card mb-3">
            <div class="card-header"><strong>반영 현황</strong></div>
            <ul class="list-group list-group-flush">
              <li class="list-group-item d-flex justify-content-between align-items-center">
                <span><i class="bi bi-server me-2"></i>개발서버 반영</span>
                <div>
                  <input 
                    type="checkbox" 
                    class="form-check-input me-2" 
                    :checked="!!task.devCompletedAt"
                    @change="toggleDeploy('dev', $event)"
                  />
                  <small class="text-muted">{{ formatDate(task.devCompletedAt) || '-' }}</small>
                </div>
              </li>
              <li class="list-group-item d-flex justify-content-between align-items-center">
                <span><i class="bi bi-cloud me-2"></i>운영서버 반영</span>
                <div>
                  <input 
                    type="checkbox" 
                    class="form-check-input me-2" 
                    :checked="!!task.opsCompletedAt"
                    @change="toggleDeploy('ops', $event)"
                  />
                  <small class="text-muted">{{ formatDate(task.opsCompletedAt) || '-' }}</small>
                </div>
              </li>
              <li class="list-group-item d-flex justify-content-between align-items-center">
                <span><i class="bi bi-person-check me-2"></i>고객 확인</span>
                <div>
                  <input 
                    type="checkbox" 
                    class="form-check-input me-2" 
                    :checked="!!task.clientConfirmedAt"
                    @change="toggleDeploy('client', $event)"
                  />
                  <small class="text-muted">{{ formatDate(task.clientConfirmedAt) || '-' }}</small>
                </div>
              </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>{{ task.createdByName || '-' }}</span>
              </li>
              <li class="list-group-item d-flex justify-content-between">
                <span class="text-muted">등록일</span>
                <span>{{ formatDateTime(task.createdAt) }}</span>
              </li>
              <li class="list-group-item d-flex justify-content-between">
                <span class="text-muted">수정자</span>
                <span>{{ task.updatedByName || '-' }}</span>
              </li>
              <li class="list-group-item d-flex justify-content-between">
                <span class="text-muted">수정일</span>
                <span>{{ formatDateTime(task.updatedAt) }}</span>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

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

const taskId = computed(() => Number(route.params.id))

const task = ref<any>(null)
const projects = ref<any[]>([])
const employees = ref<any[]>([])
const isLoading = ref(true)
const isEditing = ref(false)
const isSaving = ref(false)
const isChangingStatus = ref(false)

const statusOptions = [
  { value: 'PENDING', label: '미진행' },
  { value: 'IN_PROGRESS', label: '진행중' },
  { value: 'COMPLETED', label: '완료' }
]

const form = ref({
  projectId: '',
  requestDate: '',
  requestTitle: '',
  requestContent: '',
  requesterName: '',
  requesterContact: '',
  taskType: 'GENERAL',
  priority: 'MEDIUM',
  status: 'PENDING',
  assigneeId: '',
  resolutionContent: '',
  devCompletedAt: '',
  opsCompletedAt: '',
  clientConfirmedAt: ''
})

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

async function loadTask() {
  isLoading.value = true
  try {
    const res = await $fetch<any>(`/api/maintenance/${taskId.value}/detail`)
    task.value = res.task
  } catch (e) {
    console.error('Load task error:', e)
    alert('업무 정보를 불러올 수 없습니다.')
    router.push('/maintenance')
  } finally {
    isLoading.value = false
  }
}

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

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

function toggleEdit() {
  if (!isEditing.value) {
    form.value = {
      projectId: task.value.projectId?.toString() || '',
      requestDate: task.value.requestDate?.split('T')[0] || '',
      requestTitle: task.value.requestTitle || '',
      requestContent: task.value.requestContent || '',
      requesterName: task.value.requesterName || '',
      requesterContact: task.value.requesterContact || '',
      taskType: task.value.taskType || 'GENERAL',
      priority: task.value.priority || 'MEDIUM',
      status: task.value.status || 'PENDING',
      assigneeId: task.value.assigneeId?.toString() || '',
      resolutionContent: task.value.resolutionContent || '',
      devCompletedAt: task.value.devCompletedAt?.split('T')[0] || '',
      opsCompletedAt: task.value.opsCompletedAt?.split('T')[0] || '',
      clientConfirmedAt: task.value.clientConfirmedAt?.split('T')[0] || ''
    }
  }
  isEditing.value = !isEditing.value
}

async function saveTask() {
  isSaving.value = true
  try {
    await $fetch(`/api/maintenance/${taskId.value}/update`, {
      method: 'PUT',
      body: {
        projectId: form.value.projectId ? Number(form.value.projectId) : null,
        requestDate: form.value.requestDate,
        requestTitle: form.value.requestTitle,
        requestContent: form.value.requestContent,
        requesterName: form.value.requesterName,
        requesterContact: form.value.requesterContact,
        taskType: form.value.taskType,
        priority: form.value.priority,
        status: form.value.status,
        assigneeId: form.value.assigneeId ? Number(form.value.assigneeId) : null,
        resolutionContent: form.value.resolutionContent,
        devCompletedAt: form.value.devCompletedAt || null,
        opsCompletedAt: form.value.opsCompletedAt || null,
        clientConfirmedAt: form.value.clientConfirmedAt || null
      }
    })
    isEditing.value = false
    await loadTask()
  } catch (e: any) {
    alert(e.data?.message || '저장에 실패했습니다.')
  } finally {
    isSaving.value = false
  }
}

async function changeStatus(status: string) {
  if (task.value.status === status) return
  isChangingStatus.value = true
  try {
    await $fetch(`/api/maintenance/${taskId.value}/status`, {
      method: 'PUT',
      body: { status }
    })
    task.value.status = status
  } catch (e: any) {
    alert(e.data?.message || '상태 변경에 실패했습니다.')
  } finally {
    isChangingStatus.value = false
  }
}

async function toggleDeploy(type: string, event: Event) {
  const checked = (event.target as HTMLInputElement).checked
  const now = new Date().toISOString()
  
  const fieldMap: Record<string, string> = {
    'dev': 'devCompletedAt',
    'ops': 'opsCompletedAt',
    'client': 'clientConfirmedAt'
  }
  
  try {
    await $fetch(`/api/maintenance/${taskId.value}/update`, {
      method: 'PUT',
      body: {
        ...task.value,
        projectId: task.value.projectId,
        [fieldMap[type]]: checked ? now : null
      }
    })
    task.value[fieldMap[type]] = checked ? now : null
  } catch (e: any) {
    alert(e.data?.message || '반영 상태 변경에 실패했습니다.')
    ;(event.target as HTMLInputElement).checked = !checked
  }
}

async function deleteTask() {
  if (!confirm('정말 삭제하시겠습니까?')) return
  try {
    await $fetch(`/api/maintenance/${taskId.value}/delete`, { method: 'DELETE' })
    router.push('/maintenance')
  } catch (e: any) {
    alert(e.data?.message || '삭제에 실패했습니다.')
  }
}

function getPriorityBadgeClass(p: string) {
  return { 'HIGH': 'badge bg-danger', 'MEDIUM': 'badge bg-warning text-dark', 'LOW': 'badge bg-secondary' }[p] || 'badge bg-secondary'
}
function getPriorityText(p: string) {
  return { 'HIGH': '높음', 'MEDIUM': '보통', 'LOW': '낮음' }[p] || p
}
function getStatusBadgeClass(s: string) {
  return { 'PENDING': 'badge bg-secondary', 'IN_PROGRESS': 'badge bg-primary', 'COMPLETED': 'badge bg-success' }[s] || 'badge bg-secondary'
}
function getStatusText(s: string) {
  return { 'PENDING': '미진행', 'IN_PROGRESS': '진행중', 'COMPLETED': '완료' }[s] || s
}
function getTaskTypeText(t: string) {
  return { 'GENERAL': '일반', 'BUG': '버그수정', 'ENHANCEMENT': '기능개선', 'DATA': '데이터' }[t] || t
}
function formatDate(d: string | null) {
  if (!d) return ''
  return new Date(d).toISOString().split('T')[0]
}
function formatDateTime(d: string | null) {
  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')}`
}
</script>
