import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Cpu } from 'lucide-react'
import { login, getMe } from '../api/client'

export default function Login() {
  const [username, setUsername] = useState('admin')
  const [password, setPassword] = useState('')
  const [err, setErr] = useState('')
  const [busy, setBusy] = useState(false)
  const nav = useNavigate()

  const submit = async (e: React.FormEvent) => {
    e.preventDefault()
    setErr(''); setBusy(true)
    try {
      const res = await login(username, password)
      const token = res.data?.data?.token
      if (!token) throw new Error('no token')
      localStorage.setItem('mes_token', token)
      try {
        const me = await getMe()
        const d = me.data?.data || {}
        if (d.role) localStorage.setItem('mes_role', d.role)
        if (d.username) localStorage.setItem('mes_user', d.username)
      } catch { /* noop */ }
      nav('/dashboard')
    } catch {
      setErr('로그인 실패 — 아이디/비밀번호를 확인하세요.')
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-ink">
      <form onSubmit={submit} className="w-[360px] bg-panel border border-edge rounded-2xl p-8">
        <div className="flex items-center gap-2 justify-center mb-6">
          <Cpu className="text-brand" size={32} />
          <span className="text-xl font-bold">GUARDiA MES</span>
        </div>
        <p className="text-center text-sm text-slate-400 mb-6">AI 제조실행시스템 · WMS · MES · QMS</p>
        <label className="block text-xs text-slate-400 mb-1">아이디</label>
        <input value={username} onChange={e => setUsername(e.target.value)}
          className="w-full mb-4 px-3 py-2 rounded-lg bg-card border border-edge text-sm focus:border-brand outline-none" />
        <label className="block text-xs text-slate-400 mb-1">비밀번호</label>
        <input type="password" value={password} onChange={e => setPassword(e.target.value)}
          className="w-full mb-4 px-3 py-2 rounded-lg bg-card border border-edge text-sm focus:border-brand outline-none" />
        {err && <p className="text-rose-400 text-xs mb-3">{err}</p>}
        <button disabled={busy} className="w-full py-2.5 rounded-lg bg-brand text-ink font-semibold hover:bg-brand/90 disabled:opacity-60">
          {busy ? '로그인 중…' : '로그인'}
        </button>
        <p className="text-center text-[11px] text-slate-500 mt-4">admin / manager / worker · admin123</p>
      </form>
    </div>
  )
}
