'use client';

import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { Link, useRouter } from '@/i18n/navigation';
import Image from 'next/image';
import { ShieldCheck } from 'lucide-react';
import { login as apiLogin, getCurrentUser, logout as apiLogout } from '@/lib/api/auth';
import { useAuth } from '@/lib/context/auth-context';

export default function AdminLoginPage() {
  const t = useTranslations('admin.login');
  const router = useRouter();
  const { refreshUser } = useAuth();

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setIsLoading(true);

    try {
      await apiLogin({ email, password, rememberMe: false });
      const me = await getCurrentUser();

      if (me.role !== 'ADMIN') {
        // Valid credentials but not an administrator — drop the session.
        await apiLogout();
        setError(t('notAdmin'));
        return;
      }

      await refreshUser();
      router.replace('/admin');
    } catch (err) {
      setError(t('error'));
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-brand-navy px-4">
      <div className="absolute inset-0 bg-gradient-to-br from-brand-navy to-neutral-900 opacity-95" />

      <div className="relative w-full max-w-md">
        <div className="bg-white rounded-2xl shadow-xl p-8 sm:p-10">
          <div className="flex flex-col items-center mb-8">
            <Image
              src="/assets/logos/logo-black.svg"
              alt="Xpeditis"
              width={56}
              height={64}
              priority
              className="h-auto mb-4"
            />
            <div className="flex items-center gap-2 text-brand-turquoise">
              <ShieldCheck className="w-5 h-5" />
              <span className="text-xs font-semibold uppercase tracking-wider">{t('badge')}</span>
            </div>
            <h1 className="text-h2 text-brand-navy mt-3 text-center">{t('title')}</h1>
            <p className="text-body-sm text-neutral-600 mt-1 text-center">{t('subtitle')}</p>
          </div>

          {error && (
            <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg">
              <p className="text-body-sm text-red-800">{error}</p>
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-5">
            <div>
              <label htmlFor="email" className="label">
                {t('emailLabel')}
              </label>
              <input
                id="email"
                type="email"
                value={email}
                onChange={e => setEmail(e.target.value)}
                className="input w-full"
                placeholder={t('emailPlaceholder')}
                autoComplete="email"
                disabled={isLoading}
                required
              />
            </div>

            <div>
              <label htmlFor="password" className="label">
                {t('passwordLabel')}
              </label>
              <input
                id="password"
                type="password"
                value={password}
                onChange={e => setPassword(e.target.value)}
                className="input w-full"
                placeholder={t('passwordPlaceholder')}
                autoComplete="current-password"
                disabled={isLoading}
                required
              />
            </div>

            <button
              type="submit"
              disabled={isLoading}
              className="btn-primary w-full text-lg disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {isLoading ? t('submitting') : t('submit')}
            </button>
          </form>

          <div className="mt-6 text-center">
            <Link href="/login" className="text-body-sm link">
              {t('backToApp')}
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}
