import React, { useState, useEffect } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { toast } from 'sonner'
import { authAPI } from '@/services/api'
import { setUserInfoInCookie, setTokenInCookie } from '@/utils/cookie'
import './BeautifyLoginPage.css'

const BeautifyLoginPage: React.FC = () => {
  const location = useLocation()
  const navigate = useNavigate()
  const [isLoginMode, setIsLoginMode] = useState(true)
  const [formData, setFormData] = useState({
    // 登录字段
    username: '',
    password: '',
    rememberMe: false,
    // 注册字段
    registerUsername: '',
    registerPassword: '',
    confirmPassword: '',
    email: ''
  })
  const [isLoading, setIsLoading] = useState(false)

  // 根据路由决定默认模式
  useEffect(() => {
    if (location.pathname === '/register') {
      setIsLoginMode(false)
    } else {
      setIsLoginMode(true)
    }
  }, [location.pathname])

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value, type, checked } = e.target
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value
    }))
  }

  const handleLoginSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    if (!formData.username || !formData.password) {
      toast.error('请填写用户名和密码')
      return
    }

    setIsLoading(true)

    try {
      const response = await authAPI.login({
        username: formData.username,
        password: formData.password
      })

      if (response.success) {
        // 保存用户信息到cookie
        if (response.data?.user) {
          setUserInfoInCookie(response.data.user)
        }

        // 保存JWT token到cookie
        if (response.data?.tokens?.access_token) {
          setTokenInCookie(response.data.tokens.access_token)
          // 同时也保存到localStorage作为备份
          localStorage.setItem('access_token', response.data.tokens.access_token)
        }
        if (response.data?.tokens?.refresh_token) {
          localStorage.setItem('refresh_token', response.data.tokens.refresh_token)
        }

        if (formData.rememberMe) {
          localStorage.setItem('remember_user', formData.username)
        } else {
          localStorage.removeItem('remember_user')
        }

        toast.success('登录成功！正在跳转...')
        setTimeout(() => {
          navigate('/cloud')
        }, 1000)
      } else {
        toast.error(response.detail?.message || '登录失败')
      }
    } catch (error: any) {
      console.error('Login error:', error)

      // 尝试从错误响应中提取具体错误信息
      let errorMessage = '登录失败，请稍后重试'

      if (error.response?.data) {
        const errorData = error.response.data
        if (errorData.detail?.message) {
          errorMessage = errorData.detail.message
        } else if (errorData.detail?.code) {
          // 根据错误码显示更友好的消息
          switch (errorData.detail.code) {
            case 'INVALID_CREDENTIALS':
              errorMessage = '用户名或密码错误'
              break
            case 'USER_NOT_FOUND':
              errorMessage = '用户不存在'
              break
            default:
              errorMessage = errorData.detail.message || '登录失败'
          }
        }
      }

      toast.error(errorMessage)
    } finally {
      setIsLoading(false)
    }
  }

  const handleRegisterSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    // 基本验证 - 只有两个规则
    if (formData.registerPassword !== formData.confirmPassword) {
      toast.error('两次输入的密码不一致')
      return
    }

    if (formData.registerPassword.length <= 5) {
      toast.error('密码长度必须大于5个字符')
      return
    }

    setIsLoading(true)

    try {
      const response = await authAPI.register({
        username: formData.registerUsername,
        email: formData.email,
        password: formData.registerPassword,
        confirm_password: formData.confirmPassword
      })

      if (response.success) {
        // 保存tokens到localStorage
        if (response.data?.tokens?.access_token) {
          localStorage.setItem('access_token', response.data.tokens.access_token)
        }
        if (response.data?.tokens?.refresh_token) {
          localStorage.setItem('refresh_token', response.data.tokens.refresh_token)
        }

        toast.success('注册成功！正在跳转...')
        setTimeout(() => {
          navigate('/cloud')
        }, 1500)
      } else {
        // 处理API返回的错误
        const errorMessage = response.detail?.message || '注册失败'
        toast.error(errorMessage)
      }
    } catch (error: any) {
      console.error('Registration error:', error)

      // 尝试从错误响应中提取具体错误信息
      let errorMessage = '注册失败，请稍后重试'

      if (error.response?.data) {
        const errorData = error.response.data
        if (errorData.detail?.message) {
          errorMessage = errorData.detail.message
        } else if (errorData.detail?.code) {
          // 根据错误码显示更友好的消息
          switch (errorData.detail.code) {
            case 'USERNAME_EXISTS':
              errorMessage = '用户名已存在'
              break
            case 'CREATION_FAILED':
              errorMessage = '用户创建失败，请检查输入信息'
              break
            default:
              errorMessage = errorData.detail.message || '注册失败'
          }
        } else if (Array.isArray(errorData.detail)) {
          // 处理字段验证错误
          errorMessage = errorData.detail.map((err: any) => err.msg).join(', ')
        }
      }

      toast.error(errorMessage)
    } finally {
      setIsLoading(false)
    }
  }

  const toggleMode = () => {
    setIsLoginMode(!isLoginMode)
    // 清空错误状态
    setIsLoading(false)
  }

  return (
    <div className="beautify-login-container">
      <div className="login-container">
        <div className="logo">
          <i className={`fas ${isLoginMode ? 'fa-cloud' : 'fa-user-plus'}`}></i>
          <h1>{isLoginMode ? 'CloudStorage' : '用户注册'}</h1>
          <p>{isLoginMode ? '安全可靠的云端存储服务' : '创建您的云端存储账户'}</p>
        </div>

        {isLoginMode ? (
          <form onSubmit={handleLoginSubmit}>
            <div className="input-group">
              <i className="fas fa-user"></i>
              <input
                type="text"
                name="username"
                placeholder="用户名或邮箱"
                value={formData.username}
                onChange={handleInputChange}
                required
              />
            </div>

            <div className="input-group">
              <i className="fas fa-lock"></i>
              <input
                type="password"
                name="password"
                placeholder="密码"
                value={formData.password}
                onChange={handleInputChange}
                required
              />
            </div>

            <div className="options">
              <label className="remember-me">
                <input
                  type="checkbox"
                  name="rememberMe"
                  checked={formData.rememberMe}
                  onChange={handleInputChange}
                />
                记住我
              </label>
              <a href="#" className="forgot-password">忘记密码？</a>
            </div>

            <button type="submit" className="login-btn" disabled={isLoading}>
              {isLoading ? (
                <>
                  <i className="fas fa-spinner fa-spin"></i>
                  {' '}登录中...
                </>
              ) : (
                '登录账户'
              )}
            </button>
          </form>
        ) : (
          <form onSubmit={handleRegisterSubmit}>
            <div className="input-group">
              <i className="fas fa-user"></i>
              <input
                type="text"
                name="registerUsername"
                placeholder="账户名"
                value={formData.registerUsername}
                onChange={handleInputChange}
                required
              />
            </div>

            <div className="input-group">
              <i className="fas fa-lock"></i>
              <input
                type="password"
                name="registerPassword"
                placeholder="密码"
                value={formData.registerPassword}
                onChange={handleInputChange}
                required
              />
            </div>

            <div className="input-group">
              <i className="fas fa-lock"></i>
              <input
                type="password"
                name="confirmPassword"
                placeholder="确认密码"
                value={formData.confirmPassword}
                onChange={handleInputChange}
                required
              />
            </div>

            <div className="input-group">
              <i className="fas fa-envelope"></i>
              <input
                type="email"
                name="email"
                placeholder="邮箱地址"
                value={formData.email}
                onChange={handleInputChange}
                required
              />
            </div>

            <button type="submit" className="login-btn" disabled={isLoading}>
              {isLoading ? (
                <>
                  <i className="fas fa-spinner fa-spin"></i>
                  {' '}注册中...
                </>
              ) : (
                '注册账户'
              )}
            </button>
          </form>
        )}

        <div className="divider">
          <span>{isLoginMode ? '新用户？' : '已有账户？'}</span>
        </div>

        <div className="signup-link">
          {isLoginMode ? (
            <>
              还没有账户？
              <a href="#" onClick={(e) => { e.preventDefault(); toggleMode(); }}>
                立即注册
              </a>
            </>
          ) : (
            <>
              已有账户？
              <a href="#" onClick={(e) => { e.preventDefault(); toggleMode(); }}>
                立即登录
              </a>
            </>
          )}
        </div>
      </div>
    </div>
  )
}

export default BeautifyLoginPage