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

export default function AdminLogin() {
  const { t } = useTranslation()
  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')
      // Store the admin token under a key separate from the customer session (mall_token) — used by the interceptor in the /admin area
      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(t('admin.login.errNoPriv')); localStorage.removeItem('mall_admin_token'); return }
      nav('/admin/dashboard')
    } catch {
      setErr(t('admin.login.errFailed'))
    }
  }

  return (
    <div className="admin-shell min-h-screen flex items-center justify-center bg-ink text-[#e6edf6]">
      <div className="absolute top-5 right-5"><LanguageSwitcher variant="admin" /></div>
      <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">{t('admin.login.title')}</span>
        </div>
        <p className="text-center text-sm text-slate-400 mb-6">{t('admin.login.subtitle')}</p>
        <label className="block text-xs text-slate-400 mb-1">{t('admin.login.username')}</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">{t('admin.login.password')}</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">{t('admin.login.signIn')}</button>
        <p className="text-center text-[11px] text-slate-500 mt-4">{t('admin.login.storefrontHere')} <a href="/" className="text-brand">{t('admin.login.here')}</a></p>
      </form>
    </div>
  )
}
