import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { User, Mail, Phone, Building2, Shield, Calendar, Edit2, Save, Lock, Eye, EyeOff, ArrowLeft, Check, X } from 'lucide-react';
import { toast } from 'sonner';
import { getUserProfile, updateUserProfile, updateUserPassword, ProfileVO } from '../api/user/profile';
import { formatDate } from '../utils/formatTime';
import { getPermissionInfo, setPermissionInfo } from '../utils/permission';
import { fileApi } from '../api/file';
import { clearAuth } from '../utils/auth';

/** 传给父组件的增量更新，只传有变化的字段，避免整页刷新/抖动 */
export type ProfileUpdatePayload = { avatar?: string; nickname?: string; email?: string };

interface ProfileSettingsProps {
  onBack: () => void;
  /** 个人资料或头像更新后调用，传入变更字段即可，父组件仅合并 state 不重读存储 */
  onProfileUpdated?: (updates: ProfileUpdatePayload) => void;
}

export default function ProfileSettings({ onBack, onProfileUpdated }: ProfileSettingsProps) {
  const navigate = useNavigate();
  const { t } = useTranslation();
  // 用户信息显示
  const [userInfo, setUserInfo] = useState<ProfileVO | null>(null);
  const [loading, setLoading] = useState(true);

  // 编辑信息状态
  const [nickname, setNickname] = useState('');
  const [phone, setPhone] = useState('');
  const [email, setEmail] = useState('');
  const [gender, setGender] = useState<number>(1); // 1: 男, 2: 女
  const [avatar, setAvatar] = useState('');
  const [uploadingAvatar, setUploadingAvatar] = useState(false);

  // 密码设置状态
  const [oldPassword, setOldPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showOldPassword, setShowOldPassword] = useState(false);
  const [showNewPassword, setShowNewPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

  // 密码匹配检查
  const passwordMatch = confirmPassword.length > 0 && newPassword === confirmPassword;
  const passwordMismatch = confirmPassword.length > 0 && newPassword !== confirmPassword;

  // 表单验证错误
  const [errors, setErrors] = useState<{
    nickname?: string;
    phone?: string;
    email?: string;
  }>({});

  // 加载用户信息
  const loadUserInfo = async () => {
    try {
      setLoading(true);
      const profile = await getUserProfile();
      setUserInfo(profile);
      setNickname(profile.nickname || '');
      setPhone(profile.mobile || '');
      setEmail(profile.email || '');
      setGender(profile.sex || 1);
      setAvatar(profile.avatar || '');
    } catch (error: any) {
      toast.error(error.message || t('profile.getUserInfoFailed'));
    } finally {
      setLoading(false);
    }
  };

  // 组件挂载时加载数据
  useEffect(() => {
    loadUserInfo();
  }, []);

  // 表单验证
  const validateForm = (): boolean => {
    const newErrors: typeof errors = {};

    if (!nickname.trim()) {
      newErrors.nickname = t('profile.usernameRequired');
    }

    if (!phone.trim()) {
      newErrors.phone = t('profile.mobileRequired');
    } else if (!/^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(phone)) {
      newErrors.phone = t('profile.mobileInvalid');
    }

    if (!email.trim()) {
      newErrors.email = t('profile.emailRequired');
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      newErrors.email = t('profile.emailInvalid');
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };


  // 保存个人信息
  const handleSaveInfo = async () => {
    if (!validateForm()) {
      return;
    }

    try {
      await updateUserProfile({
        nickname: nickname.trim(),
        mobile: phone.trim(),
        email: email.trim(),
        sex: gender,
        avatar: avatar,
      });

      toast.success(t('profile.saveSuccess'));
      
      // 重新加载用户信息
      await loadUserInfo();

      // 更新本地存储的用户信息
      const permissionInfo = getPermissionInfo();
      if (permissionInfo && permissionInfo.user) {
        const updatedPermissionInfo = {
          ...permissionInfo,
          user: {
            ...permissionInfo.user,
            nickname: nickname.trim(),
            avatar: avatar,
            email: email.trim(),
          },
        };
        setPermissionInfo(updatedPermissionInfo);
        onProfileUpdated?.({ avatar, nickname: nickname.trim(), email: email.trim() });
      }
    } catch (error: any) {
      toast.error(error.message || t('profile.saveFailed'));
    }
  };

  // 保存密码
  const handleSavePassword = async () => {
    if (!oldPassword) {
      toast.error(t('profile.oldPasswordRequired'));
      return;
    }

    if (!newPassword) {
      toast.error(t('profile.newPasswordRequired'));
      return;
    }

    if (newPassword.length < 6 || newPassword.length > 20) {
      toast.error(t('profile.newPasswordLengthError'));
      return;
    }

    if (newPassword !== confirmPassword) {
      toast.error(t('profile.passwordMismatch'));
      return;
    }

    try {
      await updateUserPassword(oldPassword, newPassword);
      console.log('修改密码API调用成功');
      
      // 显示成功提示
      toast.success(t('profile.passwordChangeSuccess'), {
        duration: 3000,
      });
      
      // 延迟一下，让用户看到成功提示，然后清除认证信息并跳转到登录页面
      setTimeout(() => {
        // 清除所有认证信息
        clearAuth();
        // 跳转到登录页面
        navigate('/login');
      }, 1500);
    } catch (error: any) {
      console.error('修改密码失败:', error);
      const errorMsg = error?.response?.data?.msg || error?.message || t('profile.passwordChangeFailed');
      toast.error(errorMsg, {
        duration: 3000,
      });
    }
  };

  // 处理头像上传
  const handleAvatarUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      toast.error(t('profile.selectImageFile'));
      return;
    }

    // 检查文件大小 (限制为5MB)
    if (file.size > 5 * 1024 * 1024) {
      toast.error(t('profile.imageSizeLimit'));
      return;
    }

    setUploadingAvatar(true);
    try {
      const fileUrl = await fileApi.upload(file);
      setAvatar(fileUrl);
      
      // 立即保存头像
      await updateUserProfile({
        avatar: fileUrl,
      });

      toast.success(t('profile.avatarUploadSuccess'));
      
      // 重新加载用户信息
      await loadUserInfo();

      // 更新本地存储的用户信息
      const permissionInfo = getPermissionInfo();
      if (permissionInfo && permissionInfo.user) {
        const updatedPermissionInfo = {
          ...permissionInfo,
          user: {
            ...permissionInfo.user,
            avatar: fileUrl,
          },
        };
        setPermissionInfo(updatedPermissionInfo);
        onProfileUpdated?.({ avatar: fileUrl });
      }
    } catch (error: any) {
      toast.error(error.message || t('profile.avatarUploadFailed'));
    } finally {
      setUploadingAvatar(false);
      // 清空文件输入
      e.target.value = '';
    }
  };

  if (loading) {
    return (
      <div className="h-full flex items-center justify-center">
        <div className="text-center">
          <div className="w-12 h-12 border-4 border-blue-500 border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-gray-600">{t('profile.loading')}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="h-full">
      <div className="max-w-7xl mx-auto space-y-6 pb-6">
        {/* 返回按钮 */}
        <div className="flex items-center justify-between">
          <h2 className="text-xl text-gray-900">{t('profile.title')}</h2>
          <button
            onClick={onBack}
            className="flex items-center gap-2 px-5 py-3 text-base font-medium text-gray-700 hover:text-blue-600 hover:bg-blue-50 rounded-xl transition-colors border border-gray-200 hover:border-blue-300"
          >
            <ArrowLeft className="w-5 h-5" />
            <span>{t('profile.back')}</span>
          </button>
        </div>

        {/* 用户卡片 - 全新设计 */}
        <div className="bg-gradient-to-br from-blue-500 to-blue-600 rounded-3xl p-8 shadow-xl shadow-blue-500/20">
          <div className="flex items-center gap-8">
            {/* 头像 */}
            <div className="relative group">
              {avatar ? (
                <div className="w-28 h-28 bg-white/20 backdrop-blur-sm rounded-2xl flex items-center justify-center shadow-lg border-4 border-white/30 overflow-hidden">
                  <img 
                    src={avatar} 
                    alt={t('profile.avatarAlt')} 
                    className="w-full h-full object-cover"
                    onError={(e) => {
                      (e.target as HTMLImageElement).style.display = 'none';
                    }}
                  />
                </div>
              ) : (
                <div className="w-28 h-28 bg-white/20 backdrop-blur-sm rounded-2xl flex items-center justify-center shadow-lg border-4 border-white/30">
                  <User className="w-14 h-14 text-white" strokeWidth={2} />
                </div>
              )}
              <label className="absolute -bottom-2 -right-2 w-10 h-10 bg-white rounded-xl shadow-lg flex items-center justify-center text-blue-600 hover:bg-blue-50 transition-all cursor-pointer">
                <input
                  type="file"
                  accept="image/*"
                  onChange={handleAvatarUpload}
                  className="hidden"
                  disabled={uploadingAvatar}
                />
                {uploadingAvatar ? (
                  <div className="w-4 h-4 border-2 border-blue-600 border-t-transparent rounded-full animate-spin" />
                ) : (
                  <Edit2 className="w-4 h-4" />
                )}
              </label>
            </div>

            {/* 用户信息 */}
            <div className="flex-1">
              {loading ? (
                <div className="text-white">{t('profile.loading')}</div>
              ) : userInfo ? (
                <>
                  <h3 className="text-3xl text-white mb-2">{(userInfo.nickname || userInfo.username) || t('profile.user')}</h3>
                  <p className="text-blue-100 text-sm mb-4">@{userInfo.username || 'username'}</p>
                  
                  <div className="grid grid-cols-3 gap-6">
                    <div className="flex items-center gap-2 text-white/90">
                      <Building2 className="w-4 h-4" />
                      <span className="text-sm">{(userInfo.dept && userInfo.dept.name) ? userInfo.dept.name : '-'}</span>
                    </div>
                    <div className="flex items-center gap-2 text-white/90">
                      <Shield className="w-4 h-4" />
                      <span className="text-sm">
                        {userInfo.roles && Array.isArray(userInfo.roles) && userInfo.roles.length > 0 
                          ? userInfo.roles.filter(r => r && r.name).map(r => r.name).join(', ')
                          : '-'}
                      </span>
                    </div>
                    <div className="flex items-center gap-2 text-white/90">
                      <Calendar className="w-4 h-4" />
                      <span className="text-sm">
                        {userInfo.createTime ? formatDate(userInfo.createTime, 'date') : '-'}
                      </span>
                    </div>
                  </div>
                </>
              ) : (
                <div className="text-white">{t('profile.loadFailed')}</div>
              )}
            </div>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* 个人信息编辑 */}
          <div className="bg-white rounded-2xl border border-gray-200/50 shadow-sm overflow-hidden">
            <div className="bg-gradient-to-r from-blue-50 to-indigo-50 px-6 py-4 border-b border-gray-200/50">
              <h3 className="text-lg text-gray-900 flex items-center gap-2">
                <Edit2 className="w-5 h-5 text-blue-600" />
                {t('profile.editPersonalInfo')}
              </h3>
            </div>

            <div className="p-6 space-y-5">
              {/* 昵称 */}
              <div>
                <label className="block text-sm text-gray-700 mb-2">{t('profile.username')} <span className="text-red-500">*</span></label>
                <input
                  type="text"
                  value={nickname}
                  onChange={(e) => {
                    setNickname(e.target.value);
                    if (errors.nickname) {
                      setErrors(prev => ({ ...prev, nickname: undefined }));
                    }
                  }}
                  className={`w-full px-4 py-3 border rounded-xl focus:outline-none focus:ring-2 transition-all text-sm ${
                    errors.nickname 
                      ? 'border-red-500 focus:ring-red-500/50 focus:border-red-500' 
                      : 'border-gray-200 focus:ring-blue-500/50 focus:border-blue-500'
                  }`}
                  placeholder={t('profile.nicknamePlaceholder')}
                />
                {errors.nickname && (
                  <p className="mt-1 text-xs text-red-500">{errors.nickname}</p>
                )}
              </div>

              {/* 手机号 */}
              <div>
                <label className="block text-sm text-gray-700 mb-2">{t('profile.mobile')} <span className="text-red-500">*</span></label>
                <div className="relative">
                  <Phone className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <input
                    type="tel"
                    value={phone}
                    onChange={(e) => {
                      setPhone(e.target.value);
                      if (errors.phone) {
                        setErrors(prev => ({ ...prev, phone: undefined }));
                      }
                    }}
                    className={`w-full px-4 py-3 pl-11 border rounded-xl focus:outline-none focus:ring-2 transition-all text-sm ${
                      errors.phone 
                        ? 'border-red-500 focus:ring-red-500/50 focus:border-red-500' 
                        : 'border-gray-200 focus:ring-blue-500/50 focus:border-blue-500'
                    }`}
                    placeholder={t('form.mobilePlaceholder')}
                  />
                </div>
                {errors.phone && (
                  <p className="mt-1 text-xs text-red-500">{errors.phone}</p>
                )}
              </div>

              {/* 邮箱 */}
              <div>
                <label className="block text-sm text-gray-700 mb-2">{t('profile.email')} <span className="text-red-500">*</span></label>
                <div className="relative">
                  <Mail className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <input
                    type="email"
                    value={email}
                    onChange={(e) => {
                      setEmail(e.target.value);
                      if (errors.email) {
                        setErrors(prev => ({ ...prev, email: undefined }));
                      }
                    }}
                    className={`w-full px-4 py-3 pl-11 border rounded-xl focus:outline-none focus:ring-2 transition-all text-sm ${
                      errors.email 
                        ? 'border-red-500 focus:ring-red-500/50 focus:border-red-500' 
                        : 'border-gray-200 focus:ring-blue-500/50 focus:border-blue-500'
                    }`}
                    placeholder={t('form.deptEmailPlaceholder')}
                  />
                </div>
                {errors.email && (
                  <p className="mt-1 text-xs text-red-500">{errors.email}</p>
                )}
              </div>

              {/* 性别 */}
              <div>
                <label className="block text-sm text-gray-700 mb-3">{t('profile.gender')}</label>
                <div className="flex gap-3">
                  <label className={`flex-1 flex items-center justify-center gap-2 px-4 py-3 rounded-xl cursor-pointer transition-all border-2 ${
                    gender === 1 
                      ? 'bg-blue-50 border-blue-500 text-blue-700' 
                      : 'bg-gray-50 border-gray-200 text-gray-600 hover:border-gray-300'
                  }`}>
                    <input
                      type="radio"
                      name="gender"
                      value="1"
                      checked={gender === 1}
                      onChange={(e) => setGender(Number(e.target.value))}
                      className="hidden"
                    />
                    <span className="text-sm">👨 {t('profile.male')}</span>
                  </label>
                  <label className={`flex-1 flex items-center justify-center gap-2 px-4 py-3 rounded-xl cursor-pointer transition-all border-2 ${
                    gender === 2 
                      ? 'bg-pink-50 border-pink-500 text-pink-700' 
                      : 'bg-gray-50 border-gray-200 text-gray-600 hover:border-gray-300'
                  }`}>
                    <input
                      type="radio"
                      name="gender"
                      value="2"
                      checked={gender === 2}
                      onChange={(e) => setGender(Number(e.target.value))}
                      className="hidden"
                    />
                    <span className="text-sm">👩 {t('profile.female')}</span>
                  </label>
                </div>
              </div>

              {/* 操作按钮 */}
              <div className="flex justify-center pt-2">
                <button
                  onClick={handleSaveInfo}
                  className="flex items-center justify-center gap-2 px-16 py-3 w-48 bg-gradient-to-r from-blue-500 to-blue-600 text-white rounded-xl hover:shadow-lg hover:shadow-blue-400/40 transition-all"
                >
                  <Save className="w-4 h-4 text-white" />
                  <span className="text-sm text-white">{t('profile.saveChanges')}</span>
                </button>
              </div>
            </div>
          </div>

          {/* 密码设置 - 全新设计 */}
          <div className="bg-white rounded-2xl border border-gray-200/50 shadow-sm overflow-hidden">
            <div className="bg-gradient-to-r from-purple-50 to-pink-50 px-6 py-4 border-b border-gray-200/50">
              <h3 className="text-lg text-gray-900 flex items-center gap-2">
                <Lock className="w-5 h-5 text-purple-600" />
                {t('profile.passwordSettings')}
              </h3>
            </div>

            <div className="p-6 space-y-5">
              {/* 旧密码 */}
              <div>
                <label className="block text-sm text-gray-700 mb-2">{t('profile.oldPassword')}</label>
                <div className="relative">
                  <Lock className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <input
                    type={showOldPassword ? 'text' : 'password'}
                    value={oldPassword}
                    onChange={(e) => setOldPassword(e.target.value)}
                    className="w-full px-4 py-3 pl-11 pr-12 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500 transition-all text-sm"
                    placeholder={t('profile.oldPasswordPlaceholder')}
                  />
                  <button
                    type="button"
                    onClick={() => setShowOldPassword(!showOldPassword)}
                    className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                  >
                    {showOldPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                  </button>
                </div>
              </div>

              {/* 新密码 */}
              <div>
                <label className="block text-sm text-gray-700 mb-2">{t('profile.newPassword')}</label>
                <div className="relative">
                  <Lock className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <input
                    type={showNewPassword ? 'text' : 'password'}
                    value={newPassword}
                    onChange={(e) => setNewPassword(e.target.value)}
                    className="w-full px-4 py-3 pl-11 pr-12 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-purple-500/50 focus:border-purple-500 transition-all text-sm"
                    placeholder={t('profile.newPasswordPlaceholder')}
                  />
                  <button
                    type="button"
                    onClick={() => setShowNewPassword(!showNewPassword)}
                    className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                  >
                    {showNewPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                  </button>
                </div>
              </div>

              {/* 确认密码 */}
              <div>
                <label className="block text-sm text-gray-700 mb-2">{t('profile.confirmPassword')}</label>
                <div className="relative">
                  <Lock className="absolute left-4 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <input
                    type={showConfirmPassword ? 'text' : 'password'}
                    value={confirmPassword}
                    onChange={(e) => setConfirmPassword(e.target.value)}
                    className={`w-full px-4 py-3 pl-11 pr-12 border rounded-xl focus:outline-none focus:ring-2 transition-all text-sm ${
                      passwordMatch ? 'border-green-500 focus:ring-green-500/50 focus:border-green-500' :
                      passwordMismatch ? 'border-red-500 focus:ring-red-500/50 focus:border-red-500' :
                      'border-gray-200 focus:ring-purple-500/50 focus:border-purple-500'
                    }`}
                    placeholder={t('profile.confirmPasswordPlaceholder')}
                  />
                  <button
                    type="button"
                    onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                    className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                  >
                    {showConfirmPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                  </button>
                </div>
                
                {/* 密码匹配提示 - 始终显示 */}
                <div className={`mt-2 text-xs flex items-center gap-1.5 ${
                  passwordMatch ? 'text-green-600' :
                  passwordMismatch ? 'text-red-600' :
                  'text-gray-400'
                }`}>
                  {passwordMatch ? (
                    <>
                      <Check className="w-3.5 h-3.5" />
                      <span>{t('profile.passwordMatch')}</span>
                    </>
                  ) : passwordMismatch ? (
                    <>
                      <X className="w-3.5 h-3.5" />
                      <span>{t('profile.passwordMismatch')}</span>
                    </>
                  ) : (
                    <span>{t('profile.confirmPasswordHint')}</span>
                  )}
                </div>
              </div>

              {/* 保存密码按钮 */}
              <div className="pt-2">
                <button
                  onClick={handleSavePassword}
                  disabled={Boolean((newPassword || confirmPassword) && (!newPassword || !confirmPassword || newPassword !== confirmPassword))}
                  className="w-full flex items-center justify-center gap-2 px-6 py-3 bg-gradient-to-r from-purple-500 to-pink-600 text-white rounded-xl hover:shadow-lg hover:shadow-purple-400/40 transition-all disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:shadow-none"
                >
                  <Lock className="w-4 h-4 text-white" />
                  <span className="text-sm text-white">{t('profile.changePassword')}</span>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}