<template>
  <Dialog 
    :visible="visible" 
    @update:visible="$emit('update:visible', $event)" 
    :header="eventModel.title" 
    :style="{ width: '90vw', maxWidth: '1200px' }" 
    :modal="true"
    class="event-details-dialog"
  >
    <TabView>
      <!-- 기본 정보 탭 -->
      <TabPanel header="기본 정보">
        <div class="event-details">
          <div class="event-details-header">
            <Badge :value="getEventTypeName(eventModel.eventType)" :severity="getStatusSeverity(eventModel.status)" />
            <Badge :value="getStatusName(eventModel.status)" :severity="getStatusSeverity(eventModel.status)" />
          </div>
          
          <div class="event-details-content">
            <div class="event-details-section">
              <h4>이벤트 정보</h4>
              <div class="grid">
                <div class="col-12 md:col-6">
                  <p><strong>시작일:</strong> {{ formattedStartDate }}</p>
                  <p><strong>종료일:</strong> {{ formattedEndDate }}</p>
                  <p><strong>장소:</strong> {{ eventModel.location }}</p>
                </div>
                <div class="col-12 md:col-6">
                  <p><strong>최대 참가자 수:</strong> {{ eventModel.maxParticipants || '제한 없음' }}</p>
                  <p><strong>현재 참가자 수:</strong> {{ eventModel.participants?.length || 0 }}</p>
                </div>
              </div>
            </div>
            
            <div class="event-details-section">
              <h4>설명</h4>
              <p>{{ eventModel.description || '설명이 없습니다.' }}</p>
            </div>
          </div>
        </div>
      </TabPanel>

      <!-- 참가자 관리 탭 -->
      <TabPanel header="참가자 관리">
        <ParticipantManagement
          :eventId="eventModel.id"
          :availableMembers="availableMembers"
          @participant-updated="handleParticipantUpdated"
        />
      </TabPanel>

      <!-- 점수 관리 탭 -->
      <TabPanel header="점수 관리">
        <ScoreManagement 
          :eventId="eventModel.id"
          :participants="eventModel.participants || []"
          :maxGames="eventModel.gameCount"
          @score-updated="$emit('score-updated')"
        />
      </TabPanel>
      <!-- 팀 편성 탭 -->
      <TabPanel header="팀 편성">
        <TeamGeneration :participants="confirmedParticipants" :teams="teams" @update:teams="teams = $event" @teams-generated="teams = $event" @save-teams="handleSaveTeams" />
      </TabPanel>
    </TabView>

    <template #footer>
      <div class="dialog-footer">
        <Button label="수정" icon="pi pi-pencil" class="p-button-text" @click="$emit('edit')" />
      </div>
    </template>
  </Dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import TeamGeneration from './TeamGeneration.vue';
import Dialog from 'primevue/dialog';
import TabView from 'primevue/tabview';
import TabPanel from 'primevue/tabpanel';
import Badge from 'primevue/badge';
import Button from 'primevue/button';
import InputNumber from 'primevue/inputnumber';
import Dropdown from 'primevue/dropdown';
import InputText from 'primevue/inputtext';
import ParticipantManagement from './ParticipantManagement.vue';
import ScoreManagement from './ScoreManagement.vue';
import dayjs from 'dayjs';

const props = defineProps({
  visible: { type: Boolean, required: true },
  event: { type: Object, default: () => ({}) },
  getEventTypeName: { type: Function, required: true },
  getStatusName: { type: Function, required: true },
  getStatusSeverity: { type: Function, required: true },
  formatDate: { type: Function, required: true },
  availableMembers: { type: Array, default: () => [] }
});

const emit = defineEmits(['update:visible', 'hide', 'edit', 'participant-updated', 'score-updated']);

const eventModel = computed(() => props.event || {});
const formattedStartDate = computed(() => props.formatDate(eventModel.value.startDate));
const formattedEndDate = computed(() => props.formatDate(eventModel.value.endDate));

const hideDialog = () => {
  emit('hide');
};
// 팀 생성 결과 저장
const teams = ref([]);

// 이벤트 상세 다이얼로그가 열릴 때마다 팀 목록 불러오기
watch(() => eventModel.value.id, async (eventId) => {
  if (eventId) {
    const latestTeams = await teamService.getTeams(eventId);
    teams.value = latestTeams;
  }
}, { immediate: true });

// 참가확정 참가자 목록을 계산하는 computed 속성
const confirmedParticipants = computed(() => {
  const arr = eventModel.value.EventParticipants?.filter(p => p.status === '참가확정') || [];
  console.log('[상위] 참가확정:', arr);
  return arr;
});

// 참가확정 인원 수
const confirmedCount = computed(() => confirmedParticipants.value.length);


// 팀 배정 저장 핸들러
import teamService from '@/services/teamService';
import { useToast } from 'primevue/usetoast';
const toast = useToast();

async function handleSaveTeams(savedTeams) {
  const eventId = eventModel.value.id;
  try {
    await teamService.saveTeams(eventId, savedTeams);
    toast.add({ severity: 'success', summary: '저장 완료', detail: '팀 배정이 저장되었습니다.', life: 2000 });
    // 저장 후 최신 팀 목록 불러오기
    const latestTeams = await teamService.getTeams(eventId);
    teams.value = latestTeams;
  } catch (e) {
    toast.add({ severity: 'error', summary: '저장 실패', detail: '팀 저장 중 오류가 발생했습니다.', life: 3000 });
  }
}

// 참가자 상태 변경 처리 함수
function handleParticipantUpdated(data) {
  // 부모 컴포넌트에 이벤트 전달
  emit('participant-updated', data);
  
  // 전체 참가자 목록이 있는 경우 직접 업데이트
  if (data.allParticipants) {
    // EventParticipants 속성을 완전히 대체
    eventModel.value.EventParticipants = [...data.allParticipants];
  }
};

</script>

<style scoped>
:deep(.mini-inputnumber .p-inputnumber-input) {
  width: 60px !important;
  min-width: 0 !important;
  max-width: 100% !important;
}
</style>

<style scoped>
.team-generation-section {
  margin-top: 1rem;
}
.team-box {
  background: #f8f9fa;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.04);
}
.event-details {
  margin-top: 1rem;
}

.event-details-header {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 1rem;
}

.event-details-section {
  margin-bottom: 2rem;
}

.event-details-section h4 {
  margin-bottom: 1rem;
  color: var(--primary-color);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
}

:deep(.p-dialog-content) {
  padding: 0 !important;
}

:deep(.p-tabview-panels) {
  padding: 1.5rem !important;
}
</style>
