<template>
  <div class="subscription-management-container">
    <div class="header">
      <h2>구독 플랜 관리</h2>
      <Button label="플랜 추가" icon="pi pi-plus" @click="openNewPlanDialog" />
    </div>
    
    <DataTable 
      :value="plans" 
      :loading="loading"
      :paginator="true" 
      :rows="10"
      stripedRows
      responsiveLayout="scroll"
      v-model:expandedRows="expandedRows"
      dataKey="id"
      @row-expand="onPlanExpand"
    >
      <Column :expander="true" style="width: 1%"/>
      <Column field="id" header="ID" sortable style="width: 5%"></Column>
      <Column field="name" header="플랜명" sortable></Column>
      <Column field="maxMembers" header="최대 회원수" sortable style="width: 10%">
        <template #body="slotProps">
          {{ slotProps.data.maxMembers }}명
        </template>
      </Column>
      <Column field="price" header="가격" sortable style="width: 10%">
        <template #body="slotProps">
          {{ formatCurrency(slotProps.data.price) }}
        </template>
      </Column>
      <Column field="status" header="상태" sortable style="width: 15%">
        <template #body="slotProps">
          <Badge :value="getStatusLabel(slotProps.data.status)" :severity="getStatusSeverity(slotProps.data.status)" />
        </template>
      </Column>
      <Column header="작업" style="width: 10%">
        <template #body="slotProps">
          <div class="action-buttons">
            <Button icon="pi pi-pencil" class="p-button-rounded p-button-text p-button-sm" @click="editPlan(slotProps.data)" />
            <Button icon="pi pi-trash" class="p-button-rounded p-button-text p-button-danger p-button-sm" @click="confirmDeletePlan(slotProps.data)" />
          </div>
        </template>
      </Column>
      <template #expansion="slotProps">
        <div class="plan-details">
          <div class="plan-description">
            <h4>설명</h4>
            <p>{{ slotProps.data.description }}</p>
          </div>
          <div class="plan-features">
            <h4>포함된 기능</h4>
            <div class="features-grid">
              <div v-for="feature in slotProps.data.Features" :key="feature.id" class="feature-item">
                <i class="pi pi-check-circle" style="color: var(--green-500)"></i>
                <div class="feature-details">
                  <h5>{{ feature.name }}</h5>
                  <p>{{ feature.description }}</p>
                </div>
              </div>
            </div>
          </div>

          <div class="plan-subscriptions">
            <div class="subscriptions-header">
              <h4>구독 중인 클럽</h4>
              <Button label="클럽 구독 추가" icon="pi pi-plus" @click="openNewSubscriptionDialog(slotProps.data)" />
            </div>
            <DataTable :value="planSubscriptions[slotProps.data.id] || []" :loading="subscriptionsLoading[slotProps.data.id]">
              <Column field="Club.name" header="클럽명"></Column>
              <Column field="startDate" header="시작일">
                <template #body="subProps">
                  {{ formatDate(subProps.data.startDate) }}
                </template>
              </Column>
              <Column field="expiryDate" header="만료일">
                <template #body="subProps">
                  {{ formatDate(subProps.data.expiryDate) }}
                </template>
              </Column>
              <Column field="status" header="상태">
                <template #body="subProps">
                  <Badge :value="getSubscriptionStatusLabel(subProps.data.status)" :severity="getSubscriptionStatusSeverity(subProps.data.status)" />
                </template>
              </Column>
              <Column header="작업">
                <template #body="subProps">
                  <div class="action-buttons">
                    <Button icon="pi pi-pencil" class="p-button-rounded p-button-text p-button-sm" @click="editSubscription(subProps.data)" />
                    <Button icon="pi pi-trash" class="p-button-rounded p-button-text p-button-danger p-button-sm" @click="confirmDeleteSubscription(subProps.data)" />
                  </div>
                </template>
              </Column>
            </DataTable>
          </div>
        </div>
      </template>
    </DataTable>

    <!-- 구독 플랜 추가/수정 다이얼로그 -->
    <Dialog v-model:visible="planDialog" :header="dialogTitle" :style="{ width: '600px' }" :modal="true" class="p-fluid">
      <div class="field">
        <label for="name">플랜명</label>
        <InputText id="name" v-model="plan.name" :class="{'p-invalid': submitted && !plan.name}" />
        <small class="p-error" v-if="submitted && !plan.name">플랜명은 필수입니다.</small>
      </div>
      
      <div class="field">
        <label for="description">설명</label>
        <Textarea id="description" v-model="plan.description" rows="3" />
      </div>
      
      <div class="field">
        <label for="maxMembers">최대 회원수</label>
        <InputNumber id="maxMembers" v-model="plan.maxMembers" :min="1" />
      </div>
      
      <div class="field">
        <label for="price">가격</label>
        <InputNumber id="price" v-model="plan.price" mode="currency" currency="KRW" locale="ko-KR" />
      </div>
      
      <div class="field">
        <label for="features">기능</label>
        <MultiSelect id="features" v-model="plan.features" :options="availableFeatures" 
          optionLabel="name" optionValue="id" display="chip" :class="{'p-invalid': submitted && !plan.features?.length}" />
        <small class="p-error" v-if="submitted && !plan.features?.length">하나 이상의 기능을 선택해주세요.</small>
      </div>
      
      <div class="field">
        <label for="status">상태</label>
        <Select id="status" v-model="plan.status" :options="SUBSCRIPTION_STATUS_OPTIONS" optionLabel="name" optionValue="value" />
      </div>
      
      <template #footer>
        <Button label="취소" icon="pi pi-times" class="p-button-text" @click="hidePlanDialog" />
        <Button label="저장" icon="pi pi-check" class="p-button-text" @click="savePlan" />
      </template>
    </Dialog>
    
    <!-- 클럽 구독 추가/수정 다이얼로그 -->
    <Dialog v-model:visible="subscriptionDialog" :header="subscriptionDialogTitle" :style="{ width: '500px' }" :modal="true" class="p-fluid">
      <div class="field">
        <label for="club">클럽</label>
        <Select id="club" v-model="subscription.clubId" :options="availableClubs" optionLabel="name" optionValue="id" 
          :class="{'p-invalid': subscriptionSubmitted && !subscription.clubId}" placeholder="클럽 선택" />
        <small class="p-error" v-if="subscriptionSubmitted && !subscription.clubId">클럽을 선택해주세요.</small>
      </div>

      <div class="field">
        <label for="startDate">시작일</label>
        <DatePicker id="startDate" v-model="subscription.startDate" :showIcon="true" dateFormat="yy-mm-dd"
          :class="{'p-invalid': subscriptionSubmitted && !subscription.startDate}" />
        <small class="p-error" v-if="subscriptionSubmitted && !subscription.startDate">시작일을 선택해주세요.</small>
      </div>

      <div class="field">
        <label for="expiryDate">만료일</label>
        <DatePicker id="expiryDate" v-model="subscription.expiryDate" :showIcon="true" dateFormat="yy-mm-dd"
          :class="{'p-invalid': subscriptionSubmitted && !subscription.expiryDate}" :minDate="subscription.startDate" />
        <small class="p-error" v-if="subscriptionSubmitted && !subscription.expiryDate">만료일을 선택해주세요.</small>
      </div>

      <div class="field">
        <label for="status">상태</label>
        <Select id="status" v-model="subscription.status" :options="SUBSCRIPTION_STATUS_OPTIONS" optionLabel="name" optionValue="value" />
      </div>

      <template #footer>
        <Button label="취소" icon="pi pi-times" class="p-button-text" @click="hideSubscriptionDialog" />
        <Button label="저장" icon="pi pi-check" class="p-button-text" @click="saveSubscription" />
      </template>
    </Dialog>
    
    <!-- 삭제 확인 다이얼로그 -->
    <Dialog v-model:visible="deletePlanDialog" :style="{ width: '450px' }" header="확인" :modal="true">
      <div class="confirmation-content">
        <i class="pi pi-exclamation-triangle mr-3" style="font-size: 2rem" />
        <span v-if="plan">이 구독 플랜을 삭제하시겠습니까?</span>
      </div>
      <template #footer>
        <Button label="아니오" icon="pi pi-times" class="p-button-text" @click="deletePlanDialog = false" />
        <Button label="예" icon="pi pi-check" class="p-button-text" @click="deletePlan" />
      </template>
    </Dialog>
    
    <!-- 구독 삭제 확인 다이얼로그 -->
    <Dialog v-model:visible="deleteSubscriptionDialog" :style="{ width: '450px' }" header="확인" :modal="true">
      <div class="confirmation-content">
        <i class="pi pi-exclamation-triangle mr-3" style="font-size: 2rem" />
        <span v-if="subscription">이 구독을 삭제하시겠습니까?</span>
      </div>
      <template #footer>
        <Button label="아니오" icon="pi pi-times" class="p-button-text" @click="deleteSubscriptionDialog = false" />
        <Button label="예" icon="pi pi-check" class="p-button-text" @click="deleteSubscription" />
      </template>
    </Dialog>
    
    <Toast />
  </div>
</template>

<script setup>
import { getStatusLabel, getStatusSeverity, getSubscriptionStatusLabel, getSubscriptionStatusSeverity, SUBSCRIPTION_STATUS_OPTIONS, SUBSCRIPTION_STATUS_LABELS } from '@/utils/enumMappings';
import { ref, onMounted, computed, watch } from 'vue';
import { useGtag } from 'vue-gtag-next';
import { useToast } from 'primevue/usetoast';
import axios from 'axios';
import adminService from '@/services/adminService';

const toast = useToast();
const gtag = useGtag();
const API_URL = 'http://localhost:3030/api';

// 데이터 정의
const plans = ref([]);
const clubs = ref([]);
const features = ref([]);
const subscriptions = ref([]);
const planSubscriptions = ref({});
const loading = ref(false);
const subscriptionsLoading = ref({});

// 상태 변수
const plan = ref({});
const planDialog = ref(false);
const deletePlanDialog = ref(false);
const submitted = ref(false);
const isNewPlan = ref(false);
const expandedRows = ref([]);
const availableFeatures = ref([]);
const subscription = ref({});
const subscriptionDialog = ref(false);
const deleteSubscriptionDialog = ref(false);
const subscriptionSubmitted = ref(false);
const availableClubs = ref([]);
const selectedPlan = ref(null);

// 다이얼로그 제목
const dialogTitle = computed(() => {
  return isNewPlan.value ? '구독 플랜 추가' : '구독 플랜 수정';
});

const subscriptionDialogTitle = computed(() => {
  return !subscription.value.id ? '클럽 구독 추가' : '클럽 구독 수정';
});

// 구독 목록 가져오기
const fetchSubscriptions = async () => {
  loading.value = true;
  try {
    const response = await adminService.getSubscriptions();
    subscriptions.value = response.data;
  } catch (error) {
    console.error('구독 목록을 가져오는 중 오류 발생:', error);
    toast.add({ severity: 'error', summary: '오류', detail: '구독 목록을 가져오는 중 오류가 발생했습니다.', life: 3000 });
  } finally {
    loading.value = false;
  }
};

// 플랜별 구독 목록 가져오기
const fetchPlanSubscriptions = async (planId) => {
  subscriptionsLoading.value[planId] = true;
  try {
    const response = await adminService.getPlanSubscriptions(planId);
    planSubscriptions.value[planId] = response.data;
  } catch (error) {
    console.error('구독 목록을 가져오는 중 오류 발생:', error);
    toast.add({ severity: 'error', summary: '오류', detail: '구독 목록을 가져오는 중 오류가 발생했습니다.', life: 3000 });
  } finally {
    subscriptionsLoading.value[planId] = false;
  }
};

// 컴포넌트 마운트 시 데이터 로드
// 페이지 진입 시 Google Analytics 페이지뷰 추적
onMounted(async () => {
  const gtag = useGtag();
  gtag.pageview({
    page_title: '구독플랜관리',
    page_path: window.location.pathname,
    page_location: window.location.href
  });
  await fetchPlans();
  await fetchFeatures();
  await fetchClubs();
  await fetchSubscriptions();
});

// 플랜 확장 시 구독 목록 로드
const onPlanExpand = (event) => {
  const planId = event.data.id;
  fetchPlanSubscriptions(planId);
};

// 구독 플랜 목록 가져오기
const fetchPlans = async () => {
  loading.value = true;
  try {
    const response = await adminService.getPlans();
    plans.value = response.data;
  } catch (error) {
    console.error('구독 플랜 목록을 가져오는 중 오류 발생:', error);
    toast.add({ severity: 'error', summary: '오류', detail: '구독 플랜 목록을 가져오는 중 오류가 발생했습니다.', life: 3000 });
  } finally {
    loading.value = false;
  }
};

// 기능 목록 가져오기
const fetchFeatures = async () => {
  try {
    const response = await adminService.getFeatures();
    availableFeatures.value = response.data;
  } catch (error) {
    console.error('기능 목록을 가져오는 중 오류 발생:', error);
    toast.add({ severity: 'error', summary: '오류', detail: '기능 목록을 가져오는 중 오류가 발생했습니다.', life: 3000 });
  }
};

// 클럽 목록 가져오기
const fetchClubs = async () => {
  try {
    const response = await adminService.getClubs();
    availableClubs.value = response.data;
  } catch (error) {
    console.error('클럽 목록을 가져오는 중 오류 발생:', error);
    toast.add({ severity: 'error', summary: '오류', detail: '클럽 목록을 가져오는 중 오류가 발생했습니다.', life: 3000 });
  }
};

// 새 구독 플랜 다이얼로그 열기
const openNewPlanDialog = () => {
  plan.value = {
    name: '',
    description: '',
    maxMembers: 30,
    price: 30000,
    features: [],
    status: 'active'
  };
  submitted.value = false;
  planDialog.value = true;
  isNewPlan.value = true;
};

// 구독 플랜 수정 다이얼로그 열기
const editPlan = (planData) => {
  plan.value = { ...planData };
  plan.value.features = planData.Features.map(f => f.id);
  submitted.value = false;
  planDialog.value = true;
  isNewPlan.value = false;
};

// 다이얼로그 닫기
const hidePlanDialog = () => {
  planDialog.value = false;
  submitted.value = false;
};

// 구독 플랜 저장
const savePlan = async () => {
  submitted.value = true;

  if (!plan.value.name || !plan.value.features?.length) {
    return;
  }

  try {
    if (isNewPlan.value) {
      await adminService.createPlan(plan.value);
      toast.add({ severity: 'success', summary: '성공', detail: '구독 플랜이 생성되었습니다.', life: 3000 });
    } else {
      await adminService.updatePlan(plan.value.id, plan.value);
      toast.add({ severity: 'success', summary: '성공', detail: '구독 플랜이 수정되었습니다.', life: 3000 });
    }
    
    planDialog.value = false;
    await fetchPlans();
  } catch (error) {
    console.error('구독 플랜 저장 중 오류 발생:', error);
    toast.add({ severity: 'error', summary: '오류', detail: '구독 플랜 저장 중 오류가 발생했습니다.', life: 3000 });
  }
};

// 구독 플랜 삭제 확인
const confirmDeletePlan = (planData) => {
  plan.value = planData;
  deletePlanDialog.value = true;
};

// 구독 플랜 삭제
const deletePlan = async () => {
  try {
    await adminService.deletePlan(plan.value.id);
    
    deletePlanDialog.value = false;
    toast.add({ severity: 'success', summary: '성공', detail: '구독 플랜이 삭제되었습니다.', life: 3000 });
    await fetchPlans();
  } catch (error) {
    console.error('구독 플랜 삭제 중 오류 발생:', error);
    toast.add({ severity: 'error', summary: '오류', detail: '구독 플랜 삭제 중 오류가 발생했습니다.', life: 3000 });
  }
};

// 새 구독 다이얼로그 열기
const openNewSubscriptionDialog = (plan) => {
  selectedPlan.value = plan;
  subscription.value = {
    planId: plan.id,
    clubId: null,
    startDate: new Date(),
    expiryDate: new Date(new Date().setFullYear(new Date().getFullYear() + 1)),
    status: 'active'
  };
  subscriptionSubmitted.value = false;
  subscriptionDialog.value = true;
};

// 구독 수정 다이얼로그 열기
const editSubscription = (subscriptionData) => {
  subscription.value = {
    id: subscriptionData.id,
    planId: subscriptionData.planId,
    clubId: subscriptionData.Club.id,
    startDate: new Date(subscriptionData.startDate),
    expiryDate: new Date(subscriptionData.expiryDate),
    status: subscriptionData.status
  };
  subscriptionSubmitted.value = false;
  subscriptionDialog.value = true;
};

// 구독 다이얼로그 닫기
const hideSubscriptionDialog = () => {
  subscriptionDialog.value = false;
  subscriptionSubmitted.value = false;
};

// 구독 저장
const saveSubscription = async () => {
  subscriptionSubmitted.value = true;

  if (!subscription.value.clubId || !subscription.value.startDate || !subscription.value.expiryDate) {
    return;
  }

  try {
    if (!subscription.value.id) {
      await adminService.createSubscription(subscription.value);
      toast.add({ severity: 'success', summary: '성공', detail: '구독이 추가되었습니다.', life: 3000 });
    } else {
      await adminService.updateSubscription(subscription.value.id, subscription.value);
      toast.add({ severity: 'success', summary: '성공', detail: '구독이 수정되었습니다.', life: 3000 });
    }
    
    subscriptionDialog.value = false;
    await fetchPlanSubscriptions(subscription.value.planId);
  } catch (error) {
    console.error('구독 저장 중 오류 발생:', error);
    toast.add({ severity: 'error', summary: '오류', detail: '구독을 저장하는 중 오류가 발생했습니다.', life: 3000 });
  }
};

// 구독 삭제 확인
const confirmDeleteSubscription = (subscriptionData) => {
  subscription.value = subscriptionData;
  deleteSubscriptionDialog.value = true;
};

// 구독 삭제
const deleteSubscription = async () => {
  try {
    await adminService.deleteSubscription(subscription.value.id);
    
    deleteSubscriptionDialog.value = false;
    toast.add({ severity: 'success', summary: '성공', detail: '구독이 삭제되었습니다.', life: 3000 });
    await fetchPlanSubscriptions(subscription.value.planId);
  } catch (error) {
    console.error('구독 삭제 중 오류 발생:', error);
    toast.add({ severity: 'error', summary: '오류', detail: '구독 삭제 중 오류가 발생했습니다.', life: 3000 });
  }
};

// 금액 포맷팅
const formatCurrency = (amount) => {
  return new Intl.NumberFormat('ko-KR', {
    style: 'currency',
    currency: 'KRW'
  }).format(amount);
};

// 날짜 포맷팅
const formatDate = (date) => {
  if (!date) return '-';
  const d = new Date(date);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
};
</script>

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

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.header h2 {
  margin: 0;
}

.action-buttons {
  display: flex;
  gap: 0.5rem;
}

.plan-features {
  padding: 1rem;
  background-color: var(--surface-ground);
  border-radius: 4px;
}

.plan-features h4 {
  margin: 0 0 1rem 0;
  color: var(--text-color);
}

.features-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 1rem;
}

.feature-item {
  display: flex;
  align-items: flex-start;
  gap: 0.5rem;
  padding: 0.5rem;
  background-color: var(--surface-card);
  border-radius: 4px;
}

.feature-details h5 {
  margin: 0 0 0.25rem 0;
  color: var(--text-color);
}

.feature-details p {
  margin: 0;
  font-size: 0.875rem;
  color: var(--text-color-secondary);
}

.plan-details {
  padding: 1rem;
  background-color: var(--surface-ground);
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.plan-subscriptions {
  background-color: var(--surface-card);
  padding: 1rem;
  border-radius: 4px;
}

.subscriptions-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.subscriptions-header h4 {
  margin: 0;
}

.field {
  margin-bottom: 1rem;
}

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

.confirmation-content {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.mr-3 {
  margin-right: 0.75rem;
}

:deep(.p-inputnumber),
:deep(.p-calendar),
:deep(.p-dropdown),
:deep(.p-multiselect) {
  width: 100%;
}

:deep(.p-badge) {
  font-size: 0.8rem;
  padding: 0.3rem 0.5rem;
}

@media (max-width: 600px) {
  .subscription-management-container, .header, .dashboard-card, .activity-log-container, .user-management-container, .club-management {
    padding: 0.5rem !important;
    margin-bottom: 0.5rem !important;
  }
  .dashboard-card {
    padding: 0.7rem !important;
    font-size: 0.95rem;
  }
  .header h2, .dashboard-card h3 {
    font-size: 1.1rem !important;
  }
  .features-grid, .plan-details {
    grid-template-columns: 1fr !important;
    flex-direction: column !important;
    gap: 0.7rem !important;
  }
  .p-datatable-wrapper {
    overflow-x: auto !important;
  }
  /* Dialog 팝업 중앙 정렬 개선 */
  :deep(.p-dialog) {
    align-items: flex-start !important;
    justify-content: center !important;
    padding-top: 2.5rem !important;
  }
  :deep(.p-dialog .p-dialog-content) {
    margin-top: 0 !important;
  }
}
</style>
