import React, { useState, useEffect, useRef } from 'react'
import { BsX, BsChevronDown } from 'react-icons/bs'
import './Login.css'
import logo from '../assets/logo.png'
import { api } from '../services/api'
import { logger } from '../utils/logger'

interface LoginProps {
  onLogin: (token: string, user?: { id: number; [key: string]: any }) => void
  /** 会话过期等提示，展示在表单上方 */
  bannerMessage?: string
}

interface SavedAccount {
  mobile: string
  password?: string
  lastLoginTime: number
}

const Login: React.FC<LoginProps> = ({ onLogin, bannerMessage }) => {
  const [loginType, setLoginType] = useState<'password' | 'sms'>('sms')
  const [mobile, setMobile] = useState('')
  const [password, setPassword] = useState('')
  const [smsCode, setSmsCode] = useState('')
  const [error, setError] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  
  // 验证码倒计时
  const [countdown, setCountdown] = useState(0)
  
  // 历史账号
  const [savedAccounts, setSavedAccounts] = useState<SavedAccount[]>([])
  const [showHistory, setShowHistory] = useState(false)
  const [rememberPassword, setRememberPassword] = useState(true)

  const historyRef = useRef<HTMLDivElement>(null)

  // 初始化加载历史账号
  useEffect(() => {
    const history = localStorage.getItem('login_history')
    if (history) {
      try {
        const accounts: SavedAccount[] = JSON.parse(history)
        // 按最后登录时间排序
        accounts.sort((a, b) => b.lastLoginTime - a.lastLoginTime)
        setSavedAccounts(accounts)
        
        // 自动填充最近一次登录的账号
        if (accounts.length > 0) {
          const last = accounts[0]
          setMobile(last.mobile)
          if (last.password) {
            setPassword(last.password)
            setRememberPassword(true)
          }
        }
      } catch (e) {
        console.error('Failed to parse login history', e)
      }
    }
    
    // 点击外部关闭下拉框
    const handleClickOutside = (event: MouseEvent) => {
      if (historyRef.current && !historyRef.current.contains(event.target as Node)) {
        setShowHistory(false)
      }
    }
    document.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [])

  // 倒计时逻辑
  useEffect(() => {
    if (countdown > 0) {
      const timer = setTimeout(() => setCountdown(countdown - 1), 1000)
      return () => clearTimeout(timer)
    }
    return () => {}
  }, [countdown])

  const handleSendCode = async () => {
    if (!mobile || mobile.length !== 11) {
      const errorMsg = '请输入正确的手机号码'
      setError(errorMsg)
      logger.warn('Login: Send SMS code validation failed', { 
        mobile, 
        mobileLength: mobile.length,
        reason: 'Invalid mobile format'
      })
      return
    }
    
    logger.info('Login: Send SMS code button clicked', { mobile })
    
    try {
      setError('')
      setIsLoading(true)
      
      logger.info('Login: Calling sendSmsCode API', { mobile })
      await api.sendSmsCode(mobile)
      
      setCountdown(60)
      logger.info('Login: SMS code sent successfully', { mobile })
    } catch (err: any) {
      const errorMsg = err.message || '发送验证码失败'
      setError(errorMsg)
      logger.error('Login: Send SMS code failed', { 
        mobile,
        error: err instanceof Error ? {
          name: err.name,
          message: err.message,
          stack: err.stack
        } : String(err)
      })
    } finally {
      setIsLoading(false)
    }
  }

  const saveAccountToHistory = (mobile: string, pwd?: string) => {
    const newAccount: SavedAccount = {
      mobile,
      password: pwd || '', // 如果不记住密码，则为空
      lastLoginTime: Date.now()
    }
    
    // 过滤掉已存在的同名账号
    const others = savedAccounts.filter(acc => acc.mobile !== mobile)
    const newHistory = [newAccount, ...others].slice(0, 5) // 只保留最近5个
    
    setSavedAccounts(newHistory)
    localStorage.setItem('login_history', JSON.stringify(newHistory))
  }

  const handleDeleteAccount = (e: React.MouseEvent, targetMobile: string) => {
    e.stopPropagation() // 防止触发选择事件
    const newHistory = savedAccounts.filter(acc => acc.mobile !== targetMobile)
    setSavedAccounts(newHistory)
    localStorage.setItem('login_history', JSON.stringify(newHistory))
    
    // 如果删除的是当前输入的账号，清空输入
    if (mobile === targetMobile) {
      setMobile('')
      setPassword('')
    }
  }

  const handleSelectAccount = (acc: SavedAccount) => {
    setMobile(acc.mobile)
    if (acc.password) {
      setPassword(acc.password)
      setLoginType('password')
    }
    setShowHistory(false)
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError('')
    setIsLoading(true)
    
    logger.info('Login: Login form submitted', { 
      mobile, 
      loginType,
      hasPassword: !!password,
      hasSmsCode: !!smsCode,
      rememberPassword
    })

    try {
      let data;
      const loginStartTime = Date.now()
      
      if (loginType === 'password') {
        if (!mobile || !password) {
          const errorMsg = '请输入账号和密码'
          setError(errorMsg)
          logger.warn('Login: Password login validation failed', { 
            mobile, 
            hasPassword: !!password 
          })
          setIsLoading(false)
          return
        }
        
        logger.info('Login: Starting password login', { mobile })
        data = await api.login(mobile, password)
        
        const loginDuration = Date.now() - loginStartTime
        logger.info('Login: Password login API call completed', {
          mobile,
          duration: `${loginDuration}ms`,
          hasToken: !!data?.access_token,
          hasUser: !!data?.user
        })
      } else {
        if (!mobile || !smsCode) {
          const errorMsg = '请输入手机号和验证码'
          setError(errorMsg)
          logger.warn('Login: SMS login validation failed', { 
            mobile, 
            hasSmsCode: !!smsCode 
          })
          setIsLoading(false)
          return
        }
        
        logger.info('Login: Starting SMS login', { mobile, codeLength: smsCode.length })
        data = await api.loginBySms(mobile, smsCode)
        
        const loginDuration = Date.now() - loginStartTime
        logger.info('Login: SMS login API call completed', {
          mobile,
          duration: `${loginDuration}ms`,
          hasToken: !!data?.access_token,
          hasUser: !!data?.user
        })
      }
      
      setIsLoading(false)
      
      logger.info('Login: Login successful, processing response', { 
        mobile,
        hasToken: !!data?.access_token,
        userId: data?.user?.id,
        userName: data?.user?.name || data?.user?.full_name
      })
      
      // 保存登录成功的账号信息
      saveAccountToHistory(mobile, (loginType === 'password' && rememberPassword) ? password : undefined)
      logger.info('Login: Account saved to history', { mobile, rememberPassword })

      // 通知 Electron 主进程（可选）
      if (window.electron && window.electron.ipcRenderer) {
        window.electron.ipcRenderer.send('login-success')
        logger.info('Login: Sent login-success event to Electron main process')
      }
      
      // 传递 token 和用户信息给上层
      logger.info('Login: Calling onLogin callback', {
        mobile,
        hasToken: !!data?.access_token,
        hasUser: !!data?.user
      })
      onLogin(data.access_token, data.user)
      
      logger.info('Login: Login flow completed successfully', { 
        mobile,
        userId: data?.user?.id
      })

    } catch (err: any) {
      setIsLoading(false)
      const errorMsg = err.message || '登录失败'
      setError(errorMsg)
      
      logger.error('Login: Login failed', { 
        mobile,
        loginType,
        error: err instanceof Error ? {
          name: err.name,
          message: err.message,
          stack: err.stack
        } : String(err),
        errorMessage: errorMsg
      })
    }
  }

  return (
    <div className="login-wrapper">
      <div className="login-content">
        <div className="login-header">
           <img src={logo} alt="Logo" className="login-avatar" />
        </div>

        {bannerMessage ? (
          <div className="login-banner" role="alert">
            {bannerMessage}
          </div>
        ) : null}

        {/* Tab 切换 */}
        <div className="login-tabs">
          <div 
            className={`tab-item ${loginType === 'password' ? 'active' : ''}`}
            onClick={() => { setLoginType('password'); setError('') }}
          >
            密码登录
          </div>
          <div 
            className={`tab-item ${loginType === 'sms' ? 'active' : ''}`}
            onClick={() => { setLoginType('sms'); setError('') }}
          >
            验证码登录
          </div>
        </div>

        <form onSubmit={handleSubmit} className="login-form">
          {/* 手机号输入框 + 历史记录下拉 */}
          <div className="input-group" style={{ position: 'relative' }} ref={historyRef}>
            <input
              type="text"
              placeholder="手机号码"
              className="login-input"
              value={mobile}
              onChange={(e) => setMobile(e.target.value)}
              onFocus={() => setShowHistory(true)}
              disabled={isLoading}
              style={{ textAlign: 'left', paddingRight: '30px' }}
            />
            {savedAccounts.length > 0 && (
              <div 
                className="toggle-history-btn"
                onClick={() => setShowHistory(!showHistory)}
              >
                <BsChevronDown />
              </div>
            )}
            
            {/* 历史账号列表 */}
            {showHistory && savedAccounts.length > 0 && (
              <div className="history-dropdown">
                {savedAccounts.map((acc) => (
                  <div 
                    key={acc.mobile} 
                    className="history-item"
                    onClick={() => handleSelectAccount(acc)}
                  >
                    <div className="history-info">
                      <span className="history-mobile">{acc.mobile}</span>
                    </div>
                    <div 
                      className="history-delete"
                      onClick={(e) => handleDeleteAccount(e, acc.mobile)}
                      title="删除记录"
                    >
                      <BsX size={16} />
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
          
          {loginType === 'password' ? (
            <div className="input-group">
              <input
                type="password"
                placeholder="密码"
                className="login-input"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                disabled={isLoading}
                style={{ textAlign: 'left' }}
              />
            </div>
          ) : (
            <div className="input-group input-with-button">
              <input
                type="text"
                placeholder="验证码"
                className="login-input"
                value={smsCode}
                onChange={(e) => setSmsCode(e.target.value)}
                disabled={isLoading}
                style={{ textAlign: 'left' }}
              />
              <button 
                type="button"
                className="verify-button"
                onClick={handleSendCode}
                disabled={countdown > 0 || !mobile || isLoading}
              >
                {countdown > 0 ? `${countdown}s 后重发` : '获取验证码'}
              </button>
            </div>
          )}

          {loginType === 'password' && (
            <label className="remember-me">
              <input 
                type="checkbox" 
                checked={rememberPassword}
                onChange={(e) => setRememberPassword(e.target.checked)}
              />
              记住密码
            </label>
          )}

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

          <button type="submit" className="login-button" disabled={isLoading}>
            {isLoading ? '登录中...' : '登录'}
          </button>
        </form>

        <div className="login-footer">
          {/* <span className="footer-link">切换账号</span> */}
        </div>
      </div>
    </div>
  )
}

export default Login
