'use client';

import { useState, useEffect } from 'react';
import { signIn, getSession, useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { TowerLogo } from '@/components/TowerLogo';
import { TowerBackground } from '@/components/TowerBackground';
import { THEME_CONFIG } from '@/lib/ui-config';
import { useTheme } from '@/contexts/ThemeContext';
import { PRESET_BACKGROUNDS } from '@/lib/ui-config';

function RandomThemeApplier() {
  const { setTheme } = useTheme();
  const [applied, setApplied] = useState(false);

  useEffect(() => {
    if (!applied) {
      // Sélectionner un thème aléatoire côté client seulement
      const randomTheme =
        THEME_CONFIG.allThemes[
          Math.floor(Math.random() * THEME_CONFIG.allThemes.length)
        ];
      console.log('Applying random theme:', randomTheme);

      // Utiliser setTheme du ThemeContext pour forcer le changement
      setTheme(randomTheme);
      setApplied(true);
    }
  }, [applied, setTheme]);

  return null;
}

function RandomBackground() {
  const [background, setBackground] = useState<string>('var(--background)');
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    // Sélectionner un background aléatoire parmi les presets (sauf 'none')
    const availableBackgrounds = PRESET_BACKGROUNDS.filter(
      (bg) => bg.id !== 'none'
    );
    const randomBackground =
      availableBackgrounds[
        Math.floor(Math.random() * availableBackgrounds.length)
      ];
    setBackground(randomBackground.preview);
    setMounted(true);
  }, []);

  return (
    <div
      className="absolute inset-0 -z-10"
      style={{ background: mounted ? background : 'var(--background)' }}
    >
      {/* Effet de profondeur */}
      <div className="absolute inset-0 bg-gradient-to-t from-black/20 via-transparent to-transparent"></div>

      {/* Effet de lumière */}
      <div className="absolute inset-0 bg-gradient-to-br from-transparent via-white/5 to-transparent"></div>
    </div>
  );
}

function LoginPageContent() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const router = useRouter();
  const { data: session, status } = useSession();

  // Redirection si l'utilisateur est déjà connecté
  useEffect(() => {
    if (status === 'authenticated' && session) {
      router.push('/');
    }
  }, [status, session, router]);

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

    try {
      const result = await signIn('credentials', {
        email,
        password,
        redirect: false,
      });

      if (result?.error) {
        setError('Email ou mot de passe incorrect');
      } else {
        // Vérifier que la session est bien créée
        const session = await getSession();
        if (session) {
          router.push('/');
        }
      }
    } catch {
      setError('Une erreur est survenue');
    } finally {
      setIsLoading(false);
    }
  };

  // Afficher un loader pendant la vérification de session
  if (status === 'loading') {
    return (
      <div className="min-h-screen relative overflow-hidden">
        <TowerBackground />
        <div className="relative z-10 min-h-screen flex items-center justify-center">
          <div className="text-[var(--foreground)]">Chargement...</div>
        </div>
      </div>
    );
  }

  // Ne pas afficher le formulaire si l'utilisateur est connecté
  if (status === 'authenticated') {
    return null;
  }

  return (
    <div className="min-h-screen relative overflow-hidden">
      <RandomThemeApplier />
      <RandomBackground />

      {/* Contenu principal */}
      <div className="relative z-10 min-h-screen flex items-center justify-center p-4">
        <div className="w-full max-w-md">
          {/* Logo et titre */}
          <TowerLogo size="md" className="mb-8" />

          {/* Formulaire */}
          <div className="bg-[var(--card)]/80 backdrop-blur-sm rounded-2xl shadow-xl border border-[var(--border)] p-8">
            <h2 className="text-2xl font-mono font-bold text-[var(--foreground)] text-center mb-6">
              Connexion
            </h2>
            <form className="space-y-6" onSubmit={handleSubmit}>
              <div className="space-y-4">
                <div>
                  <label
                    htmlFor="email"
                    className="block text-sm font-medium text-[var(--foreground)] mb-2"
                  >
                    Email
                  </label>
                  <Input
                    id="email"
                    name="email"
                    type="email"
                    required
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    placeholder=""
                    className="w-full"
                  />
                </div>

                <div>
                  <label
                    htmlFor="password"
                    className="block text-sm font-medium text-[var(--foreground)] mb-2"
                  >
                    Mot de passe
                  </label>
                  <Input
                    id="password"
                    name="password"
                    type="password"
                    required
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    placeholder=""
                    className="w-full"
                  />
                </div>
              </div>

              {error && (
                <div className="text-[var(--destructive)] text-sm text-center bg-[var(--destructive)]/10 p-3 rounded-lg border border-[var(--destructive)]/20">
                  {error}
                </div>
              )}

              <div>
                <Button
                  type="submit"
                  disabled={isLoading}
                  className="w-full py-3 text-lg font-mono"
                >
                  {isLoading ? 'Connexion...' : 'Se connecter'}
                </Button>
              </div>

              <div className="text-center text-sm text-[var(--muted-foreground)]">
                <p>
                  Pas encore de compte ?{' '}
                  <Link
                    href="/register"
                    className="text-[var(--primary)] hover:underline font-medium"
                  >
                    Créer un compte
                  </Link>
                </p>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  );
}

export default function LoginPage() {
  return <LoginPageContent />;
}
