<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-journal-text me-2"></i>회의록
        </h4>
        <NuxtLink to="/meeting/write" class="btn btn-primary">
          <i class="bi bi-plus-lg me-1"></i>회의록 작성
        </NuxtLink>
      </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.keyword"
                placeholder="제목 또는 내용"
                @keyup.enter="loadMeetings"
              />
            </div>
            <div class="col-1 text-end"><label class="col-form-label">유형</label></div>
            <div class="col-2">
              <div class="btn-group" role="group">
                <input type="radio" class="btn-check" name="meetingType" id="typeAll" value="" v-model="filter.meetingType" @change="loadMeetings">
                <label class="btn btn-outline-secondary btn-sm" for="typeAll">전체</label>
                <input type="radio" class="btn-check" name="meetingType" id="typeProject" value="PROJECT" v-model="filter.meetingType" @change="loadMeetings">
                <label class="btn btn-outline-secondary btn-sm" for="typeProject">프로젝트</label>
                <input type="radio" class="btn-check" name="meetingType" id="typeInternal" value="INTERNAL" v-model="filter.meetingType" @change="loadMeetings">
                <label class="btn btn-outline-secondary btn-sm" for="typeInternal">내부</label>
              </div>
            </div>
            <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>
          <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">
              <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-1"></div>
            <div class="col-2">
              <button class="btn btn-primary btn-sm me-1" @click="loadMeetings">
                <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: 110px">회의일</th>
                  <th>제목</th>
                  <th style="width: 80px" class="text-center">유형</th>
                  <th style="width: 150px">프로젝트</th>
                  <th style="width: 80px" class="text-center">참석자</th>
                  <th style="width: 100px">작성자</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="meetings.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="(meeting, idx) in meetings" :key="meeting.meetingId">
                  <td class="text-center">{{ (pagination.page - 1) * pagination.pageSize + idx + 1 }}</td>
                  <td>
                    {{ formatDate(meeting.meetingDate) }}
                    <br v-if="meeting.startTime" />
                    <small v-if="meeting.startTime" class="text-muted">
                      {{ meeting.startTime?.slice(0, 5) }}
                      <span v-if="meeting.endTime">~{{ meeting.endTime?.slice(0, 5) }}</span>
                    </small>
                  </td>
                  <td>
                    <NuxtLink :to="`/meeting/${meeting.meetingId}`" class="text-decoration-none">
                      {{ meeting.meetingTitle }}
                    </NuxtLink>
                    <span v-if="meeting.aiStatus === 'CONFIRMED'" class="badge bg-success ms-1">AI</span>
                  </td>
                  <td class="text-center">
                    <span :class="getTypeBadgeClass(meeting.meetingType)">
                      {{ getTypeText(meeting.meetingType) }}
                    </span>
                  </td>
                  <td>{{ meeting.projectName || '-' }}</td>
                  <td class="text-center">
                    <span class="badge bg-light text-dark">{{ meeting.attendeeCount }}명</span>
                  </td>
                  <td>{{ meeting.authorName }}</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 Meeting {
  meetingId: number
  meetingTitle: string
  meetingDate: string
  startTime: string | null
  endTime: string | null
  meetingType: string
  projectId: number | null
  projectName: string | null
  attendeeCount: number
  authorId: number
  authorName: string
  aiStatus: string | null
}

interface Project {
  projectId: number
  projectName: string
}

const meetings = ref<Meeting[]>([])
const projects = ref<Project[]>([])
const isLoading = ref(false)

const filter = ref({
  keyword: '',
  meetingType: '',
  projectId: '',
  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 loadMeetings()
})

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 loadMeetings() {
  isLoading.value = true
  try {
    const res = await $fetch<any>('/api/meeting/list', {
      query: {
        keyword: filter.value.keyword || undefined,
        meetingType: filter.value.meetingType || undefined,
        projectId: filter.value.projectId || undefined,
        startDate: filter.value.startDate || undefined,
        endDate: filter.value.endDate || undefined,
        page: pagination.value.page,
        pageSize: pagination.value.pageSize
      }
    })
    meetings.value = res.meetings || []
    pagination.value.total = res.pagination?.total || 0
    pagination.value.totalPages = res.pagination?.totalPages || 0
  } catch (e) {
    console.error('Load meetings error:', e)
  } finally {
    isLoading.value = false
  }
}

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

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

function getTypeBadgeClass(type: string) {
  return type === 'PROJECT' ? 'badge bg-primary' : 'badge bg-info'
}

function getTypeText(type: string) {
  return type === 'PROJECT' ? '프로젝트' : '내부'
}

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>
