/**
 * 员工端自动登录页 — 扫码后通过一次性 token 自动登录，无需输入密码
 */

import { useEffect, useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { Loader2, CheckCircle, AlertCircle } from 'lucide-react'
import { portalApi } from '../../lib/api-services'
import Logo from '../../components/ui/Logo'

export default function AutoLogin() {
  const [params] = useSearchParams()
  const token = params.get('token') || ''
  const navigate = useNavigate()
  const [status, setStatus] = useState<'loading' | 'success' | 'error'>('loading')
  const [errorMsg, setErrorMsg] = useState('')

  useEffect(() => {
    if (!token) {
      setStatus('error')
      setErrorMsg('缺少登录凭证')
      return
    }
    portalApi.autoLogin(token).then((data: any) => {
      if (data?.token) {
        localStorage.setItem('portalToken', data.token)
        localStorage.setItem('portalEmployee', JSON.stringify(data.employee))
        setStatus('success')
        setTimeout(() => navigate('/portal/payslip'), 1000)
      } else {
        setStatus('error')
        setErrorMsg('登录失败，请重试')
      }
    }).catch((err: any) => {
      setStatus('error')
      setErrorMsg(err.response?.data?.error?.message || '登录链接无效或已过期')
    })
  }, [token, navigate])

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50 px-4 pt-safe pb-safe">
      <div className="max-w-sm w-full text-center">
        <div className="flex flex-col items-center justify-center gap-2 mb-8">
          <Logo className="w-10 h-10 object-contain" />
          <span className="text-base font-bold text-center">安职通 — 员工端</span>
        </div>

        {status === 'loading' && (
          <>
            <Loader2 className="w-12 h-12 text-primary animate-spin mx-auto mb-4" />
            <p className="text-sm text-gray-600">正在自动登录...</p>
          </>
        )}

        {status === 'success' && (
          <>
            <CheckCircle className="w-12 h-12 text-green-500 mx-auto mb-4" />
            <p className="text-sm font-medium text-gray-800">登录成功</p>
            <p className="text-xs text-gray-400 mt-1">即将进入工资条页面...</p>
          </>
        )}

        {status === 'error' && (
          <>
            <AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
            <p className="text-sm font-medium text-gray-800 mb-2">登录失败</p>
            <p className="text-xs text-gray-500 mb-4">{errorMsg}</p>
            <button
              onClick={() => navigate('/portal/login')}
              className="text-sm text-primary hover:underline"
            >
              前往手动登录
            </button>
          </>
        )}
      </div>
    </div>
  )
}
