<template>
  <div>
    <AppHeader />
    
    <div class="container py-4">
    <h2 class="mb-4">👤 마이페이지</h2>
    
    <!-- 내 정보 -->
    <div class="card mb-4">
      <div class="card-header d-flex justify-content-between align-items-center">
        <strong>내 정보</strong>
        <button v-if="!isEditing" class="btn btn-sm btn-outline-primary" @click="startEdit">
          수정
        </button>
      </div>
      <div class="card-body">
        <div v-if="isLoading" class="text-center py-4">
          <span class="spinner-border spinner-border-sm me-2"></span>로딩 중...
        </div>
        <div v-else>
          <!-- 보기 모드 -->
          <div v-if="!isEditing">
            <div class="row mb-2">
              <div class="col-3 text-muted">이름</div>
              <div class="col-9"><strong>{{ userInfo.employeeName }}</strong></div>
            </div>
            <div class="row mb-2">
              <div class="col-3 text-muted">이메일</div>
              <div class="col-9">{{ userInfo.employeeEmail }}</div>
            </div>
            <div class="row mb-2">
              <div class="col-3 text-muted">소속사</div>
              <div class="col-9">{{ userInfo.company || '-' }}</div>
            </div>
            <div class="row mb-2">
              <div class="col-3 text-muted">직급</div>
              <div class="col-9">{{ userInfo.employeePosition || '-' }}</div>
            </div>
            <div class="row mb-2">
              <div class="col-3 text-muted">연락처</div>
              <div class="col-9">{{ userInfo.employeePhone || '-' }}</div>
            </div>
            <div class="row mb-2">
              <div class="col-3 text-muted">입사일</div>
              <div class="col-9">{{ userInfo.joinDate ? userInfo.joinDate.split('T')[0] : '-' }}</div>
            </div>
            <hr class="my-2" />
            <div class="row mb-2">
              <div class="col-3 text-muted small">최초입력</div>
              <div class="col-9 small text-muted">
                {{ formatDateTime(userInfo.createdAt) }}
                <code v-if="userInfo.createdIp" class="ms-2">{{ userInfo.createdIp }}</code>
              </div>
            </div>
            <div class="row mb-2">
              <div class="col-3 text-muted small">최종수정</div>
              <div class="col-9 small text-muted">
                {{ formatDateTime(userInfo.updatedAt) }}
                <code v-if="userInfo.updatedIp" class="ms-2">{{ userInfo.updatedIp }}</code>
              </div>
            </div>
          </div>
          
          <!-- 수정 모드 -->
          <form v-else @submit.prevent="saveProfile">
            <div class="row mb-3">
              <label class="col-3 col-form-label">이름</label>
              <div class="col-9">
                <input type="text" class="form-control" v-model="editForm.employeeName" required />
              </div>
            </div>
            <div class="row mb-3">
              <label class="col-3 col-form-label">이메일</label>
              <div class="col-9">
                <input type="email" class="form-control" :value="userInfo.employeeEmail" disabled />
                <small class="text-muted">이메일은 변경할 수 없습니다.</small>
              </div>
            </div>
            <div class="row mb-3">
              <label class="col-3 col-form-label">소속사</label>
              <div class="col-9">
                <select class="form-select" v-model="editForm.company">
                  <option value="(주)터보소프트">(주)터보소프트</option>
                  <option value="(주)코쿤">(주)코쿤</option>
                  <option value="(주)오솔정보기술">(주)오솔정보기술</option>
                </select>
              </div>
            </div>
            <div class="row mb-3">
              <label class="col-3 col-form-label">직급</label>
              <div class="col-9">
                <select class="form-select" v-model="editForm.employeePosition">
                  <option value="">선택</option>
                  <optgroup label="일반">
                    <option value="인턴">인턴</option>
                    <option value="사원">사원</option>
                    <option value="주임">주임</option>
                    <option value="대리">대리</option>
                    <option value="과장">과장</option>
                    <option value="차장">차장</option>
                    <option value="부장">부장</option>
                  </optgroup>
                  <optgroup label="연구소">
                    <option value="연구원">연구원</option>
                    <option value="주임연구원">주임연구원</option>
                    <option value="선임연구원">선임연구원</option>
                    <option value="책임연구원">책임연구원</option>
                    <option value="수석연구원">수석연구원</option>
                    <option value="연구소장">연구소장</option>
                  </optgroup>
                  <optgroup label="임원">
                    <option value="이사">이사</option>
                    <option value="상무이사">상무이사</option>
                    <option value="전무이사">전무이사</option>
                    <option value="부사장">부사장</option>
                    <option value="사장">사장</option>
                    <option value="대표이사">대표이사</option>
                  </optgroup>
                  <optgroup label="기타">
                    <option value="팀장">팀장</option>
                    <option value="실장">실장</option>
                    <option value="본부장">본부장</option>
                    <option value="고문">고문</option>
                    <option value="감사">감사</option>
                  </optgroup>
                </select>
              </div>
            </div>
            <div class="row mb-3">
              <label class="col-3 col-form-label">연락처</label>
              <div class="col-9">
                <input type="tel" class="form-control" v-model="editForm.employeePhone" placeholder="010-0000-0000" />
              </div>
            </div>
            <div class="row mb-3">
              <label class="col-3 col-form-label">입사일</label>
              <div class="col-9">
                <input type="date" class="form-control" v-model="editForm.joinDate" />
              </div>
            </div>
            <div class="text-end">
              <button type="button" class="btn btn-secondary me-2" @click="cancelEdit">취소</button>
              <button type="submit" class="btn btn-primary" :disabled="isSaving">
                <span v-if="isSaving" class="spinner-border spinner-border-sm me-1"></span>
                저장
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
    
    <!-- 로그인 이력 -->
    <div class="card mb-4">
      <div class="card-header">
        <strong>로그인 이력</strong>
        <small class="text-muted ms-2">(최근 50건)</small>
      </div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-hover mb-0">
            <thead class="table-light">
              <tr>
                <th style="width: 180px">로그인 시간</th>
                <th style="width: 130px">로그인 IP</th>
                <th style="width: 180px">로그아웃 시간</th>
                <th style="width: 130px">로그아웃 IP</th>
                <th style="width: 100px">상태</th>
              </tr>
            </thead>
            <tbody>
              <tr v-if="isLoadingHistory">
                <td colspan="5" class="text-center py-4">
                  <span class="spinner-border spinner-border-sm me-2"></span>로딩 중...
                </td>
              </tr>
              <tr v-else-if="loginHistory.length === 0">
                <td colspan="5" class="text-center py-4 text-muted">로그인 이력이 없습니다.</td>
              </tr>
              <tr v-else v-for="h in loginHistory" :key="h.historyId">
                <td>{{ formatDateTime(h.loginAt) }}</td>
                <td><code>{{ h.loginIp || '-' }}</code></td>
                <td>{{ h.logoutAt ? formatDateTime(h.logoutAt) : '-' }}</td>
                <td><code>{{ h.logoutIp || '-' }}</code></td>
                <td>
                  <span v-if="h.sessionStatus === 'logout'" class="badge bg-secondary">로그아웃</span>
                  <span v-else-if="h.isCurrentSession" class="badge bg-success">접속중</span>
                  <span v-else-if="h.sessionStatus === 'active'" class="badge bg-info">활성</span>
                  <span v-else class="badge bg-warning text-dark">세션만료</span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    
    <!-- VCS 계정 설정 -->
    <div class="card mb-4">
      <div class="card-header d-flex justify-content-between align-items-center">
        <strong><i class="bi bi-git me-2"></i>VCS 계정 설정</strong>
        <button class="btn btn-sm btn-outline-primary" @click="openVcsModal()">
          <i class="bi bi-plus"></i> 계정 추가
        </button>
      </div>
      <div class="card-body p-0">
        <div v-if="isLoadingVcs" class="text-center py-4">
          <span class="spinner-border spinner-border-sm me-2"></span>로딩 중...
        </div>
        <div v-else-if="vcsAccounts.length === 0" class="text-center py-4 text-muted">
          <i class="bi bi-git display-6 d-block mb-2"></i>
          등록된 VCS 계정이 없습니다.
        </div>
        <div v-else class="table-responsive">
          <table class="table table-hover mb-0">
            <thead class="table-light">
              <tr>
                <th>서버</th>
                <th>사용자명</th>
                <th>이메일</th>
                <th style="width: 80px">인증방식</th>
                <th style="width: 100px" class="text-center">관리</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="a in vcsAccounts" :key="a.accountId">
                <td>
                  <span v-if="a.serverType === 'git'" class="badge bg-success me-1">Git</span>
                  <span v-else class="badge bg-info me-1">SVN</span>
                  {{ a.serverName }}
                </td>
                <td>{{ a.vcsUsername }}</td>
                <td>{{ a.vcsEmail || '-' }}</td>
                <td>
                  <span v-if="a.authType === 'token'" class="badge bg-primary">토큰</span>
                  <span v-else-if="a.authType === 'ssh'" class="badge bg-dark">SSH</span>
                  <span v-else class="badge bg-secondary">비밀번호</span>
                </td>
                <td class="text-center">
                  <button class="btn btn-sm btn-outline-primary me-1" @click="openVcsModal(a)">
                    <i class="bi bi-pencil"></i>
                  </button>
                  <button class="btn btn-sm btn-outline-danger" @click="deleteVcsAccount(a)">
                    <i class="bi bi-trash"></i>
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    
    <!-- 비밀번호 변경 -->
    <div class="card">
      <div class="card-header">
        <strong><i class="bi bi-key me-2"></i>비밀번호 변경</strong>
      </div>
      <div class="card-body">
        <form @submit.prevent="changePassword">
          <div class="row mb-3" v-if="userInfo.hasPassword">
            <label class="col-3 col-form-label">현재 비밀번호</label>
            <div class="col-9">
              <input type="password" class="form-control" v-model="pwForm.currentPassword" required />
            </div>
          </div>
          <div class="row mb-3">
            <label class="col-3 col-form-label">새 비밀번호</label>
            <div class="col-9">
              <input type="password" class="form-control" v-model="pwForm.newPassword" required minlength="8" />
              <small class="text-muted">8자 이상</small>
            </div>
          </div>
          <div class="row mb-3">
            <label class="col-3 col-form-label">비밀번호 확인</label>
            <div class="col-9">
              <input type="password" class="form-control" v-model="pwForm.confirmPassword" required />
            </div>
          </div>
          <div class="text-end">
            <button type="submit" class="btn btn-warning" :disabled="isChangingPw">
              <span v-if="isChangingPw" class="spinner-border spinner-border-sm me-1"></span>
              비밀번호 변경
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- VCS 계정 모달 -->
    <div class="modal fade" :class="{ show: showVcsModal }" :style="{ display: showVcsModal ? 'block' : 'none' }">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">{{ isEditVcs ? 'VCS 계정 수정' : 'VCS 계정 추가' }}</h5>
            <button type="button" class="btn-close" @click="showVcsModal = false"></button>
          </div>
          <div class="modal-body">
            <div class="mb-3">
              <label class="form-label">VCS 서버 <span class="text-danger">*</span></label>
              <select class="form-select" v-model="vcsForm.serverId" :disabled="isEditVcs">
                <option value="">선택하세요</option>
                <option v-for="s in vcsServers" :key="s.serverId" :value="s.serverId.toString()">
                  [{{ s.serverType.toUpperCase() }}] {{ s.serverName }}
                </option>
              </select>
            </div>
            <div class="mb-3">
              <label class="form-label">사용자명 <span class="text-danger">*</span></label>
              <input type="text" class="form-control" v-model="vcsForm.vcsUsername" placeholder="VCS 계정 사용자명" />
            </div>
            <div class="mb-3">
              <label class="form-label">이메일</label>
              <input type="email" class="form-control" v-model="vcsForm.vcsEmail" placeholder="커밋 시 사용하는 이메일" />
              <small class="text-muted">Git 커밋 시 사용하는 이메일과 동일하게 입력하세요.</small>
            </div>
            <div class="mb-3">
              <label class="form-label">인증 방식</label>
              <select class="form-select" v-model="vcsForm.authType">
                <option value="password">비밀번호</option>
                <option value="token">토큰</option>
                <option value="ssh">SSH 키</option>
              </select>
            </div>
            <div class="mb-3">
              <label class="form-label">{{ vcsForm.authType === 'token' ? '액세스 토큰' : '비밀번호/키' }}</label>
              <input type="password" class="form-control" v-model="vcsForm.credential" 
                :placeholder="isEditVcs ? '변경하려면 입력' : ''" />
              <small class="text-muted">암호화하여 저장됩니다.</small>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" @click="showVcsModal = false">취소</button>
            <button type="button" class="btn btn-primary" @click="saveVcsAccount">저장</button>
          </div>
        </div>
      </div>
    </div>
    <div class="modal-backdrop fade show" v-if="showVcsModal"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
const { fetchCurrentUser } = useAuth()
const router = useRouter()

const userInfo = ref<any>({})
const loginHistory = ref<any[]>([])
const isLoading = ref(true)
const isLoadingHistory = ref(true)

// VCS 계정 관련
const vcsAccounts = ref<any[]>([])
const vcsServers = ref<any[]>([])
const isLoadingVcs = ref(true)
const showVcsModal = ref(false)
const isEditVcs = ref(false)
const editVcsId = ref<number | null>(null)
const vcsForm = ref({ serverId: '', vcsUsername: '', vcsEmail: '', authType: 'password', credential: '' })
const isEditing = ref(false)
const isSaving = ref(false)

// 비밀번호 변경 관련
const pwForm = ref({ currentPassword: '', newPassword: '', confirmPassword: '' })
const isChangingPw = ref(false)

const editForm = ref({
  employeeName: '',
  company: '',
  employeePosition: '',
  employeePhone: '',
  joinDate: ''
})

onMounted(async () => {
  const user = await fetchCurrentUser()
  if (!user) {
    router.push('/login')
    return
  }
  loadUserInfo()
  loadLoginHistory()
  loadVcsAccounts()
  loadVcsServers()
})

async function loadUserInfo() {
  isLoading.value = true
  try {
    const res = await $fetch<any>('/api/auth/me')
    userInfo.value = res.user
  } catch (e) {
    console.error(e)
  } finally {
    isLoading.value = false
  }
}

async function loadLoginHistory() {
  isLoadingHistory.value = true
  try {
    const res = await $fetch<any>('/api/auth/login-history')
    loginHistory.value = res.history
  } catch (e) {
    console.error(e)
  } finally {
    isLoadingHistory.value = false
  }
}

function startEdit() {
  editForm.value = {
    employeeName: userInfo.value.employeeName || '',
    company: userInfo.value.company || '(주)터보소프트',
    employeePosition: userInfo.value.employeePosition || '',
    employeePhone: userInfo.value.employeePhone || '',
    joinDate: userInfo.value.joinDate ? userInfo.value.joinDate.split('T')[0] : ''
  }
  isEditing.value = true
}

function cancelEdit() {
  isEditing.value = false
}

async function saveProfile() {
  isSaving.value = true
  try {
    await $fetch(`/api/employee/${userInfo.value.employeeId}/update`, {
      method: 'PUT',
      body: editForm.value
    })
    alert('저장되었습니다.')
    isEditing.value = false
    loadUserInfo()
  } catch (e: any) {
    alert(e.data?.message || '저장에 실패했습니다.')
  } finally {
    isSaving.value = false
  }
}

function formatDateTime(dateStr: string) {
  if (!dateStr) return '-'
  const d = new Date(dateStr)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hour = String(d.getHours()).padStart(2, '0')
  const minute = String(d.getMinutes()).padStart(2, '0')
  const second = String(d.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`
}

// VCS 계정 관련 함수
async function loadVcsAccounts() {
  isLoadingVcs.value = true
  try {
    const res = await $fetch<any>('/api/vcs-account/my')
    vcsAccounts.value = res.accounts || []
  } catch (e) { console.error(e) }
  finally { isLoadingVcs.value = false }
}

async function loadVcsServers() {
  try {
    const res = await $fetch<any>('/api/vcs-server/list')
    vcsServers.value = res.servers || []
  } catch (e) { console.error(e) }
}

function openVcsModal(account?: any) {
  if (account) {
    isEditVcs.value = true
    editVcsId.value = account.accountId
    vcsForm.value = {
      serverId: account.serverId?.toString() || '',
      vcsUsername: account.vcsUsername || '',
      vcsEmail: account.vcsEmail || '',
      authType: account.authType || 'password',
      credential: ''
    }
  } else {
    isEditVcs.value = false
    editVcsId.value = null
    vcsForm.value = { serverId: '', vcsUsername: '', vcsEmail: '', authType: 'password', credential: '' }
  }
  showVcsModal.value = true
}

async function saveVcsAccount() {
  if (!vcsForm.value.serverId) { alert('서버를 선택해주세요.'); return }
  if (!vcsForm.value.vcsUsername.trim()) { alert('사용자명을 입력해주세요.'); return }
  
  try {
    if (isEditVcs.value && editVcsId.value) {
      await $fetch(`/api/vcs-account/${editVcsId.value}/update`, { method: 'PUT', body: vcsForm.value })
    } else {
      await $fetch('/api/vcs-account/create', { method: 'POST', body: { ...vcsForm.value, serverId: Number(vcsForm.value.serverId) } })
    }
    showVcsModal.value = false
    await loadVcsAccounts()
  } catch (e: any) {
    alert(e.data?.message || '저장에 실패했습니다.')
  }
}

async function deleteVcsAccount(account: any) {
  if (!confirm('VCS 계정을 삭제하시겠습니까?')) return
  try {
    await $fetch(`/api/vcs-account/${account.accountId}/delete`, { method: 'DELETE' })
    await loadVcsAccounts()
  } catch (e: any) {
    alert(e.data?.message || '삭제에 실패했습니다.')
  }
}

// 비밀번호 변경
async function changePassword() {
  if (!pwForm.value.newPassword || pwForm.value.newPassword.length < 8) {
    alert('새 비밀번호는 8자 이상이어야 합니다.')
    return
  }
  if (pwForm.value.newPassword !== pwForm.value.confirmPassword) {
    alert('새 비밀번호가 일치하지 않습니다.')
    return
  }
  
  isChangingPw.value = true
  try {
    await $fetch('/api/auth/change-password', {
      method: 'POST',
      body: {
        currentPassword: pwForm.value.currentPassword || null,
        newPassword: pwForm.value.newPassword,
        confirmPassword: pwForm.value.confirmPassword
      }
    })
    alert('비밀번호가 변경되었습니다.')
    pwForm.value = { currentPassword: '', newPassword: '', confirmPassword: '' }
    loadUserInfo()
  } catch (e: any) {
    alert(e.data?.message || '비밀번호 변경에 실패했습니다.')
  } finally {
    isChangingPw.value = false
  }
}
</script>
