<template>
  <div class="participant-management">
    <Toast />
    <div class="header">
      <Button label="참가자 추가" icon="pi pi-plus" class="p-button-success" @click="openNewDialog" />
    </div>
    <DataTable
      :value="participants"
      :loading="loading"
      class="mt-4"
      :paginator="true"
      :rows="10"
      stripedRows
      v-model:filters="filters"
    >
      <Column field="Member.name" header="이름" sortable>
        <template #body="slotProps">
          <div class="flex flex-column">
            <span>{{ slotProps.data.Member.name }}</span>
            <small class="text-500">{{ slotProps.data.Member.phone }}</small>
          </div>
        </template>
      </Column>
      <Column field="Member.memberType" header="회원 유형" sortable>
        <template #body="slotProps">
          <Badge :value="getMemberTypeLabel(slotProps.data.Member.memberType)" :severity="getMemberTypeSeverity(slotProps.data.Member.memberType)" />
        </template>
      </Column>
      <Column field="status" header="참가 상태" sortable>
        <template #body="slotProps">
          <Badge :value="getParticipantStatusLabel(slotProps.data.status)" :severity="getParticipantStatusSeverity(slotProps.data.status)" />
        </template>
      </Column>
      <Column field="paymentStatus" header="결제 상태" sortable>
        <template #body="slotProps">
          <Badge :value="getPaymentStatusLabel(slotProps.data.paymentStatus)" :severity="getPaymentStatusSeverity(slotProps.data.paymentStatus)" />
        </template>
      </Column>
      <Column field="createdAt" header="등록일" sortable>
        <template #body="slotProps">
          {{ formatDate(slotProps.data.createdAt) }}
        </template>
      </Column>
      <Column header="작업">
        <template #body="slotProps">
          <div class="flex gap-2">
            <Button icon="pi pi-pencil" class="p-button-rounded p-button-text" @click="editParticipant(slotProps.data)" />
            <Button icon="pi pi-trash" class="p-button-rounded p-button-text p-button-danger" @click="confirmDeleteParticipant(slotProps.data)" />
          </div>
        </template>
      </Column>
    </DataTable>

    <!-- 참가자 추가/수정 다이얼로그 -->
    <Dialog v-model:visible="participantDialog" :header="dialogTitle" modal class="p-fluid" :style="{width: '450px'}">
      <div class="field">
        <label for="member">회원</label>
        <Select
          id="member"
          v-model="editingParticipant.memberId"
          :options="props.availableMembers"
          optionLabel="name"
          optionValue="id"
          placeholder="회원을 선택하세요"
          :class="{ 'p-invalid': submitted && !editingParticipant.memberId }"
          :disabled="!!editingParticipant.id"
        />
        <small v-if="submitted && !editingParticipant.memberId" class="p-error">회원을 선택해주세요.</small>
      </div>
      <div class="field">
        <label for="status">참가 상태</label>
        <Select
          id="status"
          v-model="editingParticipant.status"
          :options="PARTICIPANT_STATUS_OPTIONS"
          optionLabel="name"
          optionValue="value"
          placeholder="상태를 선택하세요"
          :class="{ 'p-invalid': submitted && !editingParticipant.status }"
        />
        <small v-if="submitted && !editingParticipant.status" class="p-error">참가 상태를 선택해주세요.</small>
      </div>
      <div class="field">
        <label for="paymentStatus">결제 상태</label>
        <Select
          id="paymentStatus"
          v-model="editingParticipant.paymentStatus"
          :options="PAYMENT_STATUS_OPTIONS"
          optionLabel="name"
          optionValue="value"
          placeholder="결제 상태를 선택하세요"
          :class="{ 'p-invalid': submitted && !editingParticipant.paymentStatus }"
        />
        <small v-if="submitted && !editingParticipant.paymentStatus" class="p-error">결제 상태를 선택해주세요.</small>
      </div>
      <template #footer>
        <Button label="취소" icon="pi pi-times" class="p-button-text" @click="hideDialog" />
        <Button label="저장" icon="pi pi-check" class="p-button-text" @click="saveParticipant" />
      </template>
    </Dialog>

    <!-- 삭제 확인 다이얼로그 -->
    <Dialog v-model:visible="deleteDialog" :style="{width: '450px'}" header="확인" :modal="true">
      <div class="confirmation-content">
        <i class="pi pi-exclamation-triangle mr-3" style="font-size: 2rem" />
        <span>이 참가자를 제거하시겠습니까?</span>
      </div>
      <template #footer>
        <Button label="아니오" icon="pi pi-times" class="p-button-text" @click="deleteDialog = false" />
        <Button label="예" icon="pi pi-check" class="p-button-text" @click="deleteParticipant" />
      </template>
    </Dialog>
  </div>
</template>

<script setup>
import {
  PARTICIPANT_STATUS_OPTIONS,
  PAYMENT_STATUS_OPTIONS,
  getMemberTypeLabel,
  getMemberTypeSeverity,
  getParticipantStatusLabel,
  getParticipantStatusSeverity,
  getPaymentStatusLabel,
  getPaymentStatusSeverity
} from '@/utils/enumMappings';
import { ref, computed, onMounted } from 'vue';
import { useToast } from 'primevue/usetoast';
import eventService from '@/services/eventService';
import dayjs from 'dayjs';

const props = defineProps({
  eventId: {
    type: [String, Number],
    required: true
  },
  availableMembers: {
    type: Array,
    required: true
  }
});

const emit = defineEmits(['participant-updated']);
const toast = useToast();
const participants = ref([]);
const loading = ref(false);
const filters = ref({});
const participantDialog = ref(false);
const deleteDialog = ref(false);
const submitted = ref(false);
const clubId = ref(localStorage.getItem('clubId') || null);
const editingParticipant = ref({
  clubId: clubId.value,
  memberId: null,
  status: 'pending',
  paymentStatus: 'unpaid'
});
const participantToDelete = ref(null);

const fetchParticipants = async () => {
  try {
    loading.value = true;
    const data = await eventService.getEventParticipants(props.eventId);
    participants.value = data;
  } catch (error) {
    toast.add({
      severity: 'error',
      summary: '오류',
      detail: '참가자 목록을 불러오는 중 오류가 발생했습니다.',
      life: 3000
    });
  } finally {
    loading.value = false;
  }
};

const openNewDialog = () => {
  editingParticipant.value = {
    clubId: localStorage.getItem('clubId') || null,
    memberId: null,
    status: 'pending',
    paymentStatus: 'unpaid'
  };
  submitted.value = false;
  participantDialog.value = true;
};

const editParticipant = (participant) => {
  editingParticipant.value = {
    id: participant.id,
    clubId: localStorage.getItem('clubId') || null,
    memberId: participant.memberId,
    status: participant.status,
    paymentStatus: participant.paymentStatus
  };
  participantDialog.value = true;
  submitted.value = false;
};

const hideDialog = () => {
  participantDialog.value = false;
  submitted.value = false;
};

const saveParticipant = async () => {
  submitted.value = true;

  if (!editingParticipant.value.memberId) {
    return;
  }

  try {
    if (editingParticipant.value.id) {
      // 수정
      await eventService.updateEventParticipant(props.eventId, editingParticipant.value);
      toast.add({
        severity: 'success',
        summary: '성공',
        detail: '참가자 정보가 수정되었습니다.',
        life: 3000
      });
    } else {
      // 신규 등록
      await eventService.addEventParticipant(props.eventId, editingParticipant.value);
      toast.add({
        severity: 'success',
        summary: '성공',
        detail: '참가자가 추가되었습니다.',
        life: 3000
      });
    }

    // 참가자 데이터 다시 가져오기
    await fetchParticipants();
    
    // 참가자 변경 이벤트 발생 - 변경된 참가자와 전체 참가자 목록 함께 전달
    emit('participant-updated', {
      updatedParticipant: editingParticipant.value,
      allParticipants: participants.value
    });
    
    hideDialog();
  } catch (error) {
    console.error('참가자 저장 오류:', error.message);
    toast.add({
      severity: 'error',
      summary: '오류',
      detail: error.message,
      life: 3000
    });
  }
};

const confirmDeleteParticipant = (participant) => {
  participantToDelete.value = participant;
  deleteDialog.value = true;
};

const deleteParticipant = async () => {
  try {
    await eventService.removeEventParticipant(props.eventId, { id: participantToDelete.value.id });
    toast.add({
      severity: 'success',
      summary: '성공',
      detail: '참가자가 삭제되었습니다.',
      life: 3000
    });
    deleteDialog.value = false;
    participantToDelete.value = null;
    await fetchParticipants();
  } catch (error) {
    console.error('참가자 삭제 오류:', error);
    toast.add({
      severity: 'error',
      summary: '오류',
      detail: '참가자 삭제 중 오류가 발생했습니다.',
      life: 3000
    });
  }
};

const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm');
};

const dialogTitle = computed(() => {
  return editingParticipant.value.id ? '참가자 정보 수정' : '참가자 추가';
});

onMounted(() => {
  fetchParticipants();
});
</script>

<style scoped>
.participant-management {
  padding: 1rem;
}

.header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 1rem;
}

.field {
  margin-bottom: 1.5rem;
}

.field label {
  display: block;
  margin-bottom: 0.5rem;
}

.confirmation-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  padding: 1rem;
}
</style>

<style>
:deep(.p-toast) {
  z-index: 9999;
}
</style>
