'use client';

import { signIn, useSession } from 'next-auth/react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useTranslations } from 'next-intl';
import { useEffect, useRef, useState } from 'react';
import { motion } from 'framer-motion';
import { Loader2, KeyRound } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';

interface LoginPageProps {
  params: { locale: string };
}

/**
 * Login page component
 * Automatically redirects to Keycloak. Only shows UI on auth errors.
 */
export default function LoginPage({ params: { locale } }: LoginPageProps) {
  const { status } = useSession();
  const router = useRouter();
  const searchParams = useSearchParams();
  const t = useTranslations('auth');
  const [isLoading, setIsLoading] = useState(false);
  const autoSignInTriggered = useRef(false);

  const callbackUrl = searchParams.get('callbackUrl') || `/${locale}/dashboard`;
  const error = searchParams.get('error');

  // Redirect if already authenticated
  useEffect(() => {
    if (status === 'authenticated') {
      router.push(callbackUrl);
    }
  }, [status, router, callbackUrl]);

  // Auto-redirect to Keycloak if no error
  useEffect(() => {
    if (status === 'unauthenticated' && !error && !autoSignInTriggered.current) {
      autoSignInTriggered.current = true;
      signIn('keycloak', { callbackUrl });
    }
  }, [status, error, callbackUrl]);

  const handleLogin = async () => {
    setIsLoading(true);
    try {
      await signIn('keycloak', { callbackUrl });
    } catch {
      setIsLoading(false);
    }
  };

  // Show loading spinner during auto-redirect or session check
  if (!error) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-background">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    );
  }

  // Only show full UI when there's an error (so user can retry)
  return (
    <div className="flex min-h-screen items-center justify-center bg-gradient-to-br from-background to-muted p-4">
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.4, ease: 'easeOut' }}
      >
        <Card className="w-full max-w-md">
          <CardHeader className="space-y-4 text-center">
            <div className="mx-auto flex h-16 w-16 items-center justify-center rounded-2xl bg-primary text-primary-foreground">
              <span className="text-3xl font-bold">t</span>
              <span className="text-3xl font-light">OS</span>
            </div>
            <div>
              <CardTitle className="text-2xl">{t('loginTitle')}</CardTitle>
              <CardDescription className="mt-2">{t('loginSubtitle')}</CardDescription>
            </div>
          </CardHeader>
          <CardContent className="space-y-4">
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: 'auto' }}
              className="rounded-lg bg-destructive/10 p-3 text-sm text-destructive"
            >
              {error === 'SessionRequired' ? t('sessionExpired') : t('unauthorized')}
            </motion.div>

            <Button
              onClick={handleLogin}
              disabled={isLoading}
              className="w-full"
              size="lg"
            >
              {isLoading ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  {t('loggingIn')}
                </>
              ) : (
                <>
                  <KeyRound className="mr-2 h-4 w-4" />
                  {t('loginButton')}
                </>
              )}
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    </div>
  );
}
