import { useState, FormEvent } from 'react';
import { Link, Navigate } from 'react-router-dom';
import { useAuth } from '@/hooks/useAuth';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';

export default function LoginPage() {
  const { user, login } = useAuth();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  if (user) return <Navigate to="/feed" replace />;

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try { await login(username, password); }
    catch (err: any) { setError(err.response?.data?.error || 'Ошибка входа'); }
    finally { setLoading(false); }
  };

  return (
    <div className="relative flex min-h-screen items-center justify-center p-5 overflow-hidden bg-[var(--bg)]">
      {/* Декоративные пятна */}
      <div className="auth-bg-blob w-96 h-96 bg-[var(--accent)] -top-20 -left-20 absolute" />
      <div className="auth-bg-blob w-72 h-72 bg-pink-300 bottom-10 right-5 absolute" />

      <div className="relative w-full max-w-[380px] animate-fade-up">
        {/* Логотип */}
        <div className="text-center mb-8">
          <div className="mx-auto mb-5 h-[72px] w-[72px] rounded-[22px] flex items-center justify-center bg-[var(--accent)] shadow-lg">
            <span className="text-4xl select-none">🐾</span>
          </div>
          <h1 className="text-2xl font-extrabold tracking-tight">Котограм</h1>
          <p className="text-sm text-[var(--fg-tertiary)] mt-1.5">Войдите, чтобы смотреть котов</p>
        </div>

        {/* Форма */}
        <div className="card p-6 space-y-3">
          <form onSubmit={handleSubmit} className="space-y-3">
            <div className="space-y-2">
              <Input
                value={username}
                onChange={e => setUsername(e.target.value)}
                placeholder="Имя пользователя"
                required
                autoFocus
                autoComplete="username"
                className="h-12 text-sm rounded-xl bg-[var(--bg)] border-[var(--border)] focus-ring"
              />
              <Input
                type="password"
                value={password}
                onChange={e => setPassword(e.target.value)}
                placeholder="Пароль"
                required
                autoComplete="current-password"
                className="h-12 text-sm rounded-xl bg-[var(--bg)] border-[var(--border)] focus-ring"
              />
            </div>

            {error && (
              <div className="flex items-center gap-2 px-4 py-3 rounded-xl bg-[var(--danger-light)] text-[var(--danger)] text-xs font-medium animate-fade-up">
                {error}
              </div>
            )}

            <Button
              type="submit"
              disabled={loading}
              size="lg" className="w-full"
            >
              {loading ? (
                <span className="flex items-center gap-2">
                  <span className="h-4 w-4 rounded-full border-2 border-white/30 border-t-white animate-spin" />
                  Вход...
                </span>
              ) : 'Войти'}
            </Button>
          </form>
        </div>

        <p className="mt-5 text-center text-sm text-[var(--fg-tertiary)]">
          Нет аккаунта?{' '}
          <Link to="/register" className="font-semibold text-[var(--accent)] hover:opacity-80 transition-opacity">
            Зарегистрироваться
          </Link>
        </p>
      </div>
    </div>
  );
}
