<template>
  <div>
    <AppHeader />
    
    <div class="container-fluid py-4">
      <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
          <h4>
            <i class="bi bi-briefcase me-2"></i>
            {{ business?.businessName }}
          </h4>
          <p class="text-muted mb-0">
            <span :class="getStatusBadgeClass(business?.businessStatus || '')">
              {{ getStatusText(business?.businessStatus || '') }}
            </span>
            <span v-if="business?.businessCode" class="ms-2">
              <code>{{ business.businessCode }}</code>
            </span>
          </p>
        </div>
        <div>
          <NuxtLink to="/business" class="btn btn-outline-secondary me-2">
            <i class="bi bi-arrow-left me-1"></i> 목록
          </NuxtLink>
          <button class="btn btn-primary me-2" @click="openEditModal">
            <i class="bi bi-pencil me-1"></i> 수정
          </button>
          <button class="btn btn-outline-danger" @click="deleteBusiness">
            <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="business" class="row">
        <!-- 왼쪽: 기본 정보 -->
        <div class="col-md-4">
          <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>{{ business.businessCode || '-' }}</span>
              </li>
              <li class="list-group-item d-flex justify-content-between">
                <span class="text-muted">발주처</span>
                <span>{{ business.clientName || '-' }}</span>
              </li>
              <li class="list-group-item d-flex justify-content-between">
                <span class="text-muted">계약 시작일</span>
                <span>{{ formatDate(business.contractStartDate) || '-' }}</span>
              </li>
              <li class="list-group-item d-flex justify-content-between">
                <span class="text-muted">계약 종료일</span>
                <span>{{ formatDate(business.contractEndDate) || '-' }}</span>
              </li>
              <li class="list-group-item d-flex justify-content-between">
                <span class="text-muted">등록자</span>
                <span>{{ business.createdByName || '-' }}</span>
              </li>
              <li class="list-group-item d-flex justify-content-between">
                <span class="text-muted">등록일</span>
                <span>{{ formatDateTime(business.createdAt) }}</span>
              </li>
            </ul>
            <div class="card-body" v-if="business.description">
              <label class="form-label text-muted">설명</label>
              <p class="mb-0">{{ business.description }}</p>
            </div>
          </div>
        </div>

        <!-- 오른쪽: 소속 프로젝트 -->
        <div class="col-md-8">
          <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
              <strong>소속 프로젝트 ({{ projects.length }}개)</strong>
            </div>
            <div class="table-responsive">
              <table class="table table-hover mb-0">
                <thead class="table-light">
                  <tr>
                    <th>프로젝트명</th>
                    <th style="width: 80px">유형</th>
                    <th style="width: 150px">기간</th>
                    <th style="width: 100px">상태</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="p in projects" :key="p.projectId">
                    <td>
                      <NuxtLink :to="`/project/${p.projectId}`" class="text-decoration-none">
                        {{ p.projectName }}
                      </NuxtLink>
                      <small v-if="p.projectCode" class="text-muted ms-1">({{ p.projectCode }})</small>
                    </td>
                    <td>
                      <span :class="p.projectType === 'SM' ? 'badge bg-info' : 'badge bg-primary'">
                        {{ p.projectType || 'SI' }}
                      </span>
                    </td>
                    <td>
                      <small v-if="p.startDate">
                        {{ formatDate(p.startDate) }} ~ {{ formatDate(p.endDate) || '진행중' }}
                      </small>
                      <span v-else>-</span>
                    </td>
                    <td>
                      <span :class="getProjectStatusClass(p.projectStatus)">
                        {{ getProjectStatusText(p.projectStatus) }}
                      </span>
                    </td>
                  </tr>
                  <tr v-if="projects.length === 0">
                    <td colspan="4" class="text-center py-4 text-muted">
                      소속된 프로젝트가 없습니다.
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </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">사업 수정</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" />
              </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">
                <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="updateBusiness" :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 route = useRoute()
const router = useRouter()

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

const business = ref<any>(null)
const projects = ref<any[]>([])
const isLoading = ref(true)
const showModal = ref(false)
const isSaving = ref(false)

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

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

async function loadBusiness() {
  isLoading.value = true
  try {
    const res = await $fetch<any>(`/api/business/${businessId.value}/detail`)
    business.value = res.business
    projects.value = res.projects || []
  } catch (e) {
    console.error('Load business error:', e)
    alert('사업 정보를 불러올 수 없습니다.')
    router.push('/business')
  } finally {
    isLoading.value = false
  }
}

function openEditModal() {
  form.value = {
    businessName: business.value.businessName,
    businessCode: business.value.businessCode || '',
    clientName: business.value.clientName || '',
    contractStartDate: business.value.contractStartDate?.split('T')[0] || '',
    contractEndDate: business.value.contractEndDate?.split('T')[0] || '',
    businessStatus: business.value.businessStatus || 'active',
    description: business.value.description || ''
  }
  showModal.value = true
}

async function updateBusiness() {
  if (!form.value.businessName) {
    alert('사업명을 입력하세요.')
    return
  }
  
  isSaving.value = true
  try {
    await $fetch(`/api/business/${businessId.value}/update`, {
      method: 'PUT',
      body: form.value
    })
    showModal.value = false
    await loadBusiness()
  } catch (e: any) {
    alert(e.data?.message || e.message || '수정에 실패했습니다.')
  } finally {
    isSaving.value = false
  }
}

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

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 getProjectStatusClass(status: string) {
  const classes: Record<string, string> = {
    'ACTIVE': 'badge bg-success',
    'COMPLETED': 'badge bg-secondary',
    'HOLD': 'badge bg-warning'
  }
  return classes[status] || 'badge bg-secondary'
}

function getProjectStatusText(status: string) {
  const texts: Record<string, string> = {
    'ACTIVE': '진행중',
    'COMPLETED': '완료',
    'HOLD': '보류'
  }
  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')}`
}

function formatDateTime(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')} ${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}`
}
</script>

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