import { useState, useMemo } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { Button, Input, Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from '@/shared/components/ui';
import { useAuthStore } from '../hooks/use-auth-store';
import LogoOhneText from '../../../../Logos/Logo_ohne_Text.svg';

// Generate random stars for the background
function generateStars(count: number) {
  return Array.from({ length: count }, (_, i) => ({
    id: i,
    x: Math.random() * 100,
    y: Math.random() * 100,
    duration: 2 + Math.random() * 4,
    delay: Math.random() * 5,
    size: Math.random() > 0.8 ? 3 : Math.random() > 0.5 ? 2 : 1,
  }));
}

// Animated title component
function AnimatedTitle() {
  const letters = 'DIMENSION'.split('');

  return (
    <div className="flex flex-col items-center gap-2 mb-6">
      <h1
        className="text-4xl md:text-5xl font-bold tracking-[0.2em] auth-title-dimension"
        style={{ fontFamily: 'Cinzel, serif' }}
      >
        {letters.map((letter, index) => (
          <span
            key={index}
            className="auth-title-letter"
            style={{
              animationDelay: `${index * 0.1}s`,
            }}
          >
            {letter}
          </span>
        ))}
      </h1>
      <div className="flex items-center gap-4 mt-1">
        <div className="h-px w-16 bg-gradient-to-r from-transparent via-primary-500/50 to-primary-500" />
        <span className="text-5xl md:text-6xl auth-title-47">
          47
        </span>
        <div className="h-px w-16 bg-gradient-to-l from-transparent via-primary-500/50 to-primary-500" />
      </div>
    </div>
  );
}

export function LoginPage() {
  const navigate = useNavigate();
  const { login, isLoading, error, clearError } = useAuthStore();
  const [identifier, setIdentifier] = useState('');
  const [password, setPassword] = useState('');
  const [formError, setFormError] = useState('');
  const [rememberMe, setRememberMe] = useState(false);
  const [stage, setStage] = useState<'splash' | 'transition' | 'form'>('splash');
  const [logoTapped, setLogoTapped] = useState(false);

  const stars = useMemo(() => generateStars(100), []);

  const handleLogoTap = () => {
    setLogoTapped(true);
    setTimeout(() => setLogoTapped(false), 600);
  };

  const handleEnter = () => {
    setStage('transition');
    setTimeout(() => {
      setStage('form');
    }, 800);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setFormError('');
    clearError();

    if (!identifier.trim() || !password) {
      setFormError('Bitte alle Felder ausfüllen');
      return;
    }

    try {
      await login(identifier.trim(), password, rememberMe);
      navigate('/');
    } catch (err) {
      console.error('Login failed:', err);
    }
  };

  return (
    <div className="min-h-screen flex flex-col items-center justify-center px-4 py-12 relative">
      {/* Animated Background */}
      <div className="auth-background">
        {/* Stars */}
        <div className="auth-stars">
          {stars.map((star) => (
            <div
              key={star.id}
              className="auth-star"
              style={{
                left: `${star.x}%`,
                top: `${star.y}%`,
                width: `${star.size}px`,
                height: `${star.size}px`,
                ['--duration' as string]: `${star.duration}s`,
                ['--delay' as string]: `${star.delay}s`,
              }}
            />
          ))}
        </div>

        {/* Floating Orbs */}
        <div className="auth-orb auth-orb-1" />
        <div className="auth-orb auth-orb-2" />
        <div className="auth-orb auth-orb-3" />
      </div>

      {/* Content */}
      <div className="relative z-10 flex flex-col items-center w-full max-w-md auth-content">
        {/* Logo without text */}
        <img
          src={LogoOhneText}
          alt="Dimension 47"
          onClick={handleLogoTap}
          className={`mb-4 auth-logo cursor-pointer transition-all duration-[1200ms] ease-in-out ${
            stage === 'splash' ? 'h-40 md:h-48' : 'h-20 md:h-24'
          } ${logoTapped ? 'auth-logo-burst' : ''}`}
        />

        {/* Animated Title */}
        <AnimatedTitle />

        {/* Splash Screen: Button */}
        {stage === 'splash' && (
          <div className="mt-8 animate-[fade-in_0.5s_ease-out]">
            <Button
              onClick={handleEnter}
              className="px-12 h-14 text-lg font-semibold shadow-lg shadow-primary-500/30 hover:shadow-primary-500/50 transition-all duration-300 hover:scale-105 auth-enter-button"
            >
              Los geht's
            </Button>
          </div>
        )}

        {/* Transition: Fading out */}
        {stage === 'transition' && (
          <div className="mt-8 animate-[fade-out_0.6s_ease-in-out_forwards]">
            <Button
              className="px-12 h-14 text-lg font-semibold shadow-lg shadow-primary-500/30 auth-enter-button pointer-events-none"
            >
              Los geht's
            </Button>
          </div>
        )}

        {/* Form Stage */}
        {stage === 'form' && (
          <Card className="w-full auth-card rounded-2xl mt-6 animate-[fade-in_0.5s_ease-out]">
            <CardHeader className="text-center pt-6 pb-2">
              <CardTitle
                className="text-xl font-semibold text-text-primary animate-[slide-up_0.4s_ease-out_both]"
                style={{ animationDelay: '0.1s' }}
              >
                Willkommen zurück
              </CardTitle>
              <CardDescription
                className="text-text-secondary text-sm animate-[slide-up_0.4s_ease-out_both]"
                style={{ animationDelay: '0.2s' }}
              >
                Melde dich an, um fortzufahren
              </CardDescription>
            </CardHeader>
            <form onSubmit={handleSubmit}>
              <CardContent className="space-y-4 px-6">
                {(error || formError) && (
                  <div className="p-3 rounded-lg bg-error-500/10 border border-error-500/20 text-error-500 text-sm animate-[slide-down_0.3s_ease-out]">
                    {error || formError}
                  </div>
                )}
                <div
                  className="auth-input-glow rounded-lg animate-[slide-up_0.4s_ease-out_both]"
                  style={{ animationDelay: '0.15s' }}
                >
                  <Input
                    label="Benutzername oder E-Mail"
                    type="text"
                    placeholder="dein-username"
                    value={identifier}
                    onChange={(e) => setIdentifier(e.target.value)}
                    autoComplete="username"
                    disabled={isLoading}
                  />
                </div>
                <div
                  className="auth-input-glow rounded-lg animate-[slide-up_0.4s_ease-out_both]"
                  style={{ animationDelay: '0.25s' }}
                >
                  <Input
                    label="Passwort"
                    type="password"
                    placeholder="••••••••"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    autoComplete="current-password"
                    disabled={isLoading}
                  />
                </div>
                <label
                  className="flex items-center gap-3 cursor-pointer select-none group animate-[slide-up_0.4s_ease-out_both]"
                  style={{ animationDelay: '0.35s' }}
                >
                  <div className="relative">
                    <input
                      type="checkbox"
                      checked={rememberMe}
                      onChange={(e) => setRememberMe(e.target.checked)}
                      className="sr-only peer"
                      disabled={isLoading}
                    />
                    <div className="w-5 h-5 rounded border-2 border-border bg-bg-secondary transition-all duration-200 peer-checked:bg-primary-500 peer-checked:border-primary-500 group-hover:border-primary-400" />
                    <svg
                      className="absolute top-0.5 left-0.5 w-4 h-4 text-white opacity-0 peer-checked:opacity-100 transition-opacity duration-200"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                      strokeWidth={3}
                    >
                      <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
                    </svg>
                  </div>
                  <span className="text-sm text-text-secondary group-hover:text-text-primary transition-colors">
                    Anmeldung speichern
                  </span>
                </label>
              </CardContent>
              <CardFooter className="flex-col gap-4 px-6 pb-6">
                <Button
                  type="submit"
                  className="w-full h-12 text-base font-semibold shadow-lg shadow-primary-500/25 hover:shadow-primary-500/50 transition-all duration-300 hover:scale-[1.02] animate-[slide-up_0.4s_ease-out_both]"
                  style={{ animationDelay: '0.4s' }}
                  isLoading={isLoading}
                >
                  Anmelden
                </Button>
                <p
                  className="text-sm text-text-secondary text-center animate-[slide-up_0.4s_ease-out_both]"
                  style={{ animationDelay: '0.5s' }}
                >
                  Noch kein Konto?{' '}
                  <Link
                    to="/register"
                    className="text-primary-400 hover:text-primary-300 font-medium transition-colors"
                  >
                    Registrieren
                  </Link>
                </p>
              </CardFooter>
            </form>
          </Card>
        )}
      </div>
    </div>
  );
}
