import { type FormEvent, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { login } from '../api/auth'
import BillCareLogo from '../components/BillCareLogo'

export default function LoginPage() {
  const navigate = useNavigate()
  const [userid, setUserid] = useState('demo')
  const [password, setPassword] = useState('demo123')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)

  const submit = async (e: FormEvent) => {
    e.preventDefault()
    setError('')
    setLoading(true)
    try {
      const data = await login(userid, password)
      localStorage.setItem('token', data.token!)
      localStorage.setItem('role', data.role === 'SHOP' ? 'SHOP' : 'AGENT')
      localStorage.setItem('userName', data.name)
      localStorage.setItem('userid', data.userid)
      if (data.staffPermission) localStorage.setItem('staffPermission', data.staffPermission)
      else localStorage.removeItem('staffPermission')
      navigate('/care/main', { replace: true })
    } catch (err) {
      setError(err instanceof Error ? err.message : '로그인에 실패했습니다.')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="login-wrap">
      <form className="login-box" onSubmit={submit}>
        <div className="login-brand">
          <BillCareLogo title="BillCare" size="login" />
          <p>통합 영업·정산 관리 시스템</p>
        </div>
        <div className="field">
          <label htmlFor="login-userid">아이디</label>
          <input
            id="login-userid"
            value={userid}
            onChange={(e) => setUserid(e.target.value)}
            autoComplete="username"
            autoFocus
          />
        </div>
        <div className="field">
          <label htmlFor="login-password">비밀번호</label>
          <input
            id="login-password"
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            autoComplete="current-password"
          />
        </div>
        {error && <div className="login-error">{error}</div>}
        <button type="submit" className="login-submit" disabled={loading}>
          {loading ? '로그인 중...' : '로그인'}
        </button>
        <div className="login-demo">데모: demo / demo123</div>
      </form>
    </div>
  )
}
