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

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

  useEffect(() => {
    document.documentElement.classList.add('admin-shell')
    return () => document.documentElement.classList.remove('admin-shell')
  }, [])

  const submit = async (e: React.FormEvent) => {
    e.preventDefault(); setErr('')
    try {
      const res = await login(username, password)
      const token = res.data?.data?.token
      if (!token) throw new Error('no token')
      // 관리자 토큰은 고객 세션(mall_token)과 분리된 키에 저장 — 인터셉터가 /admin 영역에서 사용
      localStorage.setItem('mall_admin_token', token)
      const me: any = await getMe().catch(() => null)
      if (me?.role) localStorage.setItem('mall_role', me.role)
      if (me?.username) localStorage.setItem('mall_admin_user', me.username)
      if (me?.role === 'USER') { setErr('관리자 권한이 없습니다.'); localStorage.removeItem('mall_admin_token'); return }
      nav('/admin/dashboard')
    } catch {
      setErr('로그인 실패 — 아이디/비밀번호를 확인하세요.')
    }
  }

  return (
    <div className="admin-shell min-h-screen flex items-center justify-center bg-ink text-[#e6edf6]">
      <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">
          <Flower2 className="text-brand" size={28} />
          <span className="text-xl font-bold">GUARDiA Mall 콘솔</span>
        </div>
        <p className="text-center text-sm text-slate-400 mb-6">매장·대표 관리자 로그인</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 className="w-full py-2.5 rounded-lg bg-brand text-ink font-semibold hover:bg-brand/90">로그인</button>
        <p className="text-center text-[11px] text-slate-500 mt-4">고객 쇼핑몰은 <a href="/" className="text-brand">여기</a></p>
      </form>
    </div>
  )
}
