import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import api from '@/lib/api'

interface LoginPageProps {
  onLogin?: (user: any) => void
}

export function LoginPage({ onLogin }: LoginPageProps) {
  const navigate = useNavigate()
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError] = useState('')

  const handleLogin = async () => {
    try {
      const isPlatformAdmin = username === '平台管理员'
      const endpoint = isPlatformAdmin ? '/admin/login' : '/auth/login'
      const res: any = await api.post(endpoint, { username, password })
      localStorage.setItem('token', res.data.token)
      localStorage.setItem('user', JSON.stringify(res.data.user))
      onLogin?.(res.data.user)
      if (isPlatformAdmin) {
        navigate('/tenant-management')
      } else {
        const role = res.data.user?.role
        if (role === 'store') navigate('/store')
        else if (role === 'regional') navigate('/regional')
        else navigate('/')
      }
    } catch {
      setError('登录失败，请重试')
    }
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-muted/30">
      <div className="w-80 rounded-lg border bg-card p-6 shadow-lg">
        <h1 className="mb-6 text-center text-xl font-bold">连锁运营企业态势感知系统</h1>
        <div className="space-y-3">
          <div>
            <label className="text-sm text-muted-foreground">用户名</label>
            <input
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && handleLogin()}
              className="mt-1 w-full rounded-md border px-3 py-2 text-sm"
            />
          </div>
          {error && <p className="text-sm text-red-600">{error}</p>}
          <div>
            <label className="text-sm text-muted-foreground">密码</label>
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && handleLogin()}
              className="mt-1 w-full rounded-md border px-3 py-2 text-sm"
            />
          </div>
          <button
            onClick={handleLogin}
            className="w-full rounded-md bg-primary py-2 text-sm font-medium text-primary-foreground"
          >
            登录
          </button>
          <p className="text-center text-xs text-muted-foreground">
            租户管理员请输入用户名密码登录 · 平台管理员请输入「平台管理员」
          </p>
        </div>
      </div>
    </div>
  )
}
