import { useState, type FormEvent } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { login } from '@/lib/auth'
import { api } from '@/lib/api'
import { Logo } from '@/components/Logo'
import { validateEmail, messages } from '@/lib/validation'

interface MeResp { roles: string[] }

export function LoginPage() {
  const navigate = useNavigate()
  const location = useLocation()
  const from = (location.state as { from?: string })?.from ?? '/'

  const [email, setEmail] = useState('admin@food-market.local')
  const [password, setPassword] = useState('Admin12345!')
  const [error, setError] = useState<string | null>(null)
  const [emailErr, setEmailErr] = useState<string | null>(null)
  const [passwordErr, setPasswordErr] = useState<string | null>(null)
  const [loading, setLoading] = useState(false)

  async function handleSubmit(e: FormEvent) {
    e.preventDefault()
    const em = validateEmail(email)
    const pw = password ? null : messages.required
    setEmailErr(em); setPasswordErr(pw)
    if (em || pw) return
    setLoading(true)
    setError(null)
    try {
      await login(email, password)
      // SuperAdmin → системная консоль; обычные tenant-юзеры → tenant landing.
      let target = from
      try {
        const me = (await api.get<MeResp>('/api/me')).data
        if (me.roles?.includes('SuperAdmin') && (from === '/' || from === '/dashboard')) {
          target = '/super-admin'
        }
      } catch { /* ignore — fallback на from */ }
      navigate(target, { replace: true })
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Ошибка входа')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-slate-50 dark:bg-slate-900 p-4">
      <form
        onSubmit={handleSubmit}
        noValidate
        className="w-full max-w-md bg-white dark:bg-slate-800 rounded-xl shadow-lg p-8 space-y-5"
      >
        <div>
          <Logo />
          <p className="text-sm text-slate-500 mt-2.5">Вход в систему</p>
        </div>

        <label className="block space-y-1.5">
          <span className="text-sm font-medium text-slate-700 dark:text-slate-200">Email</span>
          <input
            type="email"
            autoComplete="username"
            placeholder="name@example.kz"
            value={email}
            onChange={(e) => { setEmail(e.target.value); if (emailErr) setEmailErr(null) }}
            className={`w-full rounded-md border bg-white dark:bg-slate-900 px-3 py-2 text-sm focus:outline-none focus:ring-2 ${emailErr ? 'border-red-400 focus:ring-red-300' : 'border-slate-300 dark:border-slate-600 focus:ring-[var(--color-brand)]'}`}
          />
          {emailErr && <span className="text-xs text-red-600 block mt-1">{emailErr}</span>}
        </label>

        <label className="block space-y-1.5">
          <span className="text-sm font-medium text-slate-700 dark:text-slate-200">Пароль</span>
          <input
            type="password"
            autoComplete="current-password"
            value={password}
            onChange={(e) => { setPassword(e.target.value); if (passwordErr) setPasswordErr(null) }}
            className={`w-full rounded-md border bg-white dark:bg-slate-900 px-3 py-2 text-sm focus:outline-none focus:ring-2 ${passwordErr ? 'border-red-400 focus:ring-red-300' : 'border-slate-300 dark:border-slate-600 focus:ring-[var(--color-brand)]'}`}
          />
          {passwordErr && <span className="text-xs text-red-600 block mt-1">{passwordErr}</span>}
        </label>

        {error && (
          <div className="text-sm text-red-600 bg-red-50 dark:bg-red-950/30 border border-red-200 dark:border-red-900 rounded-md px-3 py-2">
            {error}
          </div>
        )}

        <button
          type="submit"
          disabled={loading}
          className="w-full rounded-md bg-[var(--color-brand)] hover:bg-[var(--color-brand-hover)] disabled:opacity-60 text-white font-medium py-2.5 text-sm transition-colors"
        >
          {loading ? 'Выполняется вход…' : 'Войти'}
        </button>

        <p className="text-xs text-center">
          <a href="/forgot-password" className="text-[var(--color-brand)] hover:underline">Забыли пароль?</a>
        </p>

        <p className="text-xs text-slate-400 text-center">
          Dev admin: <code>admin@food-market.local</code> / <code>Admin12345!</code>
        </p>
      </form>
    </div>
  )
}
