<template>
  <div class="setting-wrapper mini-scrollbar">
    <div class="banner flex flex-center flex-col">
      <div class="title">Settings</div>
      <div class="slogan">Manage your account settings and preferences</div>
    </div>

    <div class="setting-content">
      <div class="setting-item flex">
        <div class="label-container">
          <div class="label">Profile</div>
          <div class="label-desc">
            Update your display name, avatar, social links and account security.
          </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">FIRST NAME</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="First Name" />
                </div>
              </div>
              <div class="read-item">
                <div class="read-label">LAST NAME</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="Last Name" />
                </div>
              </div>
            </div>

            <div class="read-row">
              <div class="read-label">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="Username" />
              </div>
            </div>
            <div class="read-tip">Your public username on Stylish Parade.</div>

            <div class="read-row role-row">
              <div class="read-label">ROLE</div>
              <div :class="{ 'readonly-radio-group': !isEditing }">
                <Radio multiple :max="2" v-model="roleModel" :options="roleList" />
              </div>
            </div>
            <div class="read-tip">Select up to 2 labels that suit you.</div>

            <div class="social-links read-social-links">
              <div class="title">SOCIAL LINKS</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">Link {{ 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">Security</div>
          <div class="label-desc">Manage your login email and password.</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">EMAIL</div>
              <div class="security-static flex-1">{{ displayData.email }}</div>
              <button
                v-show="isEditing"
                type="button"
                class="small-btn"
                @click="resetSecurityEmail"
              >
                CANCEL
              </button>
            </div>
          </div>

          <div v-show="isEditing" class="security-row">
            <div class="security-label">NEW EMAIL ADDRESS</div>
            <div class="outlined-field verify-field align-center">
              <el-input v-model="securityDraft.newEmail" placeholder="Enter new email" />
              <div class="verify-btn">Verify</div>
            </div>
          </div>

          <div class="inner-divider" />

          <div class="security-row">
            <div class="security-inline-row flex align-center">
              <div class="security-label inline">PASSWORD</div>
              <div class="security-static password-mask flex-1">.........</div>
              <button
                v-show="isEditing"
                type="button"
                class="small-btn"
                @click="resetSecurityPassword"
              >
                CANCEL
              </button>
            </div>
          </div>

          <div v-show="isEditing" class="security-row">
            <div class="security-label">NEW PASSWORD</div>
            <div class="outlined-field">
              <el-input
                v-model="securityDraft.newPassword"
                type="password"
                show-password
                placeholder="Enter new password"
              />
            </div>
            <div class="security-tip">You must satisfy ALL password conditions to register.</div>
          </div>

          <div v-show="isEditing" class="security-row">
            <div class="security-label">CURRENT PASSWORD</div>
            <div class="outlined-field">
              <el-input
                v-model="securityDraft.currentPassword"
                type="password"
                show-password
                placeholder="Confirm with your password"
              />
            </div>
          </div>
          <div class="inner-divider" />
        </div>
      </div>

      <div class="gap" />

      <div class="setting-item flex">
        <div class="label-container">
          <div class="label">Language &amp; Region</div>
          <div class="label-desc">Set your preferred language, region and currency display.</div>
        </div>

        <div class="context-container region-container">
          <div class="region-row">
            <div class="security-label">DISPLAY LANGUAGE</div>
            <div v-show="!isEditing" class="security-static field-box">
              {{ displayData.language }}
            </div>
            <div v-show="isEditing" class="outlined-field select-field">
              <el-select v-model="draftData.language" placeholder="Select language">
                <el-option v-for="item in languageList" :key="item" :label="item" :value="item" />
              </el-select>
            </div>
          </div>

          <div class="region-row">
            <div class="security-label">REGION</div>
            <div v-show="!isEditing" class="security-static field-box">
              {{ displayData.region }}
            </div>
            <div v-show="isEditing" class="outlined-field select-field">
              <el-select v-model="draftData.region" placeholder="Select region">
                <el-option v-for="item in regionList" :key="item" :label="item" :value="item" />
              </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 ? 'SAVING...' : 'SAVE CHANGE' }}
          </button>
          <button type="button" class="secondary-btn" :disabled="saving" @click="handleDiscard">
            DISCARD
          </button>
        </template>
        <template v-else>
          <button type="button" class="primary-btn edit-btn" @click="handleEdit">EDIT</button>
        </template>
      </div>
    </div>
    <Footer />
  </div>
</template>

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

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

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

const roleList = [
  'Fashion Enthusiast',
  'Content Creator',
  'Student',
  'Retail / Buyer',
  'Fashion Designer',
  'Brand / Business',
  'PR & Communications',
  'Stylist',
  'Graphic Designer',
  '3D Artist',
  'Other'
].map((item) => ({ name: item, value: item }))

const languageList = ['English', 'Chinese', 'Japanese']
const regionList = ['Hong Kong SAR', 'Mainland China', 'Singapore', 'United Kingdom']

const createDefaultData = (): SettingsData => ({
  firstName: 'Alexandra',
  lastName: 'Chen',
  email: 'alex.chen@gmail.com',
  username: '@alexandra_chen',
  role: ['Student', 'Graphic Designer'],
  links: ['https://instagram.com/username', 'https://...'],
  language: 'English',
  region: 'Hong Kong SAR'
})

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 displayData = computed(() => (isEditing.value ? draftData.value : sourceData.value))

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

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

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

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

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

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

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

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

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 () => {
  const nextData = buildNextData()
  saving.value = true
  try {
    sourceData.value = cloneSettingsData({
      ...nextData,
      links: nextData.links.length ? nextData.links : ['']
    })
    draftData.value = cloneSettingsData(sourceData.value)
    securityDraft.value = createEmptySecurityDraft()
    isEditing.value = false
    ElMessage.success('Settings updated')
  } catch (error) {
    console.warn(error)
  } finally {
    saving.value = false
  }
}
</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;
        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;
      }

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

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