<template>
  <div class="page-container">
    <!-- <div class="page-header">
      <h2 class="page-title">个人设置</h2>
      <p class="page-desc">管理您的基础资料、界面偏好和账户安全。</p>
    </div> -->

    <div class="profile-layout">
      <div class="profile-side">
        <el-card class="profile-card profile-card--profile" shadow="never">
          <template #header>
            <div class="card-header">
              <span>基础资料</span>
            </div>
          </template>

          <div class="avatar-wrapper">
            <div class="user-avatar-large">
              <svg
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="1.5"
                stroke-linecap="round"
                stroke-linejoin="round"
              >
                <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
                <circle cx="12" cy="7" r="4" />
              </svg>
            </div>
            <div class="avatar-text">
              <h3>{{ userName }}</h3>
              <p>{{ phone }}</p>
            </div>
          </div>

          <el-descriptions :column="1" border>
            <el-descriptions-item label="当前租户">{{ tenantName }}</el-descriptions-item>
            <el-descriptions-item label="租户代码">{{ tenantCode }}</el-descriptions-item>
            <el-descriptions-item label="账号身份">
              {{ authScope === "TENANT" ? "租户用户" : "平台管理员" }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <el-card class="profile-card profile-card--full-row" shadow="never">
          <template #header>
            <div class="card-header">
              <span>界面偏好</span>
              <el-tag size="small" type="info">切换即预览</el-tag>
            </div>
          </template>

          <div v-loading="preferencesLoading" class="appearance-content">
            <el-form label-position="top">
              <el-form-item label="主题模式">
                <el-radio-group v-model="preferencesForm.themeMode" class="preference-group">
                  <el-radio-button value="SYSTEM">跟随系统</el-radio-button>
                  <el-radio-button value="LIGHT">浅色</el-radio-button>
                  <el-radio-button value="DARK">深色</el-radio-button>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="主题方案">
                <div class="theme-scheme-grid">
                  <label
                    v-for="option in themeSchemeOptions"
                    :key="option.value"
                    class="theme-scheme-card"
                    :class="{ 'is-active': preferencesForm.themeScheme === option.value }"
                  >
                    <input
                      v-model="preferencesForm.themeScheme"
                      class="theme-scheme-input"
                      type="radio"
                      name="themeScheme"
                      :value="option.value"
                    />
                    <span class="theme-scheme-head">
                      <span class="theme-scheme-name">{{ option.label }}</span>
                      <span class="theme-scheme-swatches">
                        <span
                          v-for="color in option.colors"
                          :key="color"
                          class="theme-scheme-swatch"
                          :style="{ background: color }"
                        />
                      </span>
                    </span>
                    <span class="theme-scheme-description">{{ option.description }}</span>
                  </label>
                </div>
              </el-form-item>

              <el-form-item label="界面密度">
                <el-radio-group v-model="preferencesForm.density" class="preference-group">
                  <el-radio-button value="COMFORTABLE">舒适</el-radio-button>
                  <el-radio-button value="COMPACT">紧凑</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-form>

            <div class="preference-preview">
              <div class="preview-label">当前已应用</div>
              <div class="preview-value">
                <el-tag effect="plain">{{ themeModeLabelMap[themeMode] }}</el-tag>
                <el-tag effect="plain">{{ themeSchemeLabelMap[themeScheme] }}</el-tag>
                <el-tag effect="plain">{{ densityLabelMap[density] }}</el-tag>
              </div>
            </div>

            <div class="appearance-actions">
              <el-button type="primary" :loading="preferencesSaving" @click="handleSavePreferences">
                保存界面偏好
              </el-button>
              <el-button :disabled="preferencesLoading || preferencesSaving" @click="handleResetPreferences">
                重置
              </el-button>
            </div>
          </div>
        </el-card>
      </div>

      <el-card class="profile-card profile-card--password" shadow="never">
        <template #header>
          <div class="card-header">
            <span>修改密码</span>
          </div>
        </template>

        <div class="password-content">
          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="100px"
            label-position="left"
            @submit.prevent
          >
            <el-form-item label="原密码" prop="oldPassword">
              <el-input
                v-model="form.oldPassword"
                type="password"
                show-password
                placeholder="请输入原密码"
              />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="form.newPassword"
                type="password"
                show-password
                placeholder="请输入新密码（至少 6 位）"
              />
            </el-form-item>
            <el-form-item label="确认新密码" prop="confirmPassword">
              <el-input
                v-model="form.confirmPassword"
                type="password"
                show-password
                placeholder="请再次输入新密码"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
                更新密码
              </el-button>
              <el-button @click="handleResetPassword">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { storeToRefs } from "pinia";
import { useRouter } from "vue-router";
import {
  changeMyPassword,
  fetchProfilePreferences,
  logoutAllAuth,
  saveProfilePreferences,
} from "../../api/modules";
import { useAppearanceStore } from "../../stores/appearance";
import { useAuthStore } from "../../stores/auth";
import { resolveLoginPath } from "../../utils/authNavigation";
import {
  normalizeDensity,
  normalizeThemeMode,
  normalizeThemeScheme,
} from "../../stores/appearance";

const router = useRouter();
const authStore = useAuthStore();
const appearanceStore = useAppearanceStore();
const { scope, tenantCode, tenantName: storedTenantName, userName: storedUserName, phone: storedPhone } = storeToRefs(authStore);
const { themeMode, density, themeScheme } = storeToRefs(appearanceStore);

const authScope = computed(() => scope.value);
const tenantCodeDisplay = computed(() => tenantCode.value || "-");
const tenantName = computed(() => storedTenantName.value || (authScope.value === "PLATFORM" ? "平台侧" : "尚未关联"));
const userName = computed(() => storedUserName.value || "未知用户");
const phone = computed(() => storedPhone.value || "未设置");

const themeModeLabelMap: Record<string, string> = {
  SYSTEM: "跟随系统",
  LIGHT: "浅色",
  DARK: "深色",
};

const densityLabelMap: Record<string, string> = {
  COMFORTABLE: "舒适",
  COMPACT: "紧凑",
};

const themeSchemeLabelMap: Record<string, string> = {
  SLATE: "商务蓝",
  OCEAN: "海湾青",
  FOREST: "山岚绿",
  GRAPHITE: "石墨灰",
  AMBER: "琥珀棕",
  RUBY: "酒红棕",
  MIST: "晨雾蓝",
  SAGE: "鼠尾草绿",
  DAWN: "晨曦暖沙",
};

const themeSchemeOptions = [
  {
    value: "SLATE",
    label: "商务蓝",
    description: "中性稳重，适合作为默认后台主题。",
    colors: ["#22364b", "#3c6e91", "#5c88a7"],
  },
  {
    value: "OCEAN",
    label: "海湾青",
    description: "更清爽明亮，强调信息流动感。",
    colors: ["#0f3b49", "#0e7490", "#0284c7"],
  },
  {
    value: "FOREST",
    label: "山岚绿",
    description: "更柔和克制，视觉压力更低。",
    colors: ["#24372a", "#4a7c59", "#7c9a4d"],
  },
  {
    value: "GRAPHITE",
    label: "石墨灰",
    description: "偏专业工具感，冷静克制，适合长期办公。",
    colors: ["#1f2937", "#475569", "#64748b"],
  },
  {
    value: "AMBER",
    label: "琥珀棕",
    description: "更温暖但不张扬，适合弱化科技模板感。",
    colors: ["#5b4636", "#9a6b3f", "#c08a52"],
  },
  {
    value: "RUBY",
    label: "酒红棕",
    description: "偏正式和品牌感，适合需要辨识度的后台。",
    colors: ["#4b2a2f", "#7a3e46", "#a95c57"],
  },
  {
    value: "MIST",
    label: "晨雾蓝",
    description: "偏轻透的雾蓝浅色方案，整体更亮，适合长时间查看表格和列表。",
    colors: ["#f2f7fb", "#6f8faf", "#8fb4c8"],
  },
  {
    value: "SAGE",
    label: "鼠尾草绿",
    description: "留白更多、颜色更柔，能把现有页面从深色压感里拉出来。",
    colors: ["#eef5f0", "#6e947d", "#92b29b"],
  },
  {
    value: "DAWN",
    label: "晨曦暖沙",
    description: "偏暖米杏的浅色方案，比琥珀棕更轻，适合想要温和观感的后台。",
    colors: ["#f7efe9", "#ac755c", "#d19b83"],
  },
] as const;

const formRef = ref<FormInstance>();
const submitLoading = ref(false);
const preferencesLoading = ref(false);
const preferencesSaving = ref(false);
const hydratingPreferences = ref(false);

const form = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

const preferencesForm = reactive({
  themeMode: themeMode.value,
  density: density.value,
  themeScheme: themeScheme.value,
});

const syncPreferencesForm = (payload?: { themeMode?: unknown; density?: unknown; themeScheme?: unknown }) => {
  preferencesForm.themeMode = normalizeThemeMode(payload?.themeMode ?? themeMode.value);
  preferencesForm.density = normalizeDensity(payload?.density ?? density.value);
  preferencesForm.themeScheme = normalizeThemeScheme(payload?.themeScheme ?? themeScheme.value);
};

const loadPreferences = async () => {
  preferencesLoading.value = true;
  hydratingPreferences.value = true;
  try {
    const resp = await fetchProfilePreferences();
    const nextPreferences = {
      themeMode: normalizeThemeMode(resp?.data?.themeMode),
      density: normalizeDensity(resp?.data?.density),
      themeScheme: normalizeThemeScheme(resp?.data?.themeScheme),
    };
    syncPreferencesForm(nextPreferences);
    appearanceStore.setAppearance(nextPreferences, true);
  } catch (_e) {
    syncPreferencesForm();
  } finally {
    hydratingPreferences.value = false;
    preferencesLoading.value = false;
  }
};

const handleSavePreferences = async () => {
  const payload = {
    themeMode: normalizeThemeMode(preferencesForm.themeMode),
    density: normalizeDensity(preferencesForm.density),
    themeScheme: normalizeThemeScheme(preferencesForm.themeScheme),
  };
  preferencesSaving.value = true;
  try {
    await saveProfilePreferences(payload);
    appearanceStore.setAppearance(payload, true);
    ElMessage.success("界面偏好已保存");
  } catch (e: any) {
    if (e?.response?.data?.message) {
      ElMessage.error(e.response.data.message);
    } else {
      ElMessage.error("保存界面偏好失败");
    }
  } finally {
    preferencesSaving.value = false;
  }
};

const handleResetPreferences = async () => {
  await loadPreferences();
  ElMessage.success("已恢复为当前账号保存的界面偏好");
};

const validateConfirmPassword = (_rule: unknown, value: string, callback: (error?: Error) => void) => {
  if (!value) {
    callback(new Error("请再次输入新密码"));
    return;
  }
  if (value !== form.newPassword) {
    callback(new Error("两次输入的新密码不一致"));
    return;
  }
  callback();
};

const rules = reactive<FormRules>({
  oldPassword: [{ required: true, message: "请输入原密码", trigger: "blur" }],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, message: "密码长度至少 6 位", trigger: "blur" },
  ],
  confirmPassword: [{ required: true, validator: validateConfirmPassword, trigger: "blur" }],
});

const handleSubmit = async () => {
  if (!formRef.value) {
    return;
  }
  try {
    await formRef.value.validate();
  } catch (_e) {
    return;
  }

  submitLoading.value = true;
  try {
    await changeMyPassword({
      oldPassword: form.oldPassword,
      newPassword: form.newPassword,
    });
    ElMessage.success("密码修改成功，请重新登录");
    try {
      await logoutAllAuth();
    } catch (_e) {
      // ignore
    }
    const nextLoginPath = resolveLoginPath(authScope.value, tenantCode.value);
    await router.replace(nextLoginPath);
    authStore.clearAuthStorage();
  } catch (e: any) {
    if (e?.response?.data?.message) {
      ElMessage.error(e.response.data.message);
    } else {
      ElMessage.error("修改密码失败");
    }
  } finally {
    submitLoading.value = false;
  }
};

const handleResetPassword = () => {
  formRef.value?.resetFields();
};

watch(
  () => [preferencesForm.themeMode, preferencesForm.density, preferencesForm.themeScheme],
  ([themeMode, density, themeScheme]) => {
    if (hydratingPreferences.value) {
      return;
    }
    appearanceStore.setAppearance({ themeMode, density, themeScheme }, false);
  },
);

onMounted(() => {
  hydratingPreferences.value = true;
  syncPreferencesForm();
  hydratingPreferences.value = false;
  loadPreferences();
});
</script>

<style scoped>
.page-container {
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  margin: 0 0 8px;
  font-size: 20px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.page-desc {
  margin: 0;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.profile-layout {
  display: grid;
  grid-template-columns: minmax(320px, 380px) minmax(0, 1fr);
  gap: 24px;
  align-items: start;
}

.profile-side {
  display: contents;
}

.profile-card {
  border-radius: 12px;
  border: 1px solid var(--wo-card-border);
}

.profile-card--profile {
  grid-column: 1;
  grid-row: 1;
}

.profile-card--password {
  grid-column: 2;
  grid-row: 1;
}

.profile-card--full-row {
  grid-column: 1 / -1;
  grid-row: 2;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  font-weight: 600;
  font-size: 16px;
}

.avatar-wrapper {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 24px;
}

.user-avatar-large {
  width: 72px;
  height: 72px;
  border-radius: 50%;
  background: var(--wo-profile-avatar-bg);
  color: var(--wo-profile-avatar-text);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.15);
}

.user-avatar-large svg {
  width: 36px;
  height: 36px;
}

.avatar-text h3 {
  margin: 0 0 4px;
  font-size: 18px;
  color: var(--el-text-color-primary);
}

.avatar-text p {
  margin: 0;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.appearance-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.preference-group {
  display: flex;
  flex-wrap: wrap;
}

.theme-scheme-grid {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 12px;
}

.theme-scheme-card {
  position: relative;
  display: flex;
  flex-direction: column;
  gap: 10px;
  min-height: 108px;
  padding: 14px;
  border: 1px solid var(--wo-card-border);
  border-radius: 12px;
  background: var(--el-bg-color);
  cursor: pointer;
  transition: border-color 0.2s ease, box-shadow 0.2s ease, transform 0.2s ease;
}

.theme-scheme-card:hover {
  transform: translateY(-1px);
  border-color: rgba(var(--wo-theme-rgb), 0.28);
  box-shadow: 0 8px 20px rgba(15, 23, 42, 0.08);
}

.theme-scheme-card.is-active {
  border-color: var(--el-color-primary);
  box-shadow: 0 0 0 1px rgba(var(--wo-theme-rgb), 0.16), 0 10px 24px rgba(var(--wo-theme-rgb), 0.12);
}

.theme-scheme-input {
  position: absolute;
  inset: 0;
  opacity: 0;
  cursor: pointer;
}

.theme-scheme-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.theme-scheme-name {
  font-size: 14px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.theme-scheme-swatches {
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.theme-scheme-swatch {
  width: 14px;
  height: 14px;
  border-radius: 999px;
  box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.32);
}

.theme-scheme-description {
  font-size: 12px;
  line-height: 1.6;
  color: var(--el-text-color-secondary);
}

.preference-preview {
  padding: 12px 14px;
  border-radius: 10px;
  background: var(--el-fill-color-light);
}

.preview-label {
  margin-bottom: 8px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.preview-value {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.appearance-actions {
  display: flex;
  gap: 12px;
}

.password-content {
  padding-top: 4px;
}

@media (max-width: 1024px) {
  .profile-layout {
    grid-template-columns: 1fr;
  }

  .profile-card--profile,
  .profile-card--password,
  .profile-card--full-row {
    grid-column: 1 / -1;
    grid-row: auto;
  }
}

@media (max-width: 640px) {
  .avatar-wrapper {
    align-items: flex-start;
    flex-direction: column;
  }

  .theme-scheme-grid {
    grid-template-columns: 1fr;
  }

  .appearance-actions {
    flex-direction: column;
  }

  .appearance-actions :deep(.el-button) {
    width: 100%;
    margin-left: 0;
  }
}
</style>
