<template>
  <div class="mypage-container">
    <!-- 프로필 섹션 -->
    <div class="profile-section">
      <div class="profile-card">
        <div class="profile-header">
          <div class="profile-avatar">
            {{ getMemberTypeName(userInfo.memberType) === "인플루언서" ? '❤️' : '💜' }}
          </div>
          <div class="profile-info">
            <h2>{{ userInfo.name }}</h2>
            <span class="member-type-badge">{{ getMemberTypeName(userInfo.memberType) }}</span>
          </div>
          <button 
            class="edit-btn" 
            @click="toggleEditMode"
            :class="{ active: isEditMode }"
          >
            {{ isEditMode ? '취소' : '수정' }}
          </button>
        </div>

        <!-- 정보 표시/수정 폼 -->
        <div class="profile-content">
          <div v-if="!isEditMode" class="info-display">
            <div class="info-row">
              <label>이름</label>
              <span>{{ userInfo.name }}</span>
            </div>
            <div class="info-row">
              <label>이메일</label>
              <span>{{ userInfo.email }}</span>
            </div>
            <div class="info-row" v-if="userInfo.memberType !== 'INFLUENCER'">
              <label>회사명</label>
              <span>{{ userInfo.companyName }}</span>
            </div>
            <div class="info-row">
              <label>전화번호</label>
              <span>{{ userInfo.phone || '미등록' }}</span>
            </div>
          </div>

          <div v-else class="info-edit">
            <div class="form-group">
              <label>이름 *</label>
              <input 
                type="text" 
                v-model="editForm.name"
                placeholder="이름을 입력하세요"
                class="form-input"
              />
            </div>
            <div class="form-group">
              <label>이메일 *</label>
              <input 
                type="email" 
                v-model="editForm.email"
                placeholder="이메일을 입력하세요"
                class="form-input"
              />
            </div>
            <div class="form-group" v-if="userInfo.memberType !== 'INFLUENCER'">
              <label>회사명</label>
              <input 
                type="text" 
                v-model="editForm.companyName"
                placeholder="회사명을 입력하세요"
                class="form-input"
              />
            </div>
            <div class="form-group">
              <label>전화번호</label>
              <input 
                type="tel" 
                v-model="editForm.phone"
                placeholder="전화번호를 입력하세요"
                class="form-input"
              />
            </div>
            
            <div class="form-actions">
              <button 
                class="btn-save" 
                @click="saveProfile"
                :disabled="isSaving"
              >
                {{ isSaving ? '저장중...' : '저장' }}
              </button>
              <button 
                class="btn-cancel" 
                @click="cancelEdit"
              >
                취소
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 추가 정보 섹션 -->
    <div class="additional-info">
      <div class="info-card">
        <h3>계정 정보</h3>
        <div class="info-grid">
          <div class="info-item">
            <span class="info-label">회원 타입</span>
            <span class="info-value">{{ getMemberTypeName(userInfo.memberType) }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">계정 ID</span>
            <span class="info-value">{{ userInfo.id }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">가입일</span>
            <span class="info-value">{{ formatDate(userInfo.regDate) || '정보 없음' }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import "@vuepic/vue-datepicker/dist/main.css";
  /************************************************************************
|    레이아웃
************************************************************************/
  definePageMeta({
    layout: "default",
  });
  /************************************************************************
|   PROPS
 ************************************************************************/
  const props = defineProps({
    propsData: {
      type: Object,
      default: () => {},
    },
  });
  /************************************************************************
|    스토어
 ************************************************************************/
  const useDtStore = useDetailStore();
  const useAtStore = useAuthStore();
  /************************************************************************
|    전역
 ************************************************************************/
  const { $toast, $log, $dayjs, $eventBus } = useNuxtApp();
  const router = useRouter();
  
  // 사용자 정보
  const userInfo = ref({
    id: useAtStore.auth.id,
    name: useAtStore.auth.name,
    email: useAtStore.auth.email,
    companyName: useAtStore.auth.companyName,
    companyNumber: useAtStore.auth.companyNumber,
    phone: useAtStore.auth.phone,
    memberType: useAtStore.auth.memberType,
    regDate: null
  });

  // 편집 모드
  const isEditMode = ref(false);
  const isSaving = ref(false);
  const editForm = ref({
    name: '',
    email: '',
    companyName: '',
    phone: ''
  });

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

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

  // 회원 타입 이름 반환
  const getMemberTypeName = (type) => {
    switch(type) {
      case 'INFLUENCER': return '인플루언서';
      case 'VENDOR': return '벤더사';
      case 'BRAND': return '브랜드사';
      default: return '사용자';
    }
  };

  // 편집 모드 토글
  const toggleEditMode = () => {
    if (isEditMode.value) {
      // 편집 취소
      isEditMode.value = false;
    } else {
      // 편집 시작 - 현재 값으로 폼 초기화
      editForm.value = {
        name: userInfo.value.name,
        email: userInfo.value.email,
        companyName: userInfo.value.companyName,
        phone: userInfo.value.phone
      };
      isEditMode.value = true;
    }
  };

  // 편집 취소
  const cancelEdit = () => {
    isEditMode.value = false;
  };

  // 프로필 저장
  const saveProfile = async () => {
    // 유효성 검사
    if (!editForm.value.name.trim()) {
      $toast.error('이름을 입력해주세요.');
      return;
    }
    if (!editForm.value.email.trim()) {
      $toast.error('이메일을 입력해주세요.');
      return;
    }

    isSaving.value = true;
    
    try {
      const updateData = {
        USER_SEQ: useAtStore.auth.seq,
        NAME: editForm.value.name,
        EMAIL: editForm.value.email,
        PHONE: editForm.value.phone
      };

      // 회사 정보는 벤더사, 브랜드사만
      if (userInfo.value.memberType !== 'INFLUENCER') {
        updateData.COMPANY_NAME = editForm.value.companyName;
      }

      // TODO: 실제 API 호출 (현재는 임시로 로컬 업데이트)
      // const response = await useAxios().post('/user/update', updateData);
      
      // 임시로 로컬 데이터 업데이트
      userInfo.value.name = editForm.value.name;
      userInfo.value.email = editForm.value.email;
      userInfo.value.phone = editForm.value.phone;
      if (userInfo.value.memberType !== 'INFLUENCER') {
        userInfo.value.companyName = editForm.value.companyName;
      }

      // 스토어도 업데이트
      useAtStore.auth.name = editForm.value.name;
      useAtStore.auth.email = editForm.value.email;
      useAtStore.auth.phone = editForm.value.phone;
      if (userInfo.value.memberType !== 'INFLUENCER') {
        useAtStore.auth.companyName = editForm.value.companyName;
      }

      $toast.success('프로필이 성공적으로 수정되었습니다.');
      isEditMode.value = false;
      
    } catch (error) {
      console.error('프로필 수정 실패:', error);
      $toast.error('프로필 수정에 실패했습니다.');
    } finally {
      isSaving.value = false;
    }
  };

  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}`;
  };

  /************************************************************************
|    WATCH
************************************************************************/
  // 사용자 상세 정보 로드
  const fnDetail = () => {
    let req = {
      MEMBER_TYPE: useAtStore.auth.memberType, 
      MEMBER_SEQ: useAtStore.auth.seq
    }

    console.warn(req)

    useAxios()
      .post(`/mypage/detail`, req)
      .then((res) => {
        console.error(res)
        userInfo.value = {
          id: userData.ID,
          name: userData.NAME,
          email: userData.EMAIL,
          companyName: userData.COMPANY_NAME,
          companyNumber: userData.COMPANY_NUMBER,
          phone: userData.PHONE,
          memberType: userData.MEMBER_TYPE,
          nickName: userData.NICK_NAME,
          introduction: userData.INTRODUCTION,
          regDate: userData.REGDATE
        };
    })
  };

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

<style scoped>
.mypage-container {
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  margin-bottom: 32px;
  text-align: center;
}

.page-header h1 {
  font-size: 2.5rem;
  color: #1a237e;
  margin-bottom: 8px;
}

.page-header p {
  color: #666;
  font-size: 1.1rem;
}

.profile-section {
  margin-bottom: 32px;
}

.profile-card {
  background: white;
  border-radius: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.profile-header {
  display: flex;
  align-items: center;
  padding: 32px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.profile-avatar {
  font-size: 3rem;
  margin-right: 24px;
  background: rgba(255, 255, 255, 0.2);
  width: 96px;
  height: 96px;
  overflow: hidden;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.profile-info {
  flex: 1;
}

.profile-info h2 {
  margin-bottom: 15px;
  font-size: 1.8rem;
}

.member-type-badge {
  background: rgba(255, 255, 255, 0.2);
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 0.9rem;
}

.edit-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 2px solid rgba(255, 255, 255, 0.3);
  color: white;
  padding: 12px 24px;
  border-radius: 25px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
}

.edit-btn:hover, .edit-btn.active {
  background: white;
  color: #667eea;
}

.profile-content {
  padding: 32px;
}

/* 정보 표시 스타일 */
.info-display .info-row {
  display: flex;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-display .info-row:last-child {
  border-bottom: none;
}

.info-display label {
  width: 120px;
  font-weight: 600;
  color: #333;
}

.info-display span {
  flex: 1;
  color: #666;
}

/* 편집 폼 스타일 */
.form-group {
  margin-bottom: 24px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #333;
}

.form-input {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 1rem;
  transition: border-color 0.3s ease;
}

.form-input:focus {
  outline: none;
  border-color: #667eea;
}

.form-actions {
  display: flex;
  gap: 12px;
  margin-top: 32px;
}

.btn-save {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
}

.btn-save:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.btn-save:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-cancel {
  background: #f5f5f5;
  color: #666;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
}

.btn-cancel:hover {
  background: #e0e0e0;
}

/* 추가 정보 섹션 */
.additional-info {
  margin-top: 32px;
}

.info-card {
  background: white;
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.info-card h3 {
  margin: 0 0 24px 0;
  color: #1a237e;
  font-size: 1.3rem;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 24px;
}

.info-item {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 12px;
}

.info-label {
  display: block;
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 15px;
}

.info-value {
  font-weight: 600;
  color: #333;
  font-size: 1rem;
}
</style>