<template>
  <div>
    <div class="inner--headers">
      <h2>{{ pageId }}</h2>
      <div class="bread--crumbs--wrap">
        <span>홈</span>
        <span @click="goBack" class="breadcrumb-link">벤더사 관리</span>
        <span>{{ currentVendor?.name || "벤더사 상세" }}</span>
      </div>
    </div>

    <!-- 로딩 상태 -->
    <div v-if="isLoading" class="loading-wrap">
      <v-progress-circular indeterminate color="primary" size="64"></v-progress-circular>
      <p>벤더사 정보를 불러오고 있습니다...</p>
    </div>

    <!-- 에러 상태 -->
    <div v-else-if="errorMessage" class="error-wrap">
      <v-alert type="error" dismissible @click:close="vendorsStore.clearError()">
        {{ errorMessage }}
      </v-alert>
      <v-btn @click="goBack" class="custom-btn btn-blue">목록으로 돌아가기</v-btn>
    </div>

    <!-- 벤더사 상세 정보 -->
    <div v-else-if="currentVendor" class="vendor-detail-wrap">
      <!-- 벤더사 기본 정보 -->
      <v-card class="vendor-header-card" elevation="2">
        <v-card-text>
          <div class="vendor-header">
            <div class="vendor-logo-section">
              <v-avatar size="80" class="vendor-logo-large">
                <v-img
                  v-if="currentVendor.logo"
                  :src="currentVendor.logo"
                  :alt="currentVendor.name + ' 로고'"
                ></v-img>
                <div v-else class="no-logo-large">{{ currentVendor.name.charAt(0) }}</div>
              </v-avatar>
            </div>
            <div class="vendor-info-section">
              <h1 class="vendor-name">{{ currentVendor.name }}</h1>
              <div class="vendor-meta">
                <v-chip
                  :color="getCategoryColor(currentVendor.category)"
                  size="large"
                  variant="outlined"
                  class="mr-2"
                >
                  {{ getCategoryName(currentVendor.category) }}
                </v-chip>
                <v-chip
                  :color="currentVendor.status === 'ACTIVE' ? 'success' : 'error'"
                  size="large"
                >
                  {{ currentVendor.status === "ACTIVE" ? "활성" : "비활성" }}
                </v-chip>
              </div>
              <p v-if="currentVendor.description" class="vendor-description">
                {{ currentVendor.description }}
              </p>
            </div>
            <div class="vendor-actions">
              <v-btn
                v-if="currentVendor.website"
                :href="currentVendor.website"
                target="_blank"
                class="custom-btn btn-white mr-2"
                prepend-icon="mdi-web"
              >
                웹사이트
              </v-btn>
              <v-btn
                @click="goBack"
                class="custom-btn btn-blue"
                prepend-icon="mdi-arrow-left"
              >
                목록으로
              </v-btn>
            </div>
          </div>
        </v-card-text>
      </v-card>

      <!-- 상세 정보 탭 -->
      <v-card class="detail-tabs-card" elevation="2">
        <v-tabs v-model="activeTab" class="custom-tabs">
          <v-tab value="info">기업 정보</v-tab>
          <v-tab value="contact">연락처</v-tab>
          <v-tab value="products">제품 정보</v-tab>
          <v-tab value="partnership">파트너십</v-tab>
        </v-tabs>

        <v-card-text>
          <v-tabs-window v-model="activeTab">
            <!-- 기업 정보 탭 -->
            <v-tabs-window-item value="info">
              <div class="info-section">
                <v-row>
                  <v-col cols="12" md="6">
                    <div class="info-item">
                      <h3>사업자등록번호</h3>
                      <p>{{ currentVendor.businessNumber || "-" }}</p>
                    </div>
                  </v-col>
                  <v-col cols="12" md="6">
                    <div class="info-item">
                      <h3>설립일</h3>
                      <p>{{ formatDate(currentVendor.establishedDate) || "-" }}</p>
                    </div>
                  </v-col>
                  <v-col cols="12" md="6">
                    <div class="info-item">
                      <h3>직원 수</h3>
                      <p>
                        {{
                          currentVendor.employeeCount
                            ? currentVendor.employeeCount + "명"
                            : "-"
                        }}
                      </p>
                    </div>
                  </v-col>
                  <v-col cols="12" md="6">
                    <div class="info-item">
                      <h3>연매출</h3>
                      <p>{{ formatCurrency(currentVendor.annualRevenue) || "-" }}</p>
                    </div>
                  </v-col>
                  <v-col cols="12">
                    <div class="info-item">
                      <h3>사업 분야</h3>
                      <div class="business-areas">
                        <v-chip
                          v-for="area in currentVendor.businessAreas || []"
                          :key="area"
                          size="small"
                          variant="outlined"
                          class="mr-2 mb-2"
                        >
                          {{ area }}
                        </v-chip>
                      </div>
                    </div>
                  </v-col>
                </v-row>
              </div>
            </v-tabs-window-item>

            <!-- 연락처 탭 -->
            <v-tabs-window-item value="contact">
              <div class="contact-section">
                <v-row>
                  <v-col cols="12" md="6">
                    <v-card variant="outlined" class="contact-card">
                      <v-card-title>
                        <v-icon class="mr-2">mdi-account</v-icon>
                        주요 담당자
                      </v-card-title>
                      <v-card-text>
                        <div class="contact-item">
                          <strong>이름:</strong> {{ currentVendor.contactName || "-" }}
                        </div>
                        <div class="contact-item">
                          <strong>직책:</strong>
                          {{ currentVendor.contactPosition || "-" }}
                        </div>
                        <div class="contact-item">
                          <strong>전화:</strong>
                          <a
                            v-if="currentVendor.contactPhone"
                            :href="`tel:${currentVendor.contactPhone}`"
                          >
                            {{ currentVendor.contactPhone }}
                          </a>
                          <span v-else>-</span>
                        </div>
                        <div class="contact-item">
                          <strong>이메일:</strong>
                          <a
                            v-if="currentVendor.contactEmail"
                            :href="`mailto:${currentVendor.contactEmail}`"
                          >
                            {{ currentVendor.contactEmail }}
                          </a>
                          <span v-else>-</span>
                        </div>
                      </v-card-text>
                    </v-card>
                  </v-col>
                  <v-col cols="12" md="6">
                    <v-card variant="outlined" class="contact-card">
                      <v-card-title>
                        <v-icon class="mr-2">mdi-map-marker</v-icon>
                        주소 정보
                      </v-card-title>
                      <v-card-text>
                        <div class="contact-item">
                          <strong>주소:</strong>
                          <p>{{ currentVendor.address || "-" }}</p>
                        </div>
                        <div class="contact-item">
                          <strong>상세주소:</strong>
                          <p>{{ currentVendor.detailAddress || "-" }}</p>
                        </div>
                        <div class="contact-item">
                          <strong>우편번호:</strong> {{ currentVendor.zipCode || "-" }}
                        </div>
                      </v-card-text>
                    </v-card>
                  </v-col>
                </v-row>
              </div>
            </v-tabs-window-item>

            <!-- 제품 정보 탭 -->
            <v-tabs-window-item value="products">
              <div class="products-section">
                <div class="section-header">
                  <h3>주요 제품/서비스</h3>
                </div>
                <v-row v-if="currentVendor.products && currentVendor.products.length > 0">
                  <v-col
                    v-for="product in currentVendor.products"
                    :key="product.id"
                    cols="12"
                    md="6"
                    lg="4"
                  >
                    <v-card class="product-card" variant="outlined">
                      <v-img
                        v-if="product.image"
                        :src="product.image"
                        height="150"
                        cover
                      ></v-img>
                      <v-card-title>{{ product.name }}</v-card-title>
                      <v-card-text>
                        <p>{{ product.description }}</p>
                        <div class="product-price" v-if="product.price">
                          {{ formatCurrency(product.price) }}
                        </div>
                      </v-card-text>
                    </v-card>
                  </v-col>
                </v-row>
                <div v-else class="no-data">
                  <v-icon size="48" color="grey-lighten-1">mdi-package-variant</v-icon>
                  <p>등록된 제품 정보가 없습니다</p>
                </div>
              </div>
            </v-tabs-window-item>

            <!-- 파트너십 탭 -->
            <v-tabs-window-item value="partnership">
              <div class="partnership-section">
                <v-row>
                  <v-col cols="12" md="6">
                    <div class="info-item">
                      <h3>파트너십 등급</h3>
                      <v-chip
                        :color="getPartnershipColor(currentVendor.partnershipLevel)"
                        size="large"
                      >
                        {{ getPartnershipName(currentVendor.partnershipLevel) }}
                      </v-chip>
                    </div>
                  </v-col>
                  <v-col cols="12" md="6">
                    <div class="info-item">
                      <h3>협력 시작일</h3>
                      <p>{{ formatDate(currentVendor.partnershipStartDate) || "-" }}</p>
                    </div>
                  </v-col>
                  <v-col cols="12" md="6">
                    <div class="info-item">
                      <h3>협력 프로젝트 수</h3>
                      <p>{{ currentVendor.projectCount || 0 }}개</p>
                    </div>
                  </v-col>
                  <v-col cols="12" md="6">
                    <div class="info-item">
                      <h3>평점</h3>
                      <div class="rating">
                        <v-rating
                          v-model="currentVendor.rating"
                          readonly
                          size="small"
                          density="compact"
                        ></v-rating>
                        <span class="rating-text">{{ currentVendor.rating || 0 }}/5</span>
                      </div>
                    </div>
                  </v-col>
                  <v-col cols="12">
                    <div class="info-item">
                      <h3>특이사항</h3>
                      <p>{{ currentVendor.notes || "특이사항이 없습니다." }}</p>
                    </div>
                  </v-col>
                </v-row>
              </div>
            </v-tabs-window-item>
          </v-tabs-window>
        </v-card-text>
      </v-card>
    </div>

    <!-- 데이터가 없을 때 -->
    <div v-else class="no-data-wrap">
      <div class="no-data">
        <v-icon size="64" color="grey-lighten-1">mdi-store-alert</v-icon>
        <h3>벤더사 정보를 찾을 수 없습니다</h3>
        <p>요청하신 벤더사가 존재하지 않거나 삭제되었을 수 있습니다</p>
        <v-btn @click="goBack" class="custom-btn btn-blue">목록으로 돌아가기</v-btn>
      </div>
    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted, computed } from "vue";
  import { useRoute, useRouter } from "vue-router";
  import { useVendorsStore } from "@/stores/vendors";

  /************************************************************************
|    레이아웃
************************************************************************/
  definePageMeta({
    layout: "default",
  });

  /************************************************************************
|    스토어, 라우터, 라우트
************************************************************************/
  const vendorsStore = useVendorsStore();
  const router = useRouter();
  const route = useRoute();

  /************************************************************************
|    반응형 데이터
************************************************************************/
  const pageId = ref("벤더사 상세");
  const activeTab = ref("info");

  /************************************************************************
|    computed - .value 제거!
************************************************************************/
  const currentVendor = computed(() => vendorsStore.getCurrentVendor);
  const isLoading = computed(() => vendorsStore.getLoading);
  const errorMessage = computed(() => vendorsStore.getError);

  /************************************************************************
|    메서드
************************************************************************/
  const goBack = () => {
    router.push("/view/vendor/vendors");
  };

  const getCategoryColor = (category) => {
    const colors = {
      FASHION_BEAUTY: "pink",
      FOOD_HEALTH: "green",
      LIFESTYLE: "blue",
      TECH_ELECTRONICS: "purple",
      SPORTS_LEISURE: "orange",
      CULTURE_ENTERTAINMENT: "red",
    };
    return colors[category] || "grey";
  };

  const getCategoryName = (category) => {
    const names = {
      FASHION_BEAUTY: "패션·뷰티",
      FOOD_HEALTH: "식품·건강",
      LIFESTYLE: "라이프스타일",
      TECH_ELECTRONICS: "테크·가전",
      SPORTS_LEISURE: "스포츠·레저",
      CULTURE_ENTERTAINMENT: "문화·엔터테인먼트",
    };
    return names[category] || category;
  };

  const getPartnershipColor = (level) => {
    const colors = {
      PLATINUM: "purple",
      GOLD: "amber",
      SILVER: "grey",
      BRONZE: "brown",
      BASIC: "blue-grey",
    };
    return colors[level] || "grey";
  };

  const getPartnershipName = (level) => {
    const names = {
      PLATINUM: "플래티넘",
      GOLD: "골드",
      SILVER: "실버",
      BRONZE: "브론즈",
      BASIC: "베이직",
    };
    return names[level] || level;
  };

  const formatDate = (dateString) => {
    if (!dateString) return null;
    return new Date(dateString).toLocaleDateString("ko-KR");
  };

  const formatCurrency = (amount) => {
    if (!amount) return null;
    return new Intl.NumberFormat("ko-KR", {
      style: "currency",
      currency: "KRW",
    }).format(amount);
  };

  /************************************************************************
|    라이프사이클
************************************************************************/
  onMounted(async () => {
    const vendorId = route.params.id;
    if (vendorId) {
      try {
        await vendorsStore.getVendorById(vendorId);
      } catch (error) {
        console.error("벤더사 정보 로드 실패:", error);
      }
    }
  });
</script>

<style scoped>
  .vendor-detail-wrap {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .vendor-header-card {
    margin-bottom: 20px;
  }

  .vendor-header {
    display: flex;
    align-items: flex-start;
    gap: 20px;
  }

  .vendor-logo-section {
    flex-shrink: 0;
  }

  .vendor-logo-large {
    border: 1px solid #e0e0e0;
  }

  .no-logo-large {
    background: #f5f5f5;
    color: #666;
    font-weight: bold;
    font-size: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
  }

  .vendor-info-section {
    flex: 1;
  }

  .vendor-name {
    font-size: 28px;
    font-weight: bold;
    margin-bottom: 12px;
  }

  .vendor-meta {
    margin-bottom: 16px;
  }

  .vendor-description {
    color: #666;
    line-height: 1.6;
    margin: 0;
  }

  .vendor-actions {
    flex-shrink: 0;
  }

  .breadcrumb-link {
    cursor: pointer;
    color: #1976d2;
  }

  .breadcrumb-link:hover {
    text-decoration: underline;
  }

  .detail-tabs-card {
    margin-top: 20px;
  }

  .info-section,
  .contact-section,
  .products-section,
  .partnership-section {
    padding: 20px 0;
  }

  .info-item {
    margin-bottom: 24px;
  }

  .info-item h3 {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 8px;
    color: #333;
  }

  .info-item p {
    font-size: 14px;
    color: #666;
    margin: 0;
  }

  .contact-card {
    height: 100%;
  }

  .contact-item {
    margin-bottom: 12px;
  }

  .contact-item strong {
    display: inline-block;
    width: 80px;
    color: #333;
  }

  .contact-item a {
    color: #1976d2;
    text-decoration: none;
  }

  .contact-item a:hover {
    text-decoration: underline;
  }

  .section-header {
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e0e0e0;
  }

  .section-header h3 {
    font-size: 18px;
    font-weight: 600;
    margin: 0;
  }

  .product-card {
    height: 100%;
  }

  .product-price {
    font-weight: bold;
    color: #1976d2;
    margin-top: 8px;
  }

  .rating {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .rating-text {
    font-size: 14px;
    color: #666;
  }

  .business-areas {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }

  .loading-wrap,
  .error-wrap,
  .no-data-wrap {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 20px;
  }

  .no-data {
    text-align: center;
  }

  .no-data h3 {
    margin: 16px 0 8px;
    color: #666;
  }

  .no-data p {
    color: #999;
    margin-bottom: 20px;
  }

  @media (max-width: 768px) {
    .vendor-header {
      flex-direction: column;
    }

    .vendor-actions {
      width: 100%;
    }
  }
</style>
