import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAuth } from '@/contexts/AuthContext'
import { encryptPassword } from '@/utils/encryption'
import { setLoggedIn } from '@/utils/auth'
import { emailRegex, API_PREFIX } from '@/config'
import './Login.css'

export default function Login() {
  const navigate = useNavigate()
  const { login } = useAuth()
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [showPassword, setShowPassword] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState('')

  const handleLogin = async (e) => {
    e.preventDefault()
    setError('')

    if (!email) {
      setError('请输入邮箱')
      return
    }
    if (!emailRegex.test(email)) {
      setError('请输入有效的邮箱地址')
      return
    }
    if (!password?.trim()) {
      setError('请输入密码')
      return
    }

    try {
      setIsLoading(true)
      const encryptedPwd = encryptPassword(password)
      
      const response = await fetch(`${API_PREFIX}/login`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email,
          password: encryptedPwd,
          language: 'zh-Hans',
          remember_me: true,
        }),
        credentials: 'include',
      })

      const res = await response.json()

      // 调试：登录响应原始结构（确认 access_token 在不在 body 里）
      console.log('[Login] raw response →', res)

      if (res.result === 'success') {
        // 登录成功，提取 access_token 存到 localStorage
        // Dify 不同版本响应结构：
        //   { result: 'success', data: { access_token, refresh_token, ... } }
        //   { result: 'success', access_token, refresh_token, ... }（挂在根上）
        //   { result: 'success', token: '...' }（少数版本）
        const dataObj = (res.data && typeof res.data === 'object') ? res.data : {}
        const token =
          dataObj.access_token ||
          res.access_token ||
          res.token ||
          ''
        if (token) {
          try { localStorage.setItem('access_token', token) } catch (_) {}
        }
        // 登录成功，设置登录标记
        setLoggedIn()
        login()
        navigate('/')
      } else {
        setError(typeof res.data === 'string' ? res.data : '登录失败')
      }
    } catch (err) {
      console.error('Login error:', err)
      if (err.code === 'authentication_failed') {
        setError('邮箱或密码错误')
      } else {
        setError(err.message || '登录失败，请稍后重试')
      }
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="login-container">
      <div className="login-box">
        <div className="login-header">
          <img src="/logo.png" alt="Logo" className="login-logo" />
          <h1 className="login-title">AI Agent 智能体平台</h1>
          <p className="login-subtitle">登录以继续使用</p>
        </div>

        <form className="login-form" onSubmit={handleLogin}>
          <div className="form-group">
            <label className="form-label">邮箱</label>
            <input
              type="email"
              className="form-input"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="请输入邮箱"
              autoComplete="email"
            />
          </div>

          <div className="form-group">
            <label className="form-label">密码</label>
            <div className="password-input-wrapper">
              <input
                type={showPassword ? 'text' : 'password'}
                className="form-input password-input"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === 'Enter') {
                    handleLogin(e)
                  }
                }}
                placeholder="请输入密码"
                autoComplete="current-password"
              />
              <button
                type="button"
                className="toggle-password-btn"
                onClick={() => setShowPassword(!showPassword)}
              >
                {showPassword ? '👀' : '😝'}
              </button>
            </div>
          </div>

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

          <button
            type="submit"
            className="login-btn"
            disabled={isLoading || !email || !password}
          >
            {isLoading ? '登录中...' : '登录'}
          </button>
        </form>
      </div>

      <div className="bg-decoration bg-decoration-1"></div>
      <div className="bg-decoration bg-decoration-2"></div>
      <div className="bg-decoration bg-decoration-3"></div>
    </div>
  )
}