<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/upload" class="btn btn-outline-primary me-2">
            <i class="bi bi-upload me-1"></i>일괄 등록
          </NuxtLink>
          <NuxtLink to="/maintenance/write" class="btn btn-primary">
            <i class="bi bi-plus-lg me-1"></i>업무 등록
          </NuxtLink>
        </div>
      </div>

      <!-- 검색 -->
      <div class="card mb-3">
        <div class="card-body py-2">
          <div class="row g-2 align-items-center">
            <div class="col-1 text-end"><label class="col-form-label">프로젝트</label></div>
            <div class="col-2">
              <select class="form-select form-select-sm" v-model="filter.projectId">
                <option value="">전체</option>
                <option v-for="p in projects" :key="p.projectId" :value="p.projectId">
                  {{ p.projectName }}
                </option>
              </select>
            </div>
            <div class="col-1 text-end"><label class="col-form-label">제목</label></div>
            <div class="col-2">
              <input 
                type="text" 
                class="form-control form-control-sm" 
                v-model="filter.keyword"
                placeholder="제목, 내용, 요청자"
                @keyup.enter="loadTasks"
              />
            </div>
            <div class="col-1 text-end"><label class="col-form-label">상태</label></div>
            <div class="col-3">
              <div class="btn-group" role="group">
                <input type="radio" class="btn-check" name="status" id="statusAll" value="" v-model="filter.status" @change="loadTasks">
                <label class="btn btn-outline-secondary btn-sm" for="statusAll">전체</label>
                <input type="radio" class="btn-check" name="status" id="statusPending" value="PENDING" v-model="filter.status" @change="loadTasks">
                <label class="btn btn-outline-secondary btn-sm" for="statusPending">미진행</label>
                <input type="radio" class="btn-check" name="status" id="statusProgress" value="IN_PROGRESS" v-model="filter.status" @change="loadTasks">
                <label class="btn btn-outline-secondary btn-sm" for="statusProgress">진행중</label>
                <input type="radio" class="btn-check" name="status" id="statusCompleted" value="COMPLETED" v-model="filter.status" @change="loadTasks">
                <label class="btn btn-outline-secondary btn-sm" for="statusCompleted">완료</label>
              </div>
            </div>
          </div>
          <div class="row g-2 align-items-center mt-1">
            <div class="col-1 text-end"><label class="col-form-label">우선순위</label></div>
            <div class="col-2">
              <select class="form-select form-select-sm" v-model="filter.priority">
                <option value="">전체</option>
                <option value="HIGH">높음</option>
                <option value="MEDIUM">보통</option>
                <option value="LOW">낮음</option>
              </select>
            </div>
            <div class="col-1 text-end"><label class="col-form-label">요청일</label></div>
            <div class="col-2">
              <input type="date" class="form-control form-control-sm" v-model="filter.startDate" />
            </div>
            <div class="col-auto px-1">~</div>
            <div class="col-2">
              <input type="date" class="form-control form-control-sm" v-model="filter.endDate" />
            </div>
            <div class="col-2">
              <button class="btn btn-primary btn-sm me-1" @click="loadTasks">
                <i class="bi bi-search me-1"></i>조회
              </button>
              <button class="btn btn-outline-secondary btn-sm" @click="resetSearch">
                <i class="bi bi-arrow-counterclockwise"></i>
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 목록 -->
      <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
          <span>유지보수 업무 목록 총 <strong>{{ pagination.total }}</strong>건</span>
        </div>
        <div class="card-body p-0">
          <div class="table-responsive">
            <table class="table table-hover table-bordered mb-0">
              <thead class="table-light">
                <tr>
                  <th style="width: 50px" class="text-center">No</th>
                  <th style="width: 100px">요청일</th>
                  <th>제목</th>
                  <th style="width: 120px">프로젝트</th>
                  <th style="width: 80px">요청자</th>
                  <th style="width: 70px" class="text-center">우선순위</th>
                  <th style="width: 80px" class="text-center">상태</th>
                  <th style="width: 80px">담당자</th>
                  <th style="width: 50px" class="text-center" title="개발서버">개발</th>
                  <th style="width: 50px" class="text-center" title="운영서버">운영</th>
                  <th style="width: 50px" class="text-center" title="고객확인">확인</th>
                </tr>
              </thead>
              <tbody>
                <tr v-if="isLoading">
                  <td colspan="11" class="text-center py-4">
                    <span class="spinner-border spinner-border-sm me-2"></span>로딩 중...
                  </td>
                </tr>
                <tr v-else-if="tasks.length === 0">
                  <td colspan="11" class="text-center py-5 text-muted">
                    <i class="bi bi-inbox display-4"></i>
                    <p class="mt-2 mb-0">조회된 업무가 없습니다.</p>
                  </td>
                </tr>
                <tr v-else v-for="(task, idx) in tasks" :key="task.taskId">
                  <td class="text-center">{{ (pagination.page - 1) * pagination.pageSize + idx + 1 }}</td>
                  <td>{{ formatDate(task.requestDate) }}</td>
                  <td>
                    <NuxtLink :to="`/maintenance/${task.taskId}`" class="text-decoration-none">
                      {{ task.requestTitle }}
                    </NuxtLink>
                  </td>
                  <td>{{ task.projectName || '-' }}</td>
                  <td>{{ task.requesterName || '-' }}</td>
                  <td class="text-center">
                    <span :class="getPriorityBadgeClass(task.priority)">
                      {{ getPriorityText(task.priority) }}
                    </span>
                  </td>
                  <td class="text-center">
                    <span :class="getStatusBadgeClass(task.status)">
                      {{ getStatusText(task.status) }}
                    </span>
                  </td>
                  <td>{{ task.assigneeName || '-' }}</td>
                  <td class="text-center">
                    <i v-if="task.devCompletedAt" class="bi bi-check-circle-fill text-success"></i>
                    <i v-else class="bi bi-circle text-muted"></i>
                  </td>
                  <td class="text-center">
                    <i v-if="task.opsCompletedAt" class="bi bi-check-circle-fill text-success"></i>
                    <i v-else class="bi bi-circle text-muted"></i>
                  </td>
                  <td class="text-center">
                    <i v-if="task.clientConfirmedAt" class="bi bi-check-circle-fill text-success"></i>
                    <i v-else class="bi bi-circle text-muted"></i>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          
          <!-- 페이지네이션 -->
          <div class="card-footer d-flex justify-content-between align-items-center" v-if="pagination.totalPages > 1">
            <small class="text-muted">
              전체 {{ pagination.total }}건 중 {{ (pagination.page - 1) * pagination.pageSize + 1 }} - 
              {{ Math.min(pagination.page * pagination.pageSize, pagination.total) }}건
            </small>
            <nav>
              <ul class="pagination pagination-sm mb-0">
                <li class="page-item" :class="{ disabled: pagination.page === 1 }">
                  <a class="page-link" href="#" @click.prevent="goPage(pagination.page - 1)">이전</a>
                </li>
                <li 
                  class="page-item" 
                  v-for="p in visiblePages" 
                  :key="p" 
                  :class="{ active: p === pagination.page }"
                >
                  <a class="page-link" href="#" @click.prevent="goPage(p)">{{ p }}</a>
                </li>
                <li class="page-item" :class="{ disabled: pagination.page === pagination.totalPages }">
                  <a class="page-link" href="#" @click.prevent="goPage(pagination.page + 1)">다음</a>
                </li>
              </ul>
            </nav>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

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

interface Task {
  taskId: number
  projectId: number | null
  projectName: string | null
  requestDate: string
  requestTitle: string
  requesterName: string | null
  priority: string
  status: string
  assigneeId: number | null
  assigneeName: string | null
  devCompletedAt: string | null
  opsCompletedAt: string | null
  clientConfirmedAt: string | null
}

interface Project {
  projectId: number
  projectName: string
}

const tasks = ref<Task[]>([])
const projects = ref<Project[]>([])
const isLoading = ref(false)

const filter = ref({
  projectId: '',
  keyword: '',
  status: '',
  priority: '',
  startDate: '',
  endDate: ''
})

const pagination = ref({
  page: 1,
  pageSize: 20,
  total: 0,
  totalPages: 0
})

const visiblePages = computed(() => {
  const pages: number[] = []
  const total = pagination.value.totalPages
  const current = pagination.value.page
  let start = Math.max(1, current - 2)
  let end = Math.min(total, current + 2)
  if (end - start < 4) {
    if (start === 1) end = Math.min(total, 5)
    else start = Math.max(1, total - 4)
  }
  for (let i = start; i <= end; i++) pages.push(i)
  return pages
})

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

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

async function loadTasks() {
  isLoading.value = true
  try {
    const res = await $fetch<any>('/api/maintenance/list', {
      query: {
        projectId: filter.value.projectId || undefined,
        keyword: filter.value.keyword || undefined,
        status: filter.value.status || undefined,
        priority: filter.value.priority || undefined,
        startDate: filter.value.startDate || undefined,
        endDate: filter.value.endDate || undefined,
        page: pagination.value.page,
        pageSize: pagination.value.pageSize
      }
    })
    tasks.value = res.tasks || []
    pagination.value.total = res.pagination?.total || 0
    pagination.value.totalPages = res.pagination?.totalPages || 0
  } catch (e) {
    console.error('Load tasks error:', e)
  } finally {
    isLoading.value = false
  }
}

function resetSearch() {
  filter.value = {
    projectId: '',
    keyword: '',
    status: '',
    priority: '',
    startDate: '',
    endDate: ''
  }
  pagination.value.page = 1
  loadTasks()
}

function goPage(page: number) {
  if (page < 1 || page > pagination.value.totalPages) return
  pagination.value.page = page
  loadTasks()
}

function getPriorityBadgeClass(priority: string) {
  const classes: Record<string, string> = {
    'HIGH': 'badge bg-danger',
    'MEDIUM': 'badge bg-warning text-dark',
    'LOW': 'badge bg-secondary'
  }
  return classes[priority] || 'badge bg-secondary'
}

function getPriorityText(priority: string) {
  const texts: Record<string, string> = { 'HIGH': '높음', 'MEDIUM': '보통', 'LOW': '낮음' }
  return texts[priority] || priority
}

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

function getStatusText(status: string) {
  const texts: Record<string, string> = { 'PENDING': '미진행', 'IN_PROGRESS': '진행중', 'COMPLETED': '완료' }
  return texts[status] || status
}

function formatDate(dateStr: string | null) {
  if (!dateStr) return ''
  const d = new Date(dateStr)
  return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`
}
</script>
