<template>
  <div>
    <div class="inner--headers">
      <h2>{{ pageId }}</h2>
      <div class="bread--crumbs--wrap">
        <span>홈</span>
        <span>{{ pageId }}</span>
      </div>
    </div>

    <div class="data--list--wrap">
      <div class="item--list--wrap">
        <div class="cs--list--wrap">
          <div class="cs--header">
            <h3>인플루언서별 주문 건수</h3>
          </div>
          
          <!-- 검색 영역 -->
          <div class="cs--search-area">
            <div class="search-controls">
              <div class="search-filter">
                <v-select
                  v-model="filter"
                  :items="filderArr"
                  variant="outlined"
                  density="compact"
                  hide-details
                ></v-select>
              </div>
              <div class="search-input">
                <v-text-field
                  v-model="searchModel"
                  placeholder="검색어를 입력하세요"
                  variant="outlined"
                  density="compact"
                  hide-details
                  prepend-inner-icon="mdi-magnify"
                  @keyup.enter="fnSearch(searchModel, filter)"
                ></v-text-field>
              </div>
              <div class="search-actions">
                <v-btn
                  class="custom-btn mini btn--pp"
                  color="primary"
                  @click="fnSearch(searchModel, filter)"
                >
                  검색
                </v-btn>
                <v-btn
                  class="custom-btn mini btn-white"
                  color="secondary"
                  variant="outlined"
                  @click="resetSearch"
                >
                  초기화
                </v-btn>
              </div>
            </div>
          </div>
          <div class="cs--list card" v-if="influencerStats.length > 0">
            <div v-for="(stat, index) in paginatedInfluencers" :key="stat.INF_SEQ" class="influencer-profile-card" @click="toItemDetail(stat.INF_SEQ)">
              <div class="profile-header">
                <div class="profile-rank">{{ (currentPage - 1) * itemsPerPage + index + 1 }}</div>
                <div class="profile-avatar">
                  <div class="avatar-emoji">❤️</div>
                </div>
                <div class="profile-info">
                  <div class="profile-name">
                    <span class="nickname">{{ stat.INF_NAME || '닉네임 없음' }}</span>
                    <span class="real-name">{{ stat.INF_REAL_NAME || '이름 없음' }}</span>
                  </div>
                  <div class="profile-contact">
                    <span class="phone">{{ stat.PHONE || '연락처 없음' }}</span>
                  </div>
                </div>
              </div>
              <div class="profile-stats">
                <div class="stat-item">
                  <span class="stat-label">총 주문 건수</span>
                  <span class="stat-value">{{ stat.ORDER_COUNT }}건</span>
                </div>
              </div>
            </div>
          </div>
          <div class="cs--list" v-else>
            <div class="no-data">
              <h4>인플루언서 데이터가 없습니다</h4>
            </div>
          </div>
        </div>
        <div class="item--pagination" v-if="influencerStats.length > 0">
          <v-pagination
            v-model="currentPage"
            :length="Math.ceil(influencerStats.length / itemsPerPage)"
          ></v-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import "@vuepic/vue-datepicker/dist/main.css";
import dayjs from 'dayjs';
  /************************************************************************
|    레이아웃
************************************************************************/
  definePageMeta({
    layout: "default",
  });
  /************************************************************************
|   PROPS
 ************************************************************************/
  const props = defineProps({
    propsData: {
      type: Object,
      default: () => {},
    },
  });
  /************************************************************************
|    스토어
 ************************************************************************/
  const useDtStore = useDetailStore();
  const useAtStore = useAuthStore();
  /************************************************************************
|    전역
 ************************************************************************/
  const itemType = ref("G");
  const memberType = useAtStore.auth.memberType;
  const searchModel = ref("");
  const selectedRange = ref('all');
  const searchStartDate = ref("");
  const searchEndDate = ref("");
  const dateOptions = [
    { label: '오늘', value: 'today' },
    { label: '7일', value: '7d' },
    { label: '1개월', value: '1m' },
    { label: '3개월', value: '3m' },
    { label: '전체', value: 'all' },
  ]
  const datePickerFormat = "yyyy-MM-dd";
  const filter = ref("");
  const filderArr = ref([
    { title: "전체", value: "" },
    { title: "인플루언서명", value: "name" },
  ]);
  const { $toast, $log, $dayjs, $eventBus } = useNuxtApp();
  const router = useRouter();
  const pageId = computed(() => {
    return '인플루언서 정보';
    //return memberType === 'INFLUENCER' ? '제품 관리 (파트너십)' : '제품 관리 (자사)';
  });
  const itemList = ref([]);
  const allItemList = ref([]); // 전체 데이터 저장용
  const itemsPerPage = 9;
  const currentPage = ref(1);
  const influencerStats = ref([]);
  const allInfluencerStats = ref([]); // 전체 인플루언서 통계 저장용

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

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

  const paginatedItems = computed(() => {
    const start = (currentPage.value - 1) * itemsPerPage;
    return itemList.value.slice(start, start + itemsPerPage);
  });

  const paginatedInfluencers = computed(() => {
    const start = (currentPage.value - 1) * itemsPerPage;
    return influencerStats.value.slice(start, start + itemsPerPage);
  });

  const toItemDetail = (__EVENT) => {
    router.push({
      path: "/view/common/dashboard/detail",
    });
    useDtStore.boardInfo.seq = __EVENT;
  };

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

  const fnSearch = (__KEYWORD, __FILTER) => {
    let filteredStats = [...allInfluencerStats.value];
    
    // 키워드 검색
    if (__KEYWORD && __KEYWORD.trim() !== '') {
      const keyword = __KEYWORD.toLowerCase();
      filteredStats = filteredStats.filter(stat => {
        if (__FILTER === 'name') {
          return stat.INF_NAME && stat.INF_NAME.toLowerCase().includes(keyword);
        } else {
          // 전체 검색 (인플루언서 이름)
          return stat.INF_NAME && stat.INF_NAME.toLowerCase().includes(keyword);
        }
      });
    }
    
    influencerStats.value = filteredStats;
    currentPage.value = 1; // 검색 시 첫 페이지로 이동
  };

  // 검색 초기화
  const resetSearch = () => {
    searchModel.value = '';
    searchStartDate.value = null;
    searchEndDate.value = null;
    selectedRange.value = '';
    influencerStats.value = [...allInfluencerStats.value];
    currentPage.value = 1;
  };


  const goToDeliveryDetail = (item) => {
    // 제품 정보를 스토어에 저장
    useDtStore.boardInfo.seq = item.SEQ;
    useDtStore.boardInfo.pageType = "D";
    useDtStore.boardInfo.itemType = itemType.value;
    
    // 배송 관리 페이지로 이동
    router.push({
      path: "/view/common/deli/detail",
      query: {
        itemId: item.SEQ,
        itemName: item.NAME,
        price1: item.PRICE1,
        price2: item.PRICE2 || item.PRICE1,
        thumbFile: item.THUMB_FILE || ''
      }
    });
  };

  /************************************************************************
|    WATCH
************************************************************************/

  onMounted(() => {
    loadInfluencerStats();

    // 날짜 초기화
    const today = dayjs();
    searchEndDate.value = today.format('YYYY-MM-DD');
  });
</script>

<style scoped>
.influencer-profile-card {
  background: linear-gradient(135deg, #ffffff 0%, #f8f9ff 100%);
  border: 2px solid transparent;
  background-clip: padding-box;
  border-radius: 20px;
  padding: 24px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  width: calc((100% - 2rem) / 3);
  border: 1px solid #eee;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.influencer-profile-card:hover {
  transform: translateY(-4px) scale(1.01);
}

.profile-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.profile-rank {
  width: 36px;
  height: 36px;
  border-radius: 12px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 14px;
  margin-right: 16px;
  flex-shrink: 0;
  position: relative;
}

.profile-avatar {
  margin-right: 16px;
  flex-shrink: 0;
}

.avatar-emoji {
  width: 56px;
  height: 56px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  animation: bounce 3s infinite;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
  border-radius: 50%;
}

@keyframes bounce {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-3px);
  }
}

.profile-name {
  display: flex;
  flex-direction: column;
  gap: 4px;
  margin-bottom: 8px;
}

.nickname {
  font-size: 18px;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.real-name {
  font-size: 14px;
  color: #94a3b8;
  font-weight: 500;
}

.profile-contact {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.user-id, .phone {
  font-size: 13px;
  color: #475569;
  padding: 6px 12px;
  border-radius: 20px;
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.2s ease;
}

.profile-stats {
  border-top: 2px dashed #e2e8f0;
  padding-top: 16px;
  margin-top: 16px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.no-data {
  text-align: center;
  padding: 40px;
  color: #6b7280;
}

.no-data h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}
</style>