<template>
  <div class="setting-wrapper mini-scrollbar">
    <div class="banner flex flex-center flex-col">
      <div class="title">{{ t('Settings.title') }}</div>
      <div class="slogan">{{ t('Settings.slogan') }}</div>
    </div>

    <div class="setting-content">
      <div class="setting-item flex">
        <div class="label-container">
          <div class="label">{{ t('Settings.profile.title') }}</div>
          <div class="label-desc">
            {{ t('Settings.profile.description') }}
          </div>
        </div>

        <div class="context-container">
          <div class="profile-header flex align-center">
            <div class="avatar relative">
              <SvgIcon name="user_0" size="46" class="avatar-icon" />
              <img src="@/assets/images/edit.png" class="avatar-edit-icon" />
            </div>
            <div class="profile-summary flex flex-col">
              <div class="profile-name">{{ fullName }}</div>
              <div class="profile-email">{{ displayData.email }}</div>
            </div>
          </div>

          <div class="read-section">
            <div class="read-row two-column">
              <div class="read-item">
                <div class="read-label">{{ t('Settings.profile.firstName') }}</div>
                <div v-show="!isEditing" class="read-box">{{ displayData.firstName }}</div>
                <div v-show="isEditing" class="form-item-value name">
                  <el-input
                    v-model="draftData.firstName"
                    :placeholder="t('Settings.profile.firstNamePlaceholder')"
                  />
                </div>
              </div>
              <div class="read-item">
                <div class="read-label">{{ t('Settings.profile.lastName') }}</div>
                <div v-show="!isEditing" class="read-box">{{ displayData.lastName }}</div>
                <div v-show="isEditing" class="form-item-value name">
                  <el-input
                    v-model="draftData.lastName"
                    :placeholder="t('Settings.profile.lastNamePlaceholder')"
                  />
                </div>
              </div>
            </div>

            <div class="read-row">
              <div class="read-label">{{ t('Settings.profile.username') }}</div>
              <div v-show="!isEditing" class="read-box">{{ displayData.username }}</div>
              <div v-show="isEditing" class="form-item-value">
                <el-input
                  v-model="draftData.username"
                  :placeholder="t('Settings.profile.usernamePlaceholder')"
                />
              </div>
            </div>
            <div class="read-tip">{{ t('Settings.profile.usernameTip') }}</div>

            <div class="read-row role-row">
              <div class="read-label">{{ t('Settings.profile.role') }}</div>
              <div :class="{ 'readonly-radio-group': !isEditing }">
                <Radio multiple :max="2" v-model="roleModel" :options="roleList" />
              </div>
            </div>
            <div class="read-tip">{{ t('Settings.profile.roleTip') }}</div>

            <div class="social-links read-social-links">
              <div class="title">{{ t('Settings.profile.socialLinks') }}</div>
              <div class="links-list flex flex-col">
                <div
                  class="links-item flex align-center"
                  v-for="(item, index) in displayData.links"
                  :key="`view-${index}`"
                >
                  <div class="link-index">
                    {{ t('Settings.profile.linkNumber', { index: index + 1 }) }}
                  </div>
                  <div v-show="!isEditing" class="link-href flex-1 readonly">{{ item }}</div>
                  <div v-show="isEditing" class="link-href flex-1">
                    <el-input v-model="draftData.links[index]" />
                  </div>
                </div>
                <button
                  v-show="isEditing"
                  type="button"
                  class="add-link-btn"
                  @click="handleAddLink"
                >
                  +
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="gap" />

      <div class="setting-item flex">
        <div class="label-container">
          <div class="label">{{ t('Settings.security.title') }}</div>
          <div class="label-desc">{{ t('Settings.security.description') }}</div>
        </div>

        <div class="context-container security-container">
          <div class="inner-divider" />
          <div class="security-row">
            <div class="security-inline-row flex align-center">
              <div class="security-label inline">{{ t('Settings.security.email') }}</div>
              <div class="security-static flex-1">{{ displayData.email }}</div>
              <button
                v-show="isEditing"
                type="button"
                class="small-btn"
                @click="resetSecurityEmail"
              >
                {{ t('Settings.buttons.cancel') }}
              </button>
            </div>
          </div>

          <div v-show="isEditing" class="security-row">
            <div class="security-label">{{ t('Settings.security.newEmail') }}</div>
            <div class="outlined-field verify-field align-center">
              <el-input
                v-model="securityDraft.newEmail"
                :placeholder="t('Settings.security.newEmailPlaceholder')"
              />
              <button
                type="button"
                class="verify-btn"
                :class="{ verified: isEmailVerified }"
                @click="handleVerifyEmail"
              >
                {{
                  isEmailVerified ? t('Settings.security.verified') : t('Settings.security.verify')
                }}
              </button>
            </div>
            <div v-if="isEmailVerified" class="security-tip verified-tip">
              {{ t('Settings.security.verifiedTip') }}
            </div>
          </div>

          <div class="inner-divider" />

          <div class="security-row">
            <div class="security-inline-row flex align-center">
              <div class="security-label inline">{{ t('Settings.security.password') }}</div>
              <div class="security-static password-mask flex-1">.........</div>
              <button
                v-show="isEditing"
                type="button"
                class="small-btn"
                @click="resetSecurityPassword"
              >
                {{ t('Settings.buttons.cancel') }}
              </button>
            </div>
          </div>

          <div v-show="isEditing" class="security-row">
            <div class="security-label">{{ t('Settings.security.newPassword') }}</div>
            <div class="outlined-field">
              <el-input
                v-model="securityDraft.newPassword"
                type="password"
                show-password
                :placeholder="t('Settings.security.newPasswordPlaceholder')"
              />
            </div>
            <div class="security-tip">{{ t('Settings.security.passwordTip') }}</div>
          </div>

          <div v-show="isEditing" class="security-row">
            <div class="security-label">{{ t('Settings.security.currentPassword') }}</div>
            <div class="outlined-field">
              <el-input
                v-model="securityDraft.currentPassword"
                type="password"
                show-password
                :placeholder="t('Settings.security.currentPasswordPlaceholder')"
              />
            </div>
          </div>
          <div class="inner-divider" />
        </div>
      </div>

      <div class="gap" />

      <div class="setting-item flex">
        <div class="label-container">
          <div class="label">{{ t('Settings.region.title') }}</div>
          <div class="label-desc">{{ t('Settings.region.description') }}</div>
        </div>

        <div class="context-container region-container">
          <div class="region-row">
            <div class="security-label">{{ t('Settings.region.displayLanguage') }}</div>
            <div v-show="!isEditing" class="security-static field-box">
              {{ displayLanguageLabel }}
            </div>
            <div v-show="isEditing" class="outlined-field select-field">
              <el-select
                v-model="draftData.language"
                :placeholder="t('Settings.region.selectLanguage')"
              >
                <el-option
                  v-for="item in languageList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
          </div>

          <div class="region-row">
            <div class="security-label">{{ t('Settings.region.region') }}</div>
            <div v-show="!isEditing" class="security-static field-box">
              {{ displayRegionLabel }}
            </div>
            <div v-show="isEditing" class="outlined-field select-field">
              <el-select
                v-model="draftData.region"
                :placeholder="t('Settings.region.selectRegion')"
              >
                <el-option
                  v-for="item in regionList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
          </div>
        </div>
      </div>

      <div class="gap bottom-gap" />

      <div class="action-container flex">
        <template v-if="isEditing">
          <button type="button" class="primary-btn" :disabled="saving" @click="handleSave">
            {{ saving ? t('Settings.buttons.saving') : t('Settings.buttons.saveChange') }}
          </button>
          <button type="button" class="secondary-btn" :disabled="saving" @click="handleDiscard">
            {{ t('Settings.buttons.discard') }}
          </button>
        </template>
        <template v-else>
          <button type="button" class="primary-btn edit-btn" @click="handleEdit">
            {{ t('Settings.buttons.edit') }}
          </button>
        </template>
      </div>
    </div>
    <Footer />

    <EmailVerificationDialog
      :visible="isVerificationDialogVisible"
      :email="verificationTargetEmail"
      :saving="saving"
      @close="closeVerificationDialog"
      @resend="handleSendVerifyCode"
      @submit="handleVerificationSubmit"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'
import EmailVerificationDialog from './components/EmailVerificationDialog.vue'
import Radio from './components/Radio.vue'

const roleValues = [
  'fashionEnthusiast',
  'contentCreator',
  'student',
  'retailBuyer',
  'fashionDesigner',
  'brandBusiness',
  'prCommunications',
  'stylist',
  'graphicDesigner',
  'artist3d',
  'other'
] as const

const languageValues = ['english', 'chinese'] as const
const regionValues = ['hongKongSar', 'mainlandChina', 'singapore', 'unitedKingdom'] as const

type RoleValue = (typeof roleValues)[number]
type LanguageValue = (typeof languageValues)[number]
type RegionValue = (typeof regionValues)[number]

interface SettingsData {
  firstName: string
  lastName: string
  email: string
  username: string
  role: RoleValue[]
  links: string[]
  language: LanguageValue
  region: RegionValue
}

interface SecurityDraft {
  newEmail: string
  newPassword: string
  currentPassword: string
}

const { t, locale } = useI18n({ useScope: 'global' })

const languageLocaleMap: Record<LanguageValue, 'ENGLISH' | 'CHINESE_SIMPLIFIED'> = {
  english: 'ENGLISH',
  chinese: 'CHINESE_SIMPLIFIED',
}

const roleList = computed(() =>
  roleValues.map((value) => ({
    name: t(`Settings.roles.${value}`),
    value
  }))
)

const languageList = computed(() =>
  languageValues.map((value) => ({
    label: t(`Settings.languages.${value}`),
    value
  }))
)

const regionList = computed(() =>
  regionValues.map((value) => ({
    label: t(`Settings.regions.${value}`),
    value
  }))
)

const createDefaultData = (): SettingsData => ({
  firstName: 'Alexandra',
  lastName: 'Chen',
  email: 'alex.chen@gmail.com',
  username: '@alexandra_chen',
  role: ['student', 'graphicDesigner'],
  links: ['https://instagram.com/username', 'https://...'],
  language: 'english',
  region: 'hongKongSar'
})

const cloneSettingsData = (data: SettingsData): SettingsData => ({
  firstName: data.firstName,
  lastName: data.lastName,
  email: data.email,
  username: data.username,
  role: [...data.role],
  links: [...data.links],
  language: data.language,
  region: data.region
})

const createEmptySecurityDraft = (): SecurityDraft => ({
  newEmail: '',
  newPassword: '',
  currentPassword: ''
})

const sourceData = ref<SettingsData>(createDefaultData())
const draftData = ref<SettingsData>(cloneSettingsData(sourceData.value))
const securityDraft = ref<SecurityDraft>(createEmptySecurityDraft())
const isEditing = ref(false)
const saving = ref(false)
const isVerificationDialogVisible = ref(false)
const verificationTargetEmail = ref('')
const verifiedEmail = ref('')

const displayData = computed(() => (isEditing.value ? draftData.value : sourceData.value))
const normalizedNewEmail = computed(() => securityDraft.value.newEmail.trim())
const hasNewEmailChange = computed(
  () => normalizedNewEmail.value.length > 0 && normalizedNewEmail.value !== sourceData.value.email
)
const isEmailVerified = computed(
  () => hasNewEmailChange.value && verifiedEmail.value === normalizedNewEmail.value
)
const displayLanguageLabel = computed(() => t(`Settings.languages.${displayData.value.language}`))
const displayRegionLabel = computed(() => t(`Settings.regions.${displayData.value.region}`))

const fullName = computed(() => {
  const data = displayData.value
  return `${data.firstName} ${data.lastName}`.trim()
})

const roleModel = computed({
  get: () => displayData.value.role,
  set: (value: RoleValue[]) => {
    if (isEditing.value) {
      draftData.value.role = value
      return
    }
    sourceData.value.role = value
  }
})

const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

const resetEmailVerificationState = () => {
  isVerificationDialogVisible.value = false
  verificationTargetEmail.value = ''
  verifiedEmail.value = ''
}

const syncAppLanguage = (language: LanguageValue) => {
  const nextLocale = languageLocaleMap[language]
  locale.value = nextLocale
  localStorage.setItem('language', nextLocale)
}

const resetDraftState = () => {
  draftData.value = cloneSettingsData(sourceData.value)
  securityDraft.value = createEmptySecurityDraft()
  resetEmailVerificationState()
}

const handleEdit = () => {
  resetDraftState()
  isEditing.value = true
}

const handleAddLink = () => {
  draftData.value.links.push('')
}

const resetSecurityEmail = () => {
  securityDraft.value.newEmail = ''
  resetEmailVerificationState()
}

const resetSecurityPassword = () => {
  securityDraft.value.newPassword = ''
  securityDraft.value.currentPassword = ''
}

const handleDiscard = () => {
  resetDraftState()
  isEditing.value = false
}

const closeVerificationDialog = () => {
  isVerificationDialogVisible.value = false
  verificationTargetEmail.value = ''
}

const handleVerifyEmail = () => {
  const nextEmail = normalizedNewEmail.value

  if (!nextEmail) {
    ElMessage.warning(t('Settings.messages.enterNewEmailFirst'))
    return
  }

  if (!emailPattern.test(nextEmail)) {
    ElMessage.warning(t('Settings.messages.invalidEmail'))
    return
  }

  if (nextEmail === sourceData.value.email) {
    ElMessage.warning(t('Settings.messages.sameEmail'))
    return
  }

  if (verifiedEmail.value === nextEmail) {
    ElMessage.success(t('Settings.messages.alreadyVerified'))
    return
  }

  verificationTargetEmail.value = nextEmail
  handleSendVerifyCode()
  isVerificationDialogVisible.value = true
}

const handleSendVerifyCode = () => {
  ElMessage.success(t('Settings.messages.verificationCodeSent'))
}

const handleVerificationSubmit = (code: string) => {
  if (code.length !== 6) {
    ElMessage.warning(t('Settings.messages.enterVerificationCode'))
    return
  }

  verifiedEmail.value = verificationTargetEmail.value
  closeVerificationDialog()
  ElMessage.success(t('Settings.messages.verificationCompleted'))
}

const buildNextData = () => {
  const nextEmail = securityDraft.value.newEmail.trim() || draftData.value.email
  return {
    firstName: draftData.value.firstName.trim(),
    lastName: draftData.value.lastName.trim(),
    username: draftData.value.username.trim(),
    email: nextEmail,
    role: draftData.value.role,
    links: draftData.value.links.map((item) => item.trim()).filter(Boolean),
    language: draftData.value.language,
    region: draftData.value.region
  }
}

const handleSave = async () => {
  if (hasNewEmailChange.value && !isEmailVerified.value) {
    ElMessage.warning(t('Settings.messages.verifyEmailBeforeSave'))
    return
  }

  const nextData = buildNextData()
  const previousLanguage = sourceData.value.language
  saving.value = true
  try {
    sourceData.value = cloneSettingsData({
      ...nextData,
      links: nextData.links.length ? nextData.links : ['']
    })

    if (nextData.language !== previousLanguage) {
      syncAppLanguage(nextData.language)
    }

    draftData.value = cloneSettingsData(sourceData.value)
    securityDraft.value = createEmptySecurityDraft()
    resetEmailVerificationState()
    isEditing.value = false
    ElMessage.success(t('Settings.messages.settingsUpdated'))
  } catch (error) {
    console.warn(error)
  } finally {
    saving.value = false
  }
}

watch(
  () => securityDraft.value.newEmail,
  (value) => {
    const trimmedValue = value.trim()

    if (verifiedEmail.value && trimmedValue !== verifiedEmail.value) {
      verifiedEmail.value = ''
    }

    if (
      isVerificationDialogVisible.value &&
      verificationTargetEmail.value &&
      trimmedValue !== verificationTargetEmail.value
    ) {
      closeVerificationDialog()
    }
  }
)
</script>

<style lang="less" scoped>
.setting-wrapper {
  height: 100%;
  overflow-y: auto;
  background: #ffffff;

  .field-text() {
    font-family: 'KaiseiOpti-Regular';
    font-size: 1.6rem;
    line-height: 2.4rem;
    color: #232323;
  }

  .field-frame() {
    width: 100%;
    min-height: 4rem;
    border: 0.1rem solid #979797;
  }

  .control-wrapper() {
    box-shadow: none;
    border-radius: 0;
    padding: 0 2rem;
  }

  .banner {
    height: 14.8rem;
    row-gap: 1.2rem;
    background: linear-gradient(rgba(255, 255, 255, 0.91), rgba(255, 255, 255, 0.91)),
      linear-gradient(90deg, #f2eee8 0%, #fbfaf8 40%, #f1ede7 100%);

    .title {
      font-family: 'KaiseiOpti-Bold';
      font-size: 4rem;
      line-height: 3.6rem;
      color: #232323;
    }

    .slogan {
      font-family: 'KaiseiOpti-Regular';
      font-size: 1.6rem;
      line-height: 2.4rem;
      color: #585858;
    }
  }

  .setting-content {
    padding: 4rem 18rem 7rem;
    .setting-item {
      column-gap: 21.4rem;
      justify-content: center;
    }

    .label-container {
      width: 27.6rem;
      font-family: 'KaiseiOpti-Medium';

      .label {
        font-size: 2.8rem;
        line-height: 3.6rem;
        color: #232323;
      }

      .label-desc {
        width: 24rem;
        margin-top: 2rem;
        font-size: 1.6rem;
        line-height: 2.2rem;
        color: #666666;
      }
    }

    .context-container {
      width: 58rem;
      padding-top: 0.2rem;
    }

    .form-item-label,
    .read-label,
    .security-label {
      margin-bottom: 0.8rem;
      font-family: 'KaiseiOpti-Medium';
      font-size: 1.4rem;
      line-height: 2.4rem;
      letter-spacing: 0.04em;
      color: #585858;
    }

    .form-tip,
    .read-tip,
    .security-tip {
      margin-top: 0.8rem;
      font-family: 'KaiseiOpti-Regular';
      font-size: 1.2rem;
      line-height: 1.6rem;
      color: #9f9f9f;
    }

    .form-item-value,
    .outlined-field,
    .link-href {
      .field-frame();

      :deep(.el-input),
      :deep(.el-select) {
        width: 100%;
        min-height: 4rem;
      }

      :deep(.el-input__wrapper),
      :deep(.el-select__wrapper) {
        .control-wrapper();
        min-height: 4rem;
      }
    }

    .form-item-value {
      &.noborder {
        border: none;
      }

      &.name {
        width: 28.4rem;
      }

      &.radio {
        width: 58rem;
      }

      :deep(.el-input__inner) {
        .field-text();
      }
    }

    .read-box,
    .field-box,
    .security-static {
      .field-frame();
      .field-text();
      display: flex;
      align-items: center;
      padding: 0.8rem 2rem;
    }

    .profile-header {
      column-gap: 2.6rem;
      margin-bottom: 3.6rem;

      .avatar {
        width: 8rem;
        height: 8rem;
        border-radius: 50%;
        border: 0.1rem solid #d8d0c7;
      }

      .avatar-edit-icon {
        position: absolute;
        right: 0;
        bottom: 0;
        width: 3rem;
        height: 3rem;
        border: 0.1rem solid #fff;
        border-radius: 50%;
        cursor: pointer;
      }
    }

    .profile-summary {
      row-gap: 0.6rem;
    }

    .profile-name {
      font-family: 'KaiseiOpti-Medium';
      font-size: 2.4rem;
      line-height: 3.6rem;
      color: #232323;
    }

    .profile-email {
      font-family: 'KaiseiOpti-Regular';
      font-size: 1.8rem;
      line-height: 2.4rem;
      color: #979797;
    }

    .read-section {
      width: 58rem;
    }

    .form-container {
      row-gap: 3rem;
    }

    .col-gap-2 {
      column-gap: 2rem;
    }

    .read-row + .read-row,
    .region-row + .region-row {
      margin-top: 3rem;
    }

    .read-row.two-column {
      display: grid;
      grid-template-columns: 28.4rem 28.4rem;
      column-gap: 2rem;
    }

    .readonly-radio-group {
      pointer-events: none;
    }

    .role-row {
      margin-top: 3rem;
    }

    .social-links {
      margin-top: 5.8rem;
      font-family: 'KaiseiOpti-Medium';

      .title {
        margin-bottom: 2rem;
        font-size: 1.4rem;
        color: #585858;
      }

      &.read-social-links {
        margin-top: 4.8rem;
      }
    }

    .links-list {
      row-gap: 0.8rem;
    }

    .links-item {
      column-gap: 3.4rem;
    }

    .link-index {
      font-family: 'KaiseiOpti-Regular';
      font-size: 1.4rem;
      line-height: 2rem;
      color: #979797;
    }

    .link-href {
      color: #979797;

      &.readonly {
        display: flex;
        align-items: center;
        padding: 0.8rem 2rem;
        font-family: 'KaiseiOpti-Regular';
        font-size: 1.4rem;
        line-height: 2rem;
        color: #9f9f9f;
      }

      :deep(.el-input) {
        height: 4rem;
      }

      :deep(.el-input__inner) {
        font-family: 'KaiseiOpti-Regular';
        font-size: 1.4rem;
        color: #9f9f9f;
      }
    }

    .add-link-btn {
      width: 4rem;
      height: 4rem;
      border: 0.1rem solid #f0ebe5;
      background: #f6f6f6;
      color: #b4aea6;
      font-size: 2rem;
      line-height: 1;
      cursor: pointer;
    }

    .security-container {
      .security-row + .security-row {
        margin-top: 2.8rem;
      }

      .security-label {
        margin: 0 0 0.8rem;

        &.inline {
          width: 10.8rem;
          margin-bottom: 0;
          flex-shrink: 0;
        }
      }

      .security-static {
        min-height: 2.4rem;
        padding: 0.1rem 0 0;
        border: none;
      }

      .security-inline-row {
        gap: 2.8rem;
        min-height: 3.2rem;
      }

      .security-tip {
        margin-top: 0.6rem;
      }

      .verify-field {
        display: flex;
        margin-top: 0.8rem;

        :deep(.el-input) {
          flex: 1;
        }
      }

      .verify-btn {
        border: none;
        min-width: 11rem;
        height: 2.8rem;
        line-height: 2.8rem;
        border-left: 0.1rem solid #979797;
        background: #ffffff;
        font-family: 'KaiseiOpti-Medium';
        font-size: 1.4rem;
        color: #232323;
        cursor: pointer;
        padding: 0 2rem;

        &.verified {
          color: #ffffff;
          background: #232323;
          border-left-color: #232323;
        }
      }

      .password-mask {
        font-family: 'KaiseiOpti-Bold';
        letter-spacing: 0.08rem;
      }

      .inner-divider {
        height: 1px;
        margin: 2rem 0;
        background-color: #c4c4c4;
      }
    }

    .region-container {
      .field-box {
        padding: 0.8rem 2rem;
      }
    }

    .small-btn,
    .secondary-btn,
    .primary-btn {
      border: 0.1rem solid #c4c4c4;
      background: #f6f6f6;
      font-family: 'KaiseiOpti-Bold';
      color: #232323;
      cursor: pointer;
    }

    .small-btn {
      width: 10rem;
      height: 3.2rem;
      align-self: flex-start;
      font-size: 1.2rem;
      line-height: 2.6rem;
      letter-spacing: -0.03em;
    }

    .gap {
      height: 0.05rem;
      margin-top: 6rem;
      margin-bottom: 4rem;
      background-color: #c4c4c4;

      &.bottom-gap {
        margin-top: 4rem;
      }
    }

    .action-container {
      justify-content: center;
      column-gap: 1.2rem;
      margin-top: 2.8rem;
    }

    .primary-btn,
    .secondary-btn {
      height: 4.4rem;
      font-size: 1.6rem;
      line-height: 2.6rem;

      &:disabled {
        opacity: 0.6;
        cursor: not-allowed;
      }
    }

    .primary-btn {
      min-width: 23.6rem;
      padding: 0 2.4rem;
      border-color: #232323;
      background: #232323;
      color: #ffffff;
    }

    .secondary-btn {
      width: 12rem;
      background: #ffffff;
    }

    .edit-btn {
      min-width: 12rem;
    }

    .verified-tip {
      color: #6f7f68;
    }
  }
}

:deep(.el-select-dropdown__item) {
  padding: 0 2rem !important;
}
</style>
