import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Phone, Lock, ShieldCheck, ArrowRight } from 'lucide-react'
import Logo from '../../components/ui/Logo'
import { portalApi } from '../../lib/api-services'

type LoginMode = 'password' | 'code'

export default function PortalLogin() {
  const navigate = useNavigate()
  const [mode, setMode] = useState<LoginMode>('password')
  const [phone, setPhone] = useState('')
  const [password, setPassword] = useState('')
  const [code, setCode] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)
  const [codeSent, setCodeSent] = useState(false)
  const [displayedCode, setDisplayedCode] = useState('')

  const handlePasswordLogin = async () => {
    setError('')
    setLoading(true)
    try {
      const data = await portalApi.login(phone, password) as any
      localStorage.setItem('portalToken', data.token)
      localStorage.setItem('portalEmployee', JSON.stringify(data.employee))
      navigate('/portal/payslip')
    } catch (err: any) {
      setError(err.response?.data?.error?.message || '登录失败')
    } finally {
      setLoading(false)
    }
  }

  const handleSendCode = async () => {
    setError('')
    try {
      const data = await portalApi.sendCode(phone) as any
      setCodeSent(true)
      setDisplayedCode(data?.code || '')
    } catch (err: any) {
      setError(err.response?.data?.error?.message || '发送失败')
    }
  }

  const handleCodeLogin = async () => {
    setError('')
    setLoading(true)
    try {
      const data = await portalApi.verifyCode(phone, code) as any
      localStorage.setItem('portalToken', data.token)
      localStorage.setItem('portalEmployee', JSON.stringify(data.employee))
      navigate('/portal/payslip')
    } catch (err: any) {
      setError(err.response?.data?.error?.message || '登录失败')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen flex flex-col items-center justify-center bg-gradient-to-b from-blue-50 via-white to-gray-50 px-4 pt-safe pb-safe">
      <div className="w-full max-w-sm">
        {/* Logo & 标题 */}
        <div className="flex flex-col items-center justify-center gap-3 mb-8">
          <div className="w-16 h-16 rounded-2xl bg-white shadow-md flex items-center justify-center">
            <Logo className="w-10 h-10 object-contain" />
          </div>
          <div className="text-center">
            <h1 className="text-xl font-bold text-gray-900">安职通</h1>
            <p className="text-sm text-gray-500 mt-0.5">员工端</p>
          </div>
        </div>

        {/* 登录卡片 */}
        <div className="bg-white rounded-2xl shadow-lg p-6 space-y-5">
          {/* Tab 切换 */}
          <div className="flex bg-gray-100 rounded-xl p-1">
            <button
              onClick={() => { setMode('password'); setError('') }}
              className={`flex-1 py-2.5 text-sm font-medium rounded-lg transition-all ${mode === 'password' ? 'bg-white text-primary shadow-sm' : 'text-gray-500'}`}
            >密码登录</button>
            <button
              onClick={() => { setMode('code'); setError('') }}
              className={`flex-1 py-2.5 text-sm font-medium rounded-lg transition-all ${mode === 'code' ? 'bg-white text-primary shadow-sm' : 'text-gray-500'}`}
            >验证码登录</button>
          </div>

          {error && (
            <div className="px-3 py-2.5 rounded-lg bg-red-50 text-red-600 text-sm flex items-center gap-2">
              <span className="w-1.5 h-1.5 rounded-full bg-red-500 flex-shrink-0" />
              {error}
            </div>
          )}

          {mode === 'password' ? (
            <div className="space-y-4">
              <div className="relative">
                <Phone className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                <input
                  type="tel"
                  placeholder="请输入手机号"
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  maxLength={11}
                  className="w-full h-12 pl-11 pr-4 rounded-xl border border-gray-200 bg-gray-50 text-sm focus:bg-white focus:border-primary focus:ring-1 focus:ring-primary outline-none transition-all"
                />
              </div>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                <input
                  type="password"
                  placeholder="请输入密码"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  onKeyDown={(e) => e.key === 'Enter' && handlePasswordLogin()}
                  className="w-full h-12 pl-11 pr-4 rounded-xl border border-gray-200 bg-gray-50 text-sm focus:bg-white focus:border-primary focus:ring-1 focus:ring-primary outline-none transition-all"
                />
              </div>
              <button
                onClick={handlePasswordLogin}
                disabled={loading || !phone || !password}
                className="w-full h-12 rounded-xl bg-primary text-white font-medium text-sm flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed hover:bg-primary/90 active:scale-[0.98] transition-all"
              >
                {loading ? (
                  <span className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                ) : (
                  <>登录 <ArrowRight className="w-4 h-4" /></>
                )}
              </button>
            </div>
          ) : (
            <div className="space-y-4">
              <div className="relative">
                <Phone className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                <input
                  type="tel"
                  placeholder="请输入手机号"
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  maxLength={11}
                  className="w-full h-12 pl-11 pr-4 rounded-xl border border-gray-200 bg-gray-50 text-sm focus:bg-white focus:border-primary focus:ring-1 focus:ring-primary outline-none transition-all"
                />
              </div>
              <div className="flex gap-3">
                <div className="relative flex-1">
                  <ShieldCheck className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                  <input
                    placeholder="6位验证码"
                    value={code}
                    onChange={(e) => setCode(e.target.value)}
                    maxLength={6}
                    onKeyDown={(e) => e.key === 'Enter' && handleCodeLogin()}
                    className="w-full h-12 pl-11 pr-4 rounded-xl border border-gray-200 bg-gray-50 text-sm focus:bg-white focus:border-primary focus:ring-1 focus:ring-primary outline-none transition-all"
                  />
                </div>
                <button
                  onClick={handleSendCode}
                  disabled={!phone || codeSent}
                  className="h-12 px-4 rounded-xl border border-primary text-primary text-sm font-medium whitespace-nowrap disabled:opacity-50 disabled:cursor-not-allowed hover:bg-primary/5 transition-all"
                >
                  {codeSent ? '已发送' : '获取验证码'}
                </button>
              </div>
              {codeSent && displayedCode && (
                <div className="px-3 py-2.5 rounded-lg bg-blue-50 text-blue-600 text-sm">
                  验证码：{displayedCode}（开发阶段直接显示，生产环境将发送短信）
                </div>
              )}
              <button
                onClick={handleCodeLogin}
                disabled={loading || !phone || !code}
                className="w-full h-12 rounded-xl bg-primary text-white font-medium text-sm flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed hover:bg-primary/90 active:scale-[0.98] transition-all"
              >
                {loading ? (
                  <span className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                ) : (
                  <>登录 <ArrowRight className="w-4 h-4" /></>
                )}
              </button>
            </div>
          )}
        </div>

        <p className="text-center text-xs text-gray-400 mt-6">登录即表示同意《用户协议》和《隐私政策》</p>
      </div>
    </div>
  )
}
