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-4">
      <h1
        className="text-3xl md:text-4xl 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-12 bg-gradient-to-r from-transparent via-primary-500/50 to-primary-500" />
        <span className="text-4xl md:text-5xl auth-title-47">
          47
        </span>
        <div className="h-px w-12 bg-gradient-to-l from-transparent via-primary-500/50 to-primary-500" />
      </div>
    </div>
  );
}

export function RegisterPage() {
  const navigate = useNavigate();
  const { register, isLoading, error, clearError } = useAuthStore();
  const [username, setUsername] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [formError, setFormError] = useState('');

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

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

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

    if (password !== confirmPassword) {
      setFormError('Passwörter stimmen nicht überein');
      return;
    }

    if (password.length < 8) {
      setFormError('Passwort muss mindestens 8 Zeichen lang sein');
      return;
    }

    try {
      await register(username.trim(), email.trim(), password);
      navigate('/');
    } catch (err) {
      console.error('Registration failed:', err);
    }
  };

  return (
    <div className="min-h-screen flex flex-col items-center justify-center px-4 py-8 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"
          className="h-24 md:h-32 mb-3 auth-logo"
        />

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

        <Card className="w-full auth-card rounded-2xl">
          <CardHeader className="text-center pt-5 pb-1">
            <CardTitle className="text-xl font-semibold text-text-primary">
              Konto erstellen
            </CardTitle>
            <CardDescription className="text-text-secondary text-sm">
              Werde Teil der Dimension
            </CardDescription>
          </CardHeader>
          <form onSubmit={handleSubmit}>
            <CardContent className="space-y-3 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 transition-shadow duration-300">
                <Input
                  label="Benutzername"
                  type="text"
                  placeholder="dein-username"
                  value={username}
                  onChange={(e) => setUsername(e.target.value)}
                  autoComplete="username"
                  disabled={isLoading}
                />
              </div>
              <div className="auth-input-glow rounded-lg transition-shadow duration-300">
                <Input
                  label="E-Mail"
                  type="email"
                  placeholder="deine@email.de"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  autoComplete="email"
                  disabled={isLoading}
                />
              </div>
              <div className="auth-input-glow rounded-lg transition-shadow duration-300">
                <Input
                  label="Passwort"
                  type="password"
                  placeholder="••••••••"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  autoComplete="new-password"
                  disabled={isLoading}
                />
              </div>
              <div className="auth-input-glow rounded-lg transition-shadow duration-300">
                <Input
                  label="Passwort bestätigen"
                  type="password"
                  placeholder="••••••••"
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  autoComplete="new-password"
                  disabled={isLoading}
                />
              </div>
            </CardContent>
            <CardFooter className="flex-col gap-3 px-6 pb-5">
              <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]"
                isLoading={isLoading}
              >
                Registrieren
              </Button>
              <p className="text-sm text-text-secondary text-center">
                Bereits ein Konto?{' '}
                <Link
                  to="/login"
                  className="text-primary-400 hover:text-primary-300 font-medium transition-colors"
                >
                  Anmelden
                </Link>
              </p>
            </CardFooter>
          </form>
        </Card>
      </div>
    </div>
  );
}
