<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-briefcase me-2"></i>사업 관리
        </h4>
        <button class="btn btn-primary" @click="openCreateModal">
          <i class="bi bi-plus-lg me-1"></i>새 사업
        </button>
      </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">
              <input type="text" class="form-control form-control-sm" v-model="filter.businessName" @keyup.enter="loadBusinesses" />
            </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.clientName" @keyup.enter="loadBusinesses" />
            </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="loadBusinesses">
                <label class="btn btn-outline-secondary btn-sm" for="statusAll">전체</label>
                <input type="radio" class="btn-check" name="status" id="statusActive" value="active" v-model="filter.status" @change="loadBusinesses">
                <label class="btn btn-outline-secondary btn-sm" for="statusActive">진행중</label>
                <input type="radio" class="btn-check" name="status" id="statusCompleted" value="completed" v-model="filter.status" @change="loadBusinesses">
                <label class="btn btn-outline-secondary btn-sm" for="statusCompleted">완료</label>
                <input type="radio" class="btn-check" name="status" id="statusSuspended" value="suspended" v-model="filter.status" @change="loadBusinesses">
                <label class="btn btn-outline-secondary btn-sm" for="statusSuspended">중단</label>
              </div>
            </div>
            <div class="col-2">
              <button class="btn btn-primary btn-sm me-1" @click="loadBusinesses">
                <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>{{ businesses.length }}</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: 120px">사업코드</th>
                  <th>사업명</th>
                  <th style="width: 150px">발주처</th>
                  <th style="width: 200px">계약기간</th>
                  <th style="width: 80px" class="text-center">프로젝트</th>
                  <th style="width: 80px" class="text-center">상태</th>
                </tr>
              </thead>
              <tbody>
                <tr v-if="isLoading">
                  <td colspan="7" class="text-center py-4">
                    <span class="spinner-border spinner-border-sm me-2"></span>로딩 중...
                  </td>
                </tr>
                <tr v-else-if="businesses.length === 0">
                  <td colspan="7" 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="(biz, idx) in businesses" :key="biz.businessId">
                  <td class="text-center">{{ idx + 1 }}</td>
                  <td><code>{{ biz.businessCode || '-' }}</code></td>
                  <td>
                    <NuxtLink :to="`/business/${biz.businessId}`" class="text-decoration-none">
                      {{ biz.businessName }}
                    </NuxtLink>
                  </td>
                  <td>{{ biz.clientName || '-' }}</td>
                  <td>
                    <span v-if="biz.contractStartDate">
                      {{ formatDate(biz.contractStartDate) }} ~ {{ formatDate(biz.contractEndDate) || '진행중' }}
                    </span>
                    <span v-else>-</span>
                  </td>
                  <td class="text-center">
                    <span class="badge bg-light text-dark">{{ biz.projectCount }}개</span>
                  </td>
                  <td class="text-center">
                    <span :class="getStatusBadgeClass(biz.businessStatus)">
                      {{ getStatusText(biz.businessStatus) }}
                    </span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <!-- 사업 등록/수정 모달 -->
    <div class="modal fade" :class="{ show: showModal }" :style="{ display: showModal ? 'block' : 'none' }">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">{{ isEdit ? '사업 수정' : '새 사업 등록' }}</h5>
            <button type="button" class="btn-close" @click="showModal = false"></button>
          </div>
          <div class="modal-body">
            <div class="row g-3">
              <div class="col-md-8">
                <label class="form-label">사업명 <span class="text-danger">*</span></label>
                <input type="text" class="form-control" v-model="form.businessName" />
              </div>
              <div class="col-md-4">
                <label class="form-label">사업코드</label>
                <input type="text" class="form-control" v-model="form.businessCode" placeholder="BIZ-2026-001" />
              </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-6" v-if="isEdit">
                <label class="form-label">상태</label>
                <select class="form-select" v-model="form.businessStatus">
                  <option value="active">진행중</option>
                  <option value="completed">완료</option>
                  <option value="suspended">중단</option>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label">계약 시작일</label>
                <input type="date" class="form-control" v-model="form.contractStartDate" />
              </div>
              <div class="col-md-6">
                <label class="form-label">계약 종료일</label>
                <input type="date" class="form-control" v-model="form.contractEndDate" />
              </div>
              <div class="col-12">
                <label class="form-label">설명</label>
                <textarea class="form-control" v-model="form.description" rows="3"></textarea>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" @click="showModal = false">취소</button>
            <button type="button" class="btn btn-primary" @click="saveBusiness" :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 class="modal-backdrop fade show" v-if="showModal"></div>
  </div>
</template>

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

interface Business {
  businessId: number
  businessName: string
  businessCode: string | null
  clientName: string | null
  contractStartDate: string | null
  contractEndDate: string | null
  businessStatus: string
  projectCount: number
}

const businesses = ref<Business[]>([])
const isLoading = ref(false)
const showModal = ref(false)
const isEdit = ref(false)
const isSaving = ref(false)
const editId = ref<number | null>(null)

const filter = ref({
  businessName: '',
  clientName: '',
  status: ''
})

const form = ref({
  businessName: '',
  businessCode: '',
  clientName: '',
  contractStartDate: '',
  contractEndDate: '',
  businessStatus: 'active',
  description: ''
})

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

async function loadBusinesses() {
  isLoading.value = true
  try {
    const res = await $fetch<{ businesses: Business[] }>('/api/business/list', {
      query: {
        businessName: filter.value.businessName || undefined,
        clientName: filter.value.clientName || undefined,
        status: filter.value.status || undefined
      }
    })
    businesses.value = res.businesses || []
  } catch (e) {
    console.error('Load businesses error:', e)
  } finally {
    isLoading.value = false
  }
}

function resetSearch() {
  filter.value = {
    businessName: '',
    clientName: '',
    status: ''
  }
  loadBusinesses()
}

function openCreateModal() {
  isEdit.value = false
  editId.value = null
  form.value = {
    businessName: '',
    businessCode: '',
    clientName: '',
    contractStartDate: '',
    contractEndDate: '',
    businessStatus: 'active',
    description: ''
  }
  showModal.value = true
}

async function saveBusiness() {
  if (!form.value.businessName) {
    alert('사업명을 입력하세요.')
    return
  }
  
  isSaving.value = true
  try {
    if (isEdit.value && editId.value) {
      await $fetch(`/api/business/${editId.value}/update`, {
        method: 'PUT',
        body: form.value
      })
    } else {
      await $fetch('/api/business/create', {
        method: 'POST',
        body: form.value
      })
    }
    showModal.value = false
    await loadBusinesses()
  } catch (e: any) {
    alert(e.data?.message || e.message || '저장에 실패했습니다.')
  } finally {
    isSaving.value = false
  }
}

function getStatusBadgeClass(status: string) {
  const classes: Record<string, string> = {
    'active': 'badge bg-success',
    'completed': 'badge bg-secondary',
    'suspended': 'badge bg-danger'
  }
  return classes[status] || 'badge bg-secondary'
}

function getStatusText(status: string) {
  const texts: Record<string, string> = {
    'active': '진행중',
    'completed': '완료',
    'suspended': '중단'
  }
  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>

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