import { computed, type ComputedRef, onMounted, ref } from 'vue';
import type { PasswordConfig, PasswordRule } from '@/api/system/security/types';
import { getPasswordConfigWithFallback } from '@/api/system/security';

export interface PasswordStrengthConfig {
  username?: string | ComputedRef<string>;
  showStrengthMeter?: boolean;
  showTooltip?: boolean;
}

/**
 * 密码强度管理 - 重构版本
 * 职责：仅负责前端UI反馈，不做业务验证
 */
export function usePasswordStrength(config: PasswordStrengthConfig = {}) {
  const { username: usernameInput = '', showStrengthMeter = true, showTooltip = true } = config;

  // 统一处理用户名
  const username = computed(() => {
    if (typeof usernameInput === 'string') {
      return usernameInput;
    } else {
      return usernameInput?.value || '';
    }
  });

  // 密码配置（从服务器获取）
  const passwordConfig = ref<PasswordConfig | null>(null);
  const configLoaded = ref(false);
  const configError = ref<string>('');

  // 当前密码值
  const currentPassword = ref('');

  // 密码规则校验状态（仅用于UI显示）
  const lengthValid = ref(false);
  const uppercaseValid = ref(false);
  const lowercaseValid = ref(false);
  const numberValid = ref(false);
  const specialCharValid = ref(false);
  const containsUsername = ref(false);

  // 密码正则表达式常量
  const PASSWORD_REGEX = {
    UPPERCASE: /[A-Z]/,
    LOWERCASE: /[a-z]/,
    NUMBER: /[0-9]/,
    SPECIAL_CHAR: /[^A-Za-z0-9]/
  } as const;

  // 计算至少满足指定数量的字符类型
  const minTypesMet = computed(() => {
    if (!passwordConfig.value) return false;

    let count = 0;
    if (uppercaseValid.value) count++;
    if (lowercaseValid.value) count++;
    if (numberValid.value) count++;
    if (specialCharValid.value) count++;
    return count >= passwordConfig.value.minTypeCount;
  });

  // 所有基础规则是否满足（仅用于UI反馈）
  const allBasicRulesMet = computed(() => {
    return lengthValid.value && minTypesMet.value && !containsUsername.value;
  });

  // 密码强度评分 (0-100) - 简化版本，仅用于UI显示
  const strengthScore = computed(() => {
    if (!currentPassword.value || !passwordConfig.value) return 0;

    const weights = passwordConfig.value.strengthWeights;
    if (!weights) return 0;

    let score = 0;
    if (lengthValid.value) score += weights.length || 20;
    if (uppercaseValid.value) score += weights.uppercase || 15;
    if (lowercaseValid.value) score += weights.lowercase || 15;
    if (numberValid.value) score += weights.number || 15;
    if (specialCharValid.value) score += weights.specialChar || 15;
    if (!containsUsername.value) score += weights.noUsername || 20;

    return Math.min(score, 100);
  });

  // 密码强度等级
  const strengthLevel = computed(() => {
    if (!passwordConfig.value?.strengthLevels) return '未知';

    const levels = passwordConfig.value.strengthLevels;
    const score = strengthScore.value;

    if (score < levels.weak.threshold) return levels.weak.label;
    if (score < levels.medium.threshold) return levels.medium.label;
    return levels.strong.label;
  });

  // 密码强度颜色
  const strengthColor = computed(() => {
    if (!passwordConfig.value?.strengthLevels) return '#ccc';

    const levels = passwordConfig.value.strengthLevels;
    const score = strengthScore.value;

    if (score < levels.weak.threshold) return levels.weak.color;
    if (score < levels.medium.threshold) return levels.medium.color;
    return levels.strong.color;
  });

  // 获取规则图标名称
  const getRuleIcon = (isValid: boolean, hasPassword: boolean) => {
    if (!hasPassword) return 'Minus';
    return isValid ? 'Check' : 'Close';
  };

  // 密码规则列表
  const passwordRules = computed((): PasswordRule[] => {
    if (!passwordConfig.value) return [];

    return [
      {
        key: 'length',
        label: `长度至少${passwordConfig.value.minLength}位`,
        valid: lengthValid.value,
        icon: getRuleIcon(lengthValid.value, !!currentPassword.value)
      },
      {
        key: 'uppercase',
        label: '包含大写字母',
        valid: uppercaseValid.value,
        icon: getRuleIcon(uppercaseValid.value, !!currentPassword.value)
      },
      {
        key: 'lowercase',
        label: '包含小写字母',
        valid: lowercaseValid.value,
        icon: getRuleIcon(lowercaseValid.value, !!currentPassword.value)
      },
      {
        key: 'number',
        label: '包含数字',
        valid: numberValid.value,
        icon: getRuleIcon(numberValid.value, !!currentPassword.value)
      },
      {
        key: 'special',
        label: '包含特殊字符',
        valid: specialCharValid.value,
        icon: getRuleIcon(specialCharValid.value, !!currentPassword.value)
      },
      {
        key: 'types',
        label: `至少满足上述${passwordConfig.value.minTypeCount}种字符要求`,
        valid: minTypesMet.value,
        icon: getRuleIcon(minTypesMet.value, !!currentPassword.value)
      },
      {
        key: 'username',
        label: '不能包含用户名',
        valid: !containsUsername.value && !!currentPassword.value,
        icon: getRuleIcon(!containsUsername.value && !!currentPassword.value, !!currentPassword.value)
      }
    ];
  });

  /**
   * 检查密码强度 - 简化版本，仅用于UI反馈
   * 注意：这里不做业务验证，只做UI状态更新
   */
  const checkPasswordStrengthForUI = (password: string) => {
    currentPassword.value = password;

    if (!password || !passwordConfig.value) {
      resetPasswordStrength();
      return;
    }

    // 1. 长度检查
    lengthValid.value = password.length >= passwordConfig.value.minLength;

    // 2. 字符类型检查
    uppercaseValid.value = PASSWORD_REGEX.UPPERCASE.test(password);
    lowercaseValid.value = PASSWORD_REGEX.LOWERCASE.test(password);
    numberValid.value = PASSWORD_REGEX.NUMBER.test(password);
    specialCharValid.value = PASSWORD_REGEX.SPECIAL_CHAR.test(password);

    // 3. 用户名包含检查
    containsUsername.value = username.value ? password.toLowerCase().includes(username.value.toLowerCase()) : false;
  };

  /**
   * 创建前端验证规则 - 简化版本
   * 注意：仅用于基础的表单验证，不替代后端验证
   */
  const createBasicPasswordRules = (config: { isRequired?: boolean; fieldName?: string } = {}) => {
    const { isRequired = true, fieldName = '密码' } = config;

    if (!configLoaded.value || !passwordConfig.value) {
      // 配置未加载时使用最基础的规则
      return [
        {
          required: isRequired,
          message: `${fieldName}不能为空`,
          trigger: 'blur'
        }
      ];
    }

    const rules = [];

    // 必填验证
    if (isRequired) {
      rules.push({
        required: true,
        message: `${fieldName}不能为空`,
        trigger: 'blur'
      });
    }

    // 长度验证
    rules.push({
      min: passwordConfig.value.minLength,
      message: `${fieldName}长度至少${passwordConfig.value.minLength}位`,
      trigger: 'blur'
    });

    // 基础格式验证（不包含业务逻辑）
    rules.push({
      validator: (rule: any, value: string, callback: any) => {
        if (!value) {
          callback();
          return;
        }

        // 基础检查，提示用户但不阻止提交（后端会最终验证）
        checkPasswordStrengthForUI(value);

        // 只检查最基本的要求，复杂验证交给后端
        if (value.length < passwordConfig.value!.minLength) {
          callback(new Error(`${fieldName}长度至少${passwordConfig.value!.minLength}位`));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    });

    return rules;
  };

  // 重置密码强度状态
  const resetPasswordStrength = () => {
    currentPassword.value = '';
    lengthValid.value = false;
    uppercaseValid.value = false;
    lowercaseValid.value = false;
    numberValid.value = false;
    specialCharValid.value = false;
    containsUsername.value = false;
  };

  // 加载密码配置
  const loadPasswordConfig = async () => {
    try {
      passwordConfig.value = await getPasswordConfigWithFallback();
      configLoaded.value = true;
      configError.value = '';
    } catch (error) {
      configError.value = '配置加载失败';
      configLoaded.value = false;
    }
  };

  // 组件初始化时加载配置
  onMounted(() => {
    loadPasswordConfig();
  });

  return {
    // 基础状态
    lengthValid,
    uppercaseValid,
    lowercaseValid,
    numberValid,
    specialCharValid,
    containsUsername,
    currentPassword,
    passwordConfig,
    configLoaded,
    configError,

    // 计算属性
    minTypesMet,
    allBasicRulesMet,
    strengthScore,
    strengthLevel,
    strengthColor,
    passwordRules,

    // 方法
    checkPasswordStrengthForUI, // 明确标注为UI用途
    createBasicPasswordRules, // 基础前端规则
    resetPasswordStrength,
    loadPasswordConfig,
    getRuleIcon
  };
}
