<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" />
              <button v-if="isEditing" type="button" class="avatar-edit-btn">
                <SvgIcon name="ThumbEdit" size="18" class="avatar-edit-icon" />
              </button>
            </div>
            <div class="profile-summary flex flex-col">
              <div class="profile-name">{{ fullName }}</div>
              <div class="profile-email">{{ displayData.email }}</div>
            </div>
          </div>

          <template v-if="isEditing">
            <div class="form-container flex flex-col">
              <div class="flex col-gap-2">
                <div class="form-item">
                  <div class="form-item-label">FIRST NAME</div>
                  <div class="form-item-value name">
                    <el-input v-model="draftData.firstName" placeholder="First Name" />
                  </div>
                </div>
                <div class="form-item">
                  <div class="form-item-label">LAST NAME</div>
                  <div class="form-item-value name">
                    <el-input v-model="draftData.lastName" placeholder="Last Name" />
                  </div>
                </div>
              </div>

              <div class="form-item">
                <div class="form-item-label">USERNAME</div>
                <div class="form-item-value">
                  <el-input v-model="draftData.username" placeholder="Username" />
                </div>
                <div class="form-tip">Your public username on Stylish Parade.</div>
              </div>

              <div class="form-item">
                <div class="form-item-label">ROLE</div>
                <div class="form-item-value noborder radio">
                  <Radio multiple v-model="roleModel" :options="roleList" />
                </div>
                <div class="form-tip">Select up to 2 labels that suit you.</div>
              </div>
            </div>

            <div class="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 draftData.links"
                  :key="`edit-${index}`"
                >
                  <div class="link-index">Link {{ index + 1 }}</div>
                  <div class="link-href flex-1">
                    <el-input v-model="draftData.links[index]" />
                  </div>
                </div>
                <button type="button" class="add-link-btn" @click="handleAddLink">+</button>
              </div>
            </div>
          </template>

          <template v-else>
            <div class="read-section">
              <div class="read-row two-column">
                <div class="read-item">
                  <div class="read-label">FIRST NAME</div>
                  <div class="read-box">{{ displayData.firstName }}</div>
                </div>
                <div class="read-item">
                  <div class="read-label">LAST NAME</div>
                  <div class="read-box">{{ displayData.lastName }}</div>
                </div>
              </div>

              <div class="read-row">
                <div class="read-label">USERNAME</div>
                <div class="read-box">{{ displayData.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="role-tags">
                  <div
                    v-for="item in displayData.role"
                    :key="item"
                    class="role-tag is-active"
                  >
                    {{ item }}
                  </div>
                  <div
                    v-for="item in inactiveRoleList"
                    :key="`inactive-${item}`"
                    class="role-tag"
                  >
                    {{ item }}
                  </div>
                </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 class="link-href flex-1 readonly">{{ item }}</div>
                  </div>
                </div>
              </div>
            </div>
          </template>
        </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="security-row">
            <div class="security-label">EMAIL</div>
            <template v-if="isEditing">
              <div class="inline-header flex align-center">
                <div class="security-static flex-1">{{ displayData.email }}</div>
                <button type="button" class="small-btn" @click="resetSecurityEmail">
                  CANCEL
                </button>
              </div>
            </template>
            <template v-else>
              <div class="security-static">{{ displayData.email }}</div>
            </template>
          </div>

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

          <div class="inner-divider" v-if="isEditing" />

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

          <template v-if="isEditing">
            <div 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 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>
          </template>
        </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>
            <template v-if="isEditing">
              <div 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>
            </template>
            <template v-else>
              <div class="security-static field-box">{{ displayData.language }}</div>
            </template>
          </div>

          <div class="region-row">
            <div class="security-label">REGION</div>
            <template v-if="isEditing">
              <div 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>
            </template>
            <template v-else>
              <div class="security-static field-box">{{ displayData.region }}</div>
            </template>
          </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>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { updateUserInfo } from '@/api/login'
import { useUserInfoStore } from '@/stores'
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 userInfoStore = useUserInfoStore()

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 createFallbackData = (): 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 normalizeArray = (value: unknown, fallback: string[] = []) => {
  if (!Array.isArray(value)) return fallback
  return value.filter((item): item is string => typeof item === 'string' && item.trim().length > 0)
}

const createSettingsFromUserInfo = (userInfo: any): SettingsData => {
  const fallback = createFallbackData()
  const firstName = userInfo?.firstName || userInfo?.first_name || fallback.firstName
  const lastName = userInfo?.lastName || userInfo?.last_name || fallback.lastName
  return {
    firstName,
    lastName,
    email: userInfo?.email || fallback.email,
    username: userInfo?.username || fallback.username,
    role: normalizeArray(userInfo?.role || userInfo?.roles, fallback.role).slice(0, 2),
    links: normalizeArray(userInfo?.links || userInfo?.socialLinks, fallback.links),
    language: userInfo?.language || fallback.language,
    region: userInfo?.region || fallback.region
  }
}

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>(createSettingsFromUserInfo(userInfoStore.getUserInfo))
const draftData = ref<SettingsData>(cloneSettingsData(sourceData.value))
const securityDraft = ref<SecurityDraft>(createEmptySecurityDraft())
const isEditing = ref(false)
const saving = ref(false)

watch(
  () => userInfoStore.getUserInfo,
  (value) => {
    const next = createSettingsFromUserInfo(value)
    sourceData.value = next
    if (!isEditing.value) {
      draftData.value = cloneSettingsData(next)
    }
  },
  { deep: true, immediate: true }
)

const displayData = computed(() => (isEditing.value ? draftData.value : sourceData.value))

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

const inactiveRoleList = computed(() => {
  const selected = new Set(sourceData.value.role)
  return roleList
    .map((item) => String(item.value))
    .filter((item) => !selected.has(item))
})

const roleModel = computed({
  get: () => draftData.value.role,
  set: (value: string[]) => {
    draftData.value.role = value.slice(0, 2)
  }
})

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 buildUpdatePayload = () => {
  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,
    password: securityDraft.value.newPassword.trim() || undefined,
    currentPassword: securityDraft.value.currentPassword.trim() || undefined,
    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 payload = buildUpdatePayload()
  saving.value = true
  try {
    await updateUserInfo(payload)
    const nextData = cloneSettingsData({
      ...draftData.value,
      email: payload.email,
      links: payload.links.length ? payload.links : ['']
    })
    sourceData.value = nextData
    draftData.value = cloneSettingsData(nextData)
    userInfoStore.setUserInfo({
      ...userInfoStore.getUserInfo,
      ...payload
    })
    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;

  .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;
    align-items: flex-start;
  }

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

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

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

  .avatar-icon {
    color: #979797;
  }

  .avatar-edit-btn {
    position: absolute;
    right: -0.2rem;
    bottom: -0.2rem;
    width: 3rem;
    height: 3rem;
    border: 0.2rem solid #ffffff;
    border-radius: 50%;
    background: #232323;
    cursor: pointer;
  }

  .avatar-edit-icon {
    color: #ffffff;
  }

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

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

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

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

  .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 {
    border: 0.1rem solid #979797;

    &.noborder {
      border: none;
    }

    &.name {
      width: 28.4rem;
    }

    &.radio {
      width: 58rem;
    }

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

    :deep(.el-input__wrapper) {
      box-shadow: none;
      border-radius: 0;
      padding: 0 2rem;
    }

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

  .read-section {
    width: 58rem;
  }

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

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

  .read-box,
  .field-box {
    width: 100%;
    min-height: 4rem;
    border: 0.1rem solid #979797;
    padding: 0.8rem 2rem;
    display: flex;
    align-items: center;
    font-family: 'KaiseiOpti-Regular';
    font-size: 1.6rem;
    line-height: 2.4rem;
    color: #232323;
  }

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

  .role-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 0.8rem;
  }

  .role-tag {
    min-width: 8rem;
    height: 4rem;
    padding: 0 1.2rem;
    border: 0.1rem solid #979797;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-family: 'KaiseiOpti-Regular';
    font-size: 1.4rem;
    line-height: 2rem;
    color: #979797;

    &.is-active {
      background: #232323;
      border-color: #232323;
      color: #ffffff;
    }
  }

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

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

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

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

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

  .link-href {
    min-height: 4rem;
    border: 0.1rem solid #979797;
    color: #979797;

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

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

    :deep(.el-input__wrapper) {
      box-shadow: none;
      border-radius: 0;
      padding: 0 2rem;
    }

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

  .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-static {
    min-height: 4rem;
    display: flex;
    align-items: center;
    font-family: 'KaiseiOpti-Regular';
    font-size: 1.6rem;
    line-height: 2.4rem;
    color: #232323;
  }

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

  .inline-header {
    gap: 1.6rem;
  }

  .outlined-field {
    width: 58rem;
    border: 0.1rem solid #979797;

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

    :deep(.el-input__wrapper),
    :deep(.el-select__wrapper) {
      min-height: 4rem;
      box-shadow: none;
      border-radius: 0;
      padding: 0 2rem;
    }

    :deep(.el-input__inner),
    :deep(.el-select__selected-item),
    :deep(.el-select__placeholder) {
      font-family: 'KaiseiOpti-Regular';
      font-size: 1.4rem;
      color: #232323;
    }

    :deep(.el-input__inner::placeholder) {
      color: #9f9f9f;
    }
  }

  .verify-field {
    display: flex;
    align-items: stretch;

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

  .verify-btn {
    width: 7.6rem;
    border: none;
    border-left: 0.1rem solid #979797;
    background: #ffffff;
    font-family: 'KaiseiOpti-Medium';
    font-size: 1.4rem;
    color: #232323;
    cursor: pointer;
  }

  .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;
    font-size: 1.2rem;
    line-height: 2.6rem;
  }

  .inner-divider {
    height: 0.05rem;
    margin: 2.8rem 0 3rem;
    background-color: #c4c4c4;
  }

  .gap {
    height: 0.05rem;
    margin-top: 6rem;
    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;
  }

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

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

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

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

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

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

  .security-container,
  .region-container {
    padding-top: 0.2rem;
  }

  .role-tag,
  :deep(.radio-button) {
    white-space: nowrap;
  }

  :deep(.radio-button-group) {
    gap: 0.8rem;
  }

  :deep(.radio-button) {
    border: 0.1rem solid #979797;
    height: 4rem;
    min-width: 8rem;
    padding: 0 1.2rem;
    color: #979797;
    background-color: #fff;
    font-size: 1.4rem;
    font-family: 'KaiseiOpti-Regular';
  }

  :deep(.radio-button.is-active),
  :deep(.radio-button:hover) {
    border-color: #232323;
    color: #fff;
    background-color: #232323;
  }
}
</style>
