import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import Logo from '../../components/ui/Logo'
import { portalApi } from '../../lib/api-services'
import { Input, Label } from '../../components/ui/Input'
import Button from '../../components/ui/Button'

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 items-center justify-center bg-gray-50 px-4 pt-safe pb-safe">
      <div className="w-full max-w-sm">
        <div className="flex flex-col items-center justify-center gap-2 mb-8">
          <Logo className="w-10 h-10 text-primary" />
          <span className="text-base font-bold text-center">企业用工专家 — 员工端</span>
        </div>

        <div className="card">
          <div className="flex border-b mb-4">
            <button
              onClick={() => { setMode('password'); setError('') }}
              className={`flex-1 py-2 text-sm font-medium border-b-2 ${mode === 'password' ? 'border-primary text-primary' : 'border-transparent text-gray-500'}`}
            >密码登录</button>
            <button
              onClick={() => { setMode('code'); setError('') }}
              className={`flex-1 py-2 text-sm font-medium border-b-2 ${mode === 'code' ? 'border-primary text-primary' : 'border-transparent text-gray-500'}`}
            >验证码登录</button>
          </div>

          {error && <div className="mb-4 px-3 py-2 rounded-md bg-red-50 text-red-700 text-sm">{error}</div>}

          {mode === 'password' ? (
            <div className="space-y-4">
              <div>
                <Label>手机号</Label>
                <Input type="tel" placeholder="请输入手机号" value={phone} onChange={(e) => setPhone(e.target.value)} maxLength={11} className="h-11" />
              </div>
              <div>
                <Label>密码</Label>
                <Input type="password" placeholder="请输入密码" value={password} onChange={(e) => setPassword(e.target.value)} className="h-11" />
              </div>
              <Button className="w-full h-11" onClick={handlePasswordLogin} disabled={loading || !phone || !password}>
                {loading ? '登录中...' : '登录'}
              </Button>
            </div>
          ) : (
            <div className="space-y-4">
              <div>
                <Label>手机号</Label>
                <Input type="tel" placeholder="请输入手机号" value={phone} onChange={(e) => setPhone(e.target.value)} maxLength={11} className="h-11" />
              </div>
              <div className="flex gap-2">
                <div className="flex-1">
                  <Label>验证码</Label>
                  <Input placeholder="6位验证码" value={code} onChange={(e) => setCode(e.target.value)} maxLength={6} className="h-11" />
                </div>
                <div className="flex items-end">
                  <Button variant="secondary" onClick={handleSendCode} disabled={!phone || codeSent} className="h-11 whitespace-nowrap">
                    {codeSent ? '已发送' : '获取验证码'}
                  </Button>
                </div>
              </div>
              {codeSent && displayedCode && (
                <div className="px-3 py-2 rounded-md bg-blue-50 text-blue-700 text-sm">
                  验证码：{displayedCode}（开发阶段直接显示，生产环境将发送短信）
                </div>
              )}
              <Button className="w-full h-11" onClick={handleCodeLogin} disabled={loading || !phone || !code}>
                {loading ? '登录中...' : '登录'}
              </Button>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
