<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="/maintenance" class="text-decoration-none text-muted me-2"><i class="bi bi-arrow-left"></i></NuxtLink>
          <i class="bi bi-upload me-2"></i>유지보수 업무 일괄 등록
        </h4>
      </div>

      <!-- Step 1: 파일 업로드 -->
      <div class="card mb-4" v-if="step === 1">
        <div class="card-header"><strong>Step 1. 파일 업로드</strong></div>
        <div class="card-body">
          <div class="row g-3">
            <div class="col-md-6">
              <label class="form-label">프로젝트 <span class="text-danger">*</span></label>
              <select class="form-select" v-model="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-6">
              <label class="form-label">엑셀/CSV 파일 <span class="text-danger">*</span></label>
              <input type="file" class="form-control" @change="onFileChange" accept=".xlsx,.xls,.csv" ref="fileInput" />
            </div>
          </div>
          <div class="alert alert-info mt-3">
            <i class="bi bi-info-circle me-2"></i>
            엑셀 파일의 첫 번째 행은 헤더여야 합니다. AI가 자동으로 컬럼을 매핑합니다.
          </div>
          <div class="mt-3">
            <button class="btn btn-primary" @click="uploadFile" :disabled="!projectId || !selectedFile || isUploading">
              <span v-if="isUploading"><span class="spinner-border spinner-border-sm me-1"></span>분석 중...</span>
              <span v-else><i class="bi bi-cloud-upload me-1"></i>업로드 및 분석</span>
            </button>
          </div>
        </div>
      </div>

      <!-- Step 2: 파싱 결과 검토 -->
      <div class="card mb-4" v-if="step === 2">
        <div class="card-header d-flex justify-content-between align-items-center">
          <strong>Step 2. 파싱 결과 검토</strong>
          <span class="text-muted">{{ uploadResult?.filename }} - {{ uploadResult?.totalRows }}건</span>
        </div>
        <div class="card-body p-0">
          <div class="table-responsive">
            <table class="table table-sm table-bordered mb-0">
              <thead class="table-light">
                <tr>
                  <th style="width: 40px" class="text-center">
                    <input type="checkbox" v-model="selectAll" @change="toggleSelectAll" />
                  </th>
                  <th style="width: 40px" class="text-center">행</th>
                  <th style="width: 100px">요청일</th>
                  <th>요청 제목</th>
                  <th style="width: 80px">유형</th>
                  <th style="width: 80px">우선순위</th>
                  <th style="width: 80px">요청자</th>
                  <th style="width: 80px" class="text-center">상태</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(task, idx) in parsedTasks" :key="idx" :class="{ 'table-warning': task.isDuplicate }">
                  <td class="text-center">
                    <input type="checkbox" v-model="task.selected" :disabled="task.isDuplicate" />
                  </td>
                  <td class="text-center">{{ task.rowIndex }}</td>
                  <td>
                    <input type="date" class="form-control form-control-sm" v-model="task.requestDate" />
                  </td>
                  <td>
                    <input type="text" class="form-control form-control-sm" v-model="task.requestTitle" />
                  </td>
                  <td>
                    <select class="form-select form-select-sm" v-model="task.taskType">
                      <option value="bug">버그</option>
                      <option value="feature">기능</option>
                      <option value="inquiry">문의</option>
                      <option value="other">기타</option>
                    </select>
                  </td>
                  <td>
                    <select class="form-select form-select-sm" v-model="task.priority">
                      <option value="high">높음</option>
                      <option value="medium">중간</option>
                      <option value="low">낮음</option>
                    </select>
                  </td>
                  <td>{{ task.requesterName || '-' }}</td>
                  <td class="text-center">
                    <span v-if="task.isDuplicate" class="badge bg-danger">중복</span>
                    <span v-else class="badge bg-success">신규</span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        <div class="card-footer d-flex justify-content-between">
          <button class="btn btn-secondary" @click="step = 1">
            <i class="bi bi-arrow-left me-1"></i>이전
          </button>
          <div>
            <span class="me-3">선택: {{ selectedCount }}건 / 중복: {{ duplicateCount }}건</span>
            <button class="btn btn-primary" @click="bulkCreate" :disabled="selectedCount === 0 || isCreating">
              <span v-if="isCreating"><span class="spinner-border spinner-border-sm me-1"></span>등록 중...</span>
              <span v-else><i class="bi bi-check-lg me-1"></i>{{ selectedCount }}건 등록</span>
            </button>
          </div>
        </div>
      </div>

      <!-- Step 3: 완료 -->
      <div class="card" v-if="step === 3">
        <div class="card-body text-center py-5">
          <i class="bi bi-check-circle text-success display-1"></i>
          <h4 class="mt-3">등록 완료!</h4>
          <p class="text-muted">{{ createResult?.insertedCount }}건이 등록되었습니다.</p>
          <div class="mt-4">
            <NuxtLink to="/maintenance" class="btn btn-primary me-2">
              <i class="bi bi-list me-1"></i>목록으로
            </NuxtLink>
            <button class="btn btn-outline-secondary" @click="resetAll">
              <i class="bi bi-plus-lg me-1"></i>추가 등록
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

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

interface Project { projectId: number; projectName: string }
interface ParsedTask {
  rowIndex: number
  requestDate: string | null
  requestTitle: string
  requestContent: string | null
  requesterName: string | null
  requesterContact: string | null
  taskType: string
  priority: string
  resolutionContent: string | null
  isDuplicate: boolean
  selected: boolean
}

const projects = ref<Project[]>([])
const projectId = ref('')
const selectedFile = ref<File | null>(null)
const fileInput = ref<HTMLInputElement | null>(null)

const step = ref(1)
const isUploading = ref(false)
const isCreating = ref(false)

const uploadResult = ref<any>(null)
const parsedTasks = ref<ParsedTask[]>([])
const createResult = ref<any>(null)
const selectAll = ref(true)

const selectedCount = computed(() => parsedTasks.value.filter(t => t.selected && !t.isDuplicate).length)
const duplicateCount = computed(() => parsedTasks.value.filter(t => t.isDuplicate).length)

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

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

function onFileChange(e: Event) {
  const target = e.target as HTMLInputElement
  selectedFile.value = target.files?.[0] || null
}

async function uploadFile() {
  if (!projectId.value || !selectedFile.value) return
  
  isUploading.value = true
  try {
    const formData = new FormData()
    formData.append('file', selectedFile.value)
    formData.append('projectId', projectId.value)
    
    const res = await $fetch<any>('/api/maintenance/upload', {
      method: 'POST',
      body: formData
    })
    
    uploadResult.value = res
    parsedTasks.value = res.tasks.map((t: any) => ({ ...t, selected: !t.isDuplicate }))
    step.value = 2
  } catch (e: any) {
    alert(e.data?.message || '파일 분석에 실패했습니다.')
  } finally {
    isUploading.value = false
  }
}

function toggleSelectAll() {
  parsedTasks.value.forEach(t => {
    if (!t.isDuplicate) t.selected = selectAll.value
  })
}

async function bulkCreate() {
  if (selectedCount.value === 0) return
  
  isCreating.value = true
  try {
    const res = await $fetch<any>('/api/maintenance/bulk-create', {
      method: 'POST',
      body: {
        projectId: Number(projectId.value),
        batchId: uploadResult.value.batchId,
        tasks: parsedTasks.value.filter(t => t.selected && !t.isDuplicate)
      }
    })
    createResult.value = res
    step.value = 3
  } catch (e: any) {
    alert(e.data?.message || '등록에 실패했습니다.')
  } finally {
    isCreating.value = false
  }
}

function resetAll() {
  step.value = 1
  selectedFile.value = null
  uploadResult.value = null
  parsedTasks.value = []
  createResult.value = null
  if (fileInput.value) fileInput.value.value = ''
}
</script>
