import React, { useState,useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { getUserInfo, updatePassword } from '../../api/personal';
import './personalSubpage.css';

const Setting = ({ onLogout }) => {
  const navigate = useNavigate();
  const location = useLocation();
  const [userInfo, setUserInfo] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [success, setSuccess] = useState(null);
  const [passwordForm, setPasswordForm] = useState({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  });

  // 获取用户信息
  useEffect(() => {
    const fetchUserInfo = async () => {
      try {
        const info = await getUserInfo();
        setUserInfo(info);
      } catch (err) {
        console.error('获取用户信息失败:', err);
      }
    };
    fetchUserInfo();
  }, []);

  const handleBack = () => {
    navigate('/personal', { 
      state: { 
        fromSubpage: true,
        dashboardTab: location.state?.dashboardTab
      },
      replace: true
    });
  };

  const handlePasswordChange = (e) => {
    const { name, value } = e.target;
    setPasswordForm(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handlePasswordSubmit = async (e) => {
    e.preventDefault();
    setError(null);
    setSuccess(null);

    // 验证表单
    if (!passwordForm.oldPassword || !passwordForm.newPassword || !passwordForm.confirmPassword) {
      setError('请填写所有密码字段');
      return;
    }

    if (passwordForm.newPassword !== passwordForm.confirmPassword) {
      setError('新密码与确认密码不一致');
      return;
    }

    if (passwordForm.newPassword.length < 6) {
      setError('新密码长度至少为6位');
      return;
    }

    try {
      setLoading(true);
      await updatePassword(passwordForm.oldPassword, passwordForm.newPassword);
      setSuccess('密码修改成功');
      setPasswordForm({
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      });
    } catch (err) {
      setError(err.message || '修改密码失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="subpage-container">
      <button className="back-button" onClick={handleBack}>
        ← 返回个人中心
      </button>

      <h2 className="page-title">个人设置</h2>

      <div className="setting-section">
        <div className="user-info-card">
          <h3>账户信息</h3>
          <div className="info-item">
            <label>用户名:</label>
            <span>{userInfo?.username || '加载中...'}</span>
          </div>
          <p className="info-note">用户名不可更改</p>
        </div>

        <div className="password-form-card">
          <h3>修改密码</h3>
          <form onSubmit={handlePasswordSubmit}>
            <div className="form-group">
              <label htmlFor="oldPassword">原密码:</label>
              <input
                type="password"
                id="oldPassword"
                name="oldPassword"
                value={passwordForm.oldPassword}
                onChange={handlePasswordChange}
                required
              />
            </div>

            <div className="form-group">
              <label htmlFor="newPassword">新密码:</label>
              <input
                type="password"
                id="newPassword"
                name="newPassword"
                value={passwordForm.newPassword}
                onChange={handlePasswordChange}
                required
                minLength="6"
              />
            </div>

            <div className="form-group">
              <label htmlFor="confirmPassword">确认新密码:</label>
              <input
                type="password"
                id="confirmPassword"
                name="confirmPassword"
                value={passwordForm.confirmPassword}
                onChange={handlePasswordChange}
                required
                minLength="6"
              />
            </div>

            {error && <div className="error-message">{error}</div>}
            {success && <div className="success-message">{success}</div>}

            <button 
              type="submit" 
              className="submit-button"
              disabled={loading}
            >
              {loading ? '处理中...' : '修改密码'}
            </button>
          </form>
        </div>
      </div>
    </div>
  );
};

export default Setting;