import { useState, type FormEvent } from 'react'
import { useTranslation } from 'react-i18next'
import { Link, Navigate, useLocation, useNavigate } from 'react-router'
import { ApiRequestError } from '@/lib/api'
import { Alert, Button, Card, Input } from '@/components/ui'
import { useAuth } from '@/features/auth'
import { usePlatformBrand, type DemoAccount } from '@/lib/brand'

interface LocationState {
  from?: { pathname?: string }
}

/**
 * Email/password sign-in. Calls auth.login (which stores the bearer token and
 * bootstraps /me), surfaces API errors inline, then redirects to the page the
 * guard bounced from — or /dashboard. Already-authenticated visitors skip it.
 */
export function LoginPage() {
  const { t } = useTranslation()
  const { login, isAuthenticated, me } = useAuth()
  const { demoAccounts } = usePlatformBrand()
  const navigate = useNavigate()
  const location = useLocation()
  // Superadmins belong in the console, not a store's back office — they have
  // no store, so /dashboard is an empty shell for them. An explicit deep link
  // the guard bounced from still wins; only the default differs.
  const home = me?.user?.is_superadmin ? '/superadmin/dashboard' : '/dashboard'
  const from = (location.state as LocationState | null)?.from?.pathname ?? home

  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError] = useState<string | null>(null)
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({})
  const [submitting, setSubmitting] = useState(false)

  function fillDemoAccount(account: DemoAccount) {
    setEmail(account.email)
    setPassword(account.password)
    setError(null)
    setFieldErrors({})
  }

  if (isAuthenticated) return <Navigate to={from} replace />

  async function onSubmit(e: FormEvent) {
    e.preventDefault()
    setError(null)
    setFieldErrors({})
    setSubmitting(true)
    try {
      await login(email, password)
      navigate(from, { replace: true })
    } catch (err) {
      if (err instanceof ApiRequestError) {
        const first = err.errors[0]
        const fields = first?.fields ?? {}
        setFieldErrors(Object.fromEntries(Object.entries(fields).map(([k, v]) => [k, v[0] ?? ''])))
        setError(err.status === 422 ? t('Please check the details below.') : err.message)
      } else {
        setError(t('Could not reach the server. Check your connection and try again.'))
      }
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <Card padded={false}>
      <form onSubmit={onSubmit} className="card-b" noValidate>
        <div className="auth-head">
          <h1>{t('Sign in')}</h1>
          <p>{t('Enter your credentials to open the back office.')}</p>
        </div>

        {error && <Alert tone="danger" title={t('Sign-in failed')} message={error} className="mb-4" />}

        <div className="flex flex-col gap-3">
          <Input
            label={t('Email')}
            type="email"
            name="email"
            autoComplete="username"
            icon="mail"
            placeholder="you@store.com"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            error={fieldErrors.email}
            required
            autoFocus
          />
          <Input
            label={t('Password')}
            type="password"
            name="password"
            autoComplete="current-password"
            placeholder="••••••••"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            error={fieldErrors.password}
            required
          />
        </div>

        {/* Under the fields, where somebody looks the moment the password they
            typed is refused — not buried at the foot of the card. */}
        <p className="mt-2 text-right text-sm">
          <Link to="/forgot-password" className="text-accent">
            {t('Forgot your password?')}
          </Link>
        </p>

        <Button type="submit" variant="primary" loading={submitting} className="mt-4 w-full justify-center">
          {t('Sign in')}
        </Button>

        <p className="mt-4 text-center text-sm text-content-2">
          {t('New here?')}{' '}
          <Link to="/register" className="text-accent">
            {t('Create your store')}
          </Link>
        </p>
      </form>

      {demoAccounts.length > 0 && (
        <div className="card-b border-t border-border">
          <p className="mb-2 text-sm font-semibold text-content">{t('Demo account login credentials')}</p>
          <ul className="flex flex-col divide-y divide-border">
            {demoAccounts.map((account) => (
              <li key={account.email} className="flex items-center gap-3 py-2 text-sm">
                <div className="min-w-0 flex-1">
                  <div className="text-xs text-content-2">{account.role}</div>
                  <div className="mono break-all">{account.email}</div>
                </div>
                <span className="mono shrink-0 text-content-2">{account.password}</span>
                <Button variant="ghost" size="sm" icon="copy" aria-label={t('Use this account')} onClick={() => fillDemoAccount(account)} />
              </li>
            ))}
          </ul>
        </div>
      )}
    </Card>
  )
}

export default LoginPage
