import { useState, useEffect } from 'react'
import { useUserProfile, updateAccountName, updatePassword } from '@/service/account'

function ProfileModal({ onClose }) {
  // 加载用户信息
  const [userProfile, setUserProfile] = useState(null)
  const [loadingProfile, setLoadingProfile] = useState(false)

  useEffect(() => {
    loadUserProfile()
  }, [])

  const loadUserProfile = async () => {
    setLoadingProfile(true)
    try {
      const response = await useUserProfile()
      setUserProfile(response)
    } catch (error) {
      console.error('Failed to load user profile:', error)
    } finally {
      setLoadingProfile(false)
    }
  }



  // 更新用户名
  const [editingName, setEditingName] = useState(false)
  const [newName, setNewName] = useState('')

  const handleEditName = () => {
    setNewName(userProfile?.name || '')
    setEditingName(true)
  }

  const handleSaveName = async () => {
    if (!newName.trim()) {
      alert('用户名不能为空')
      return
    }
    try {
      const response = await updateAccountName(newName)
      setUserProfile(response)
      setEditingName(false)
      alert('用户名更新成功')
    } catch (error) {
      console.error('Failed to update name:', error)
      alert('更新用户名失败')
    }
  }

  // 更新密码
  const [showPasswordForm, setShowPasswordForm] = useState(false)
  const [currentPassword, setCurrentPassword] = useState('')
  const [newPassword, setNewPassword] = useState('')
  const [repeatPassword, setRepeatPassword] = useState('')
  const [updatingPassword, setUpdatingPassword] = useState(false)

  const handleUpdatePassword = async () => {
    if (newPassword !== repeatPassword) {
      alert('两次输入的新密码不一致')
      return
    }
    if (newPassword.length < 8) {
      alert('新密码长度至少8位')
      return
    }
    setUpdatingPassword(true)
    try {
      await updatePassword(currentPassword, newPassword, repeatPassword)
      alert('密码更新成功')
      setCurrentPassword('')
      setNewPassword('')
      setRepeatPassword('')
      setShowPasswordForm(false)
    } catch (error) {
      console.error('Failed to update password:', error)
      alert('更新密码失败')
    } finally {
      setUpdatingPassword(false)
    }
  }

  return (
    <div className="profile-modal-overlay" onClick={onClose}>
      <div className="profile-modal" onClick={e => e.stopPropagation()}>
        <div className="profile-modal-header">
          <h2>个人信息</h2>
          <button className="profile-close-btn" onClick={onClose}>✕</button>
        </div>

        <div className="profile-tab-content">
          <div className="account-info">
            <div className="account-avatar-section">
              <div className="account-avatar">👤</div>
              {editingName ? (
                <div className="account-name-edit">
                  <input
                    type="text"
                    value={newName}
                    onChange={(e) => setNewName(e.target.value)}
                    className="account-name-input"
                    minLength={3}
                    maxLength={30}
                  />
                  <div className="account-name-actions">
                    <button onClick={handleSaveName} className="account-name-btn save">保存</button>
                    <button onClick={() => setEditingName(false)} className="account-name-btn cancel">取消</button>
                  </div>
                </div>
              ) : (
                <div className="account-name-edit">
                  <div className="account-name">{userProfile?.name || '用户'}</div>
                  <button onClick={handleEditName} className="account-name-edit-btn">编辑</button>
                </div>
              )}
            </div>
            <div className="account-field">
              <label>邮箱</label>
              <input type="email" value={userProfile?.email || ''} readOnly />
            </div>
            <div className="account-field">
              <label>个人数据</label>
              <input type="text" value={`创建于: ${userProfile?.created_at ? new Date(userProfile.created_at * 1000).toLocaleDateString() : '未知'}`} readOnly />
            </div>
            
            <div className="account-password-section">
              <div className="account-password-title">密码管理</div>
              {showPasswordForm ? (
                <div className="account-password-form">
                  <div className="account-password-field">
                    <label>当前密码</label>
                    <input
                      type="password"
                      value={currentPassword}
                      onChange={(e) => setCurrentPassword(e.target.value)}
                      placeholder="请输入当前密码"
                    />
                  </div>
                  <div className="account-password-field">
                    <label>新密码</label>
                    <input
                      type="password"
                      value={newPassword}
                      onChange={(e) => setNewPassword(e.target.value)}
                      placeholder="请输入新密码（至少8位）"
                    />
                  </div>
                  <div className="account-password-field">
                    <label>确认新密码</label>
                    <input
                      type="password"
                      value={repeatPassword}
                      onChange={(e) => setRepeatPassword(e.target.value)}
                      placeholder="请再次输入新密码"
                    />
                  </div>
                  <div className="account-password-actions">
                    <button 
                      className="account-password-btn save" 
                      onClick={handleUpdatePassword}
                      disabled={updatingPassword}
                    >
                      {updatingPassword ? '保存中...' : '保存'}
                    </button>
                    <button 
                      className="account-password-btn cancel" 
                      onClick={() => {
                        setShowPasswordForm(false)
                        setCurrentPassword('')
                        setNewPassword('')
                        setRepeatPassword('')
                      }}
                    >
                      取消
                    </button>
                  </div>
                </div>
              ) : (
                <button 
                  className="account-action-btn"
                  onClick={() => setShowPasswordForm(true)}
                >
                  更改密码
                </button>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

export default ProfileModal