<template>
  <div class="mypage-container">
    <!-- 헤더 섹션 -->
    <div class="mypage-header">
      <div class="header-content">
        <div class="profile-section">
          <div class="profile-avatar">
            <div class="avatar-placeholder">
              <i class="mdi mdi-account"></i>
            </div>
          </div>
          <div class="profile-info">
            <h1 class="user-name">{{ useAtStore.auth.nickName || useAtStore.auth.companyName || '사용자' }}</h1>
            <p class="user-type">{{ memberType === 'INFLUENCER' ? '인플루언서' : memberType === 'VENDOR' ? '벤더사' : '브랜드사' }}</p>
          </div>
        </div>
      </div>
      <!-- 통계 요약 카드 -->
      <div class="stats-overview">
        <div class="stat-card">
          <div class="stat-icon orders">
            <i class="mdi mdi-cart"></i>
          </div>
          <div class="stat-info">
            <h3>{{ recentOrdersTotal }}</h3>
            <p>신규 주문</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon items">
            <i class="mdi mdi-package-variant"></i>
          </div>
          <div class="stat-info">
            <h3>{{ activeItemsCount }}</h3>
            <p>진행중인 공동구매</p>
          </div>
        </div>
        <!-- <div class="stat-card">
          <div class="stat-icon sales">
            <i class="mdi mdi-trending-up"></i>
          </div>
          <div class="stat-info">
            <h3>{{ totalSalesCount }}</h3>
            <p>총 주문 건수</p>
          </div>
        </div> -->
        <div class="stat-card">
          <div class="stat-icon influencers">
            <i class="mdi mdi-account-group"></i>
          </div>
          <div class="stat-info">
            <h3>{{ activeInfluencersCount }}</h3>
            <p>활성 인플루언서</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 대시보드 섹션 -->
    <div class="dashboard-section">
      <div class="dashboard-cards">
        <!-- 최근 주문 현황 카드 -->
        <div class="dashboard-card recent-orders">
          <div class="card-header">
            <h3>신규 주문 <span class="limit-badge">*최근 10건까지</span></h3>
            <i class="mdi mdi-cart-outline"></i>
          </div>
          <div class="card-content">
            <div class="order-list">
              <div v-if="recentOrders.length > 0">
                <div 
                  v-for="order in recentOrders" 
                  :key="order.SEQ" 
                  class="order-item recent-order"
                  @click="goToOrderDetail(order.ITEM_SEQ)"
                >
                  <div class="order-icon">
                    🛒
                  </div>
                  <div class="item-info">
                    <h4>{{ order.ITEM_NAME }}</h4>
                    <div class="order-meta">
                      <!-- <span class="order-number">#{{ order.ORDER_NUMB }}</span> -->
                      <span class="influencer-name">#{{ order.INF_NICK_NAME || order.INF_NAME }}</span>
                      <div class="order-date">{{ formatDateTime(order.CONTENT_REGDATE) }}</div>
                    </div>
                  </div>
                </div>
              </div>
              <div v-else class="no-orders">
                <i class="mdi mdi-cart-off"></i>
                <p>신규 주문이 없습니다</p>
              </div>
            </div>
            <div class="view-all">
              <v-btn variant="text" class="custom-btn btn-white" @click="goToOrders()">전체 보기</v-btn>
            </div>
          </div>
        </div>

        <!-- 진행중인 공동구매 카드 -->
        <div class="dashboard-card active-items">
          <div class="card-header">
            <h3>진행중인 공동구매<span class="limit-badge">*최근 5건까지</span></h3>
            <i class="mdi mdi-package-variant-closed"></i>
          </div>
          <div class="card-content">
            <div class="item-list">
              <div v-if="activeItems.length > 0">
                <div 
                  v-for="item in activeItems" 
                  :key="item.SEQ" 
                  class="item-card active-item"
                  @click="goToItemDetail(item.SEQ)"
                >
                  <div class="item-header">
                    <div class="item-icon">📦</div>
                  </div>
                  <div class="item-info">
                    <h4>{{ item.NAME }}</h4>
                    <div class="item-stats">
                      <span class="order-count">{{ formatDate(item.ORDER_START_DATE) }} ~ {{ formatDate(item.ORDER_END_DATE) }}</span>
                    </div>
                  </div>
                </div>
              </div>
              <div v-else class="no-items">
                <i class="mdi mdi-package-variant-closed-remove"></i>
                <p>진행중인 공동구매가 없습니다</p>
              </div>
            </div>
            <div class="view-all">
              <v-btn variant="text" class="custom-btn btn-white" @click="goToItems()">전체 보기</v-btn>
            </div>
          </div>
        </div>

        <!-- 인플루언서별 판매 통계 카드 -->
        <div class="dashboard-card influencer-stats">
          <div class="card-header">
            <h3>인플루언서별 주문 건수<span class="limit-badge">*상위 6명까지</span></h3>
            <i class="mdi mdi-account-star"></i>
          </div>
          <div class="card-content">
            <div class="influencer-list">
              <div v-if="influencerStats.length > 0" class="influencer-cards">
                <div 
                  v-for="(stat, index) in influencerStats" 
                  :key="stat.INF_SEQ" 
                  class="influencer-card"
                >
                  <div class="rank-badge">{{ index + 1 }}</div>
                  <div class="user-avatar">
                    🤝
                  </div>
                  <div class="influencer-info">
                    <h4>{{ stat.INF_NAME || '인플루언서' + stat.INF_SEQ }}</h4>
                    <div class="order-count white">
                      <span class="count">{{ stat.ORDER_COUNT }}</span>
                      <span class="label">건</span>
                    </div>
                  </div>
                </div>
              </div>
              <div v-else class="no-stats">
                <i class="mdi mdi-chart-line"></i>
                <p>인플루언서 정보가 없습니다.</p>
              </div>
              <div class="view-all">
                <v-btn variant="text" class="custom-btn btn-white" @click="goToContact()">전체 보기</v-btn>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
  /************************************************************************
|    레이아웃
************************************************************************/
  definePageMeta({
    layout: "default",
  });
  /************************************************************************
|   PROPS
 ************************************************************************/
  const props = defineProps({
    propsData: {
      type: Object,
      default: () => {},
    },
  });
  /************************************************************************
|    스토어
 ************************************************************************/
  const useDtStore = useDetailStore();
  const useAtStore = useAuthStore();
  /************************************************************************
|    전역
 ************************************************************************/
  const memberType = useAtStore.auth.memberType;
  const { $toast, $log, $dayjs, $eventBus } = useNuxtApp();
  const router = useRouter();
  const activeItemsCount = ref(0);
  const activeInfluencersCount = ref(0);
  const recentOrders = ref([]);
  const recentOrdersTotal = ref(0);
  const activeItems = ref([]);
  const influencerStats = ref([]);
  
  // 대시보드 관련 computed
  const completedInquiries = computed(() => {
    return csList.value.filter(item => item.STATUS === '1').length;
  });

  
  const totalSalesCount = computed(() => {
    return recentOrders.value.length;
  });

  // 문의 등록 팝업 관련
  const showInquiryModal = ref(false);
  const isSubmitting = ref(false);
  const inquiryForm = ref({
    category: '',
    title: '',
    content: '',
    attachments: []
  });
  const categoryOptions = ref([
    { title: '기능문의', value: 'D' },
    { title: '기타문의', value: 'E' }
  ]);

  /* eslint-disable */
  /* prettier-ignore */

  /************************************************************************
|    함수(METHODS)
************************************************************************/

  // 대시보드 데이터 로드 함수들
  const loadRecentOrders = async () => {
    try {
      const _req = {
        COMPANY_NUMBER: useAtStore.auth.companyNumber,
        MEMBER_TYPE: useAtStore.auth.memberType,
        MEMBER_SEQ: useAtStore.auth.seq,
        LIMIT: 10,
      };
      
      const response = await useAxios().post('/dashboard/recentOrders', _req);
      recentOrders.value = response.data.data || response.data; // 하위호환성
      recentOrdersTotal.value = response.data.total || 0;
    } catch (error) {
      console.error('최근 주문 로드 실패:', error);
    }
  };

  const loadActiveItems = async () => {
    try {
      const _req = {
        SHOW_YN: "Y",
        TYPE: "G",
        //INF_SEQ: useAtStore.auth.seq,
        MEMBER_TYPE: memberType,
        MEMBER_SEQ: useAtStore.auth.seq,
        STATUS: 0,
        COMPANY_NUMBER: useAtStore.auth.companyNumber,
        LIMIT: 5,
      };
      const response = await useAxios().post('/dashboard/activeItems', _req);
      activeItems.value = response.data.data || response.data; // 하위호환성
      activeItemsCount.value = response.data.total || activeItems.value.length;
    } catch (error) {
      console.error('진행중인 공동구매 로드 실패:', error);
    }
  };

  const loadInfluencerStats = async () => {
    try {
      const _req = {
        COMPANY_NUMBER: useAtStore.auth.companyNumber,
        MEMBER_TYPE: useAtStore.auth.memberType,
        MEMBER_SEQ: useAtStore.auth.seq,
        LIMIT: 6,
      };
      
      const response = await useAxios().post('/dashboard/influencerStats', _req);
      influencerStats.value = response.data.data || response.data; // 하위호환성
      activeInfluencersCount.value = response.data.total || 0;
    } catch (error) {
      //console.error('인플루언서 통계 로드 실패:', error);
    }
  };

  const loadDashboardData = async () => {
    await Promise.all([
      loadRecentOrders(),
      loadActiveItems(),
      loadInfluencerStats(),
    ]);
  };

  const goToContact = () => {
    router.push('/view/common/dashboard/contact');
  };
  
  const goToItems = () => {
    router.push('/view/common/item');
  };

  const goToOrders = () => {
    router.push('/view/common/item');
  };

  const goToOrderDetail = (itemSeq) => {
    useDtStore.boardInfo.seq = itemSeq;
    useDtStore.boardInfo.pageType = "D";
    router.push({
      path: "/view/common/item/detail",
      query: { itemId: itemSeq }
    });
  };

  const goToItemDetail = (itemSeq) => {
    useDtStore.boardInfo.seq = itemSeq;
    router.push({
      path: "/view/common/item/detail",
      query: { itemId: itemSeq }
    });
  };

  const formatDate = (dateStr) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}.${month}.${day}`;
  };

  const formatDateTime = (dateStr) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${year}.${month}.${day} ${hours}:${minutes}`;
  };

  const showComingSoon = () => {
    $eventBus.emit('OPEN_CONFIRM_POP_UP', {
      id: 'coming-soon',
      title: '안내',
      content: '준비중입니다.',
      yes: {
        text: '확인',
        isProc: false
      }
    });
  };

  /************************************************************************
|    WATCH
************************************************************************/
  onMounted(() => {
    loadDashboardData();
  });
</script>