import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { Loader2 } from 'lucide-react';
import ReCAPTCHA from 'react-google-recaptcha';
import { supabase } from '../lib/supabase';
import { useAuth } from '../contexts/AuthContext';

export default function Auth() {
  const [isLogin, setIsLogin] = useState(true);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const navigate = useNavigate();
  const { session, isLoading: authLoading } = useAuth();

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [nombre, setNombre] = useState('');
  const [apellido, setApellido] = useState('');
  const [alias, setAlias] = useState('');
  const [celular, setCelular] = useState('');
  const [fechaNacimiento, setFechaNacimiento] = useState('');
  const [termsAccepted, setTermsAccepted] = useState(false);
  const [captchaValue, setCaptchaValue] = useState<string | null>(null);
  const recaptchaRef = useRef<ReCAPTCHA>(null);

  useEffect(() => {
    if (authLoading) return;
    if (session) {
      navigate('/dashboard');
    }
  }, [session, authLoading, navigate]);

  if (authLoading || session) {
    return null;
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!captchaValue) {
      setError("Por favor, completa el reCAPTCHA.");
      return;
    }
    
    if (!isLogin && password !== confirmPassword) {
      setError("Las contraseñas no coinciden.");
      return;
    }
    if (!isLogin && !termsAccepted) {
      setError("Debes aceptar los términos y condiciones.");
      return;
    }

    setLoading(true);
    setError(null);

    try {
      if (isLogin) {
        const { error: signInError } = await supabase.auth.signInWithPassword({ email, password });
        if (signInError) throw signInError;
        navigate('/dashboard');
      } else {
        const { data: signUpData, error: signUpError } = await supabase.auth.signUp({ email, password });
        if (signUpError) throw signUpError;
        
        if (signUpData.user) {
          const { error: rpcError } = await supabase.rpc('rpc_create_profile', {
            p_id: signUpData.user.id,
            p_nombre: nombre,
            p_apellido: apellido,
            p_alias: alias,
            p_celular: celular,
            p_fecha_nacimiento: fechaNacimiento
          });

          if (rpcError) {
             console.error("Profile error:", rpcError);
             throw new Error("No se pudo crear el perfil correctamente.");
          }
        }
        navigate('/dashboard');
      }
    } catch (err: any) {
      console.error(err);
      setError(err.message || 'Ocurrió un error. Por favor, intenta de nuevo.');
      recaptchaRef.current?.reset();
      setCaptchaValue(null);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex-1 flex flex-col animate-in fade-in duration-300 min-h-[calc(100vh-80px)]">
      {/* Dynamic Background */}
      <div className="absolute inset-0 z-0 flex overflow-hidden">
        <div className="w-1/2 bg-gradient-to-br from-brand-red to-brand-dark-blue"></div>
        <div className="w-1/2 bg-gradient-to-bl from-brand-blue to-brand-dark-blue"></div>
        {/* Abstract Texture Overlay */}
        <div className="absolute inset-0 z-0 opacity-30 mix-blend-overlay">
          <img 
            src={`${import.meta.env.BASE_URL}images/auth-bg.jpg`}
            alt="Texture" 
            className="w-full h-full object-cover" 
            onError={(e) => { e.currentTarget.src = "https://images.unsplash.com/photo-1557672172-298e090bd0f1?q=80&w=2000&auto=format&fit=crop" }} /* Fallback while they don't upload their image */
          />
        </div>
      </div>

      <div className="relative z-10 flex-1 flex items-center justify-center p-4 py-12">
        <div className="bg-brand-dark-blue/95 backdrop-blur-md w-full max-w-lg rounded-3xl p-8 md:p-10 shadow-2xl overflow-hidden relative border border-white/5">
          
          {/* White top right circle embellishment */}
          <div className="absolute -top-16 -right-16 w-48 h-48 bg-white rounded-full opacity-100"></div>

          <h1 className="font-display italic text-4xl text-brand-yellow mb-8 tracking-wider drop-shadow-sm text-center relative z-10">
            {isLogin ? 'LOGIN' : 'REGISTRO'}
          </h1>

          {error && (
            <div className="bg-red-500/10 text-red-300 p-4 rounded-xl mb-6 text-sm border border-red-500/20 text-center font-medium relative z-10">
              {error}
            </div>
          )}

          <form onSubmit={handleSubmit} className="flex flex-col gap-5 relative z-10">
            
            {!isLogin && (
              <>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                  <div className="flex flex-col gap-1">
                    <label className="text-sm font-bold text-brand-yellow">Nombre</label>
                    <input type="text" required value={nombre} onChange={(e) => setNombre(e.target.value)} placeholder="Nombre" className="w-full bg-white text-gray-900 rounded-xl px-4 py-3 outline-none" />
                  </div>
                  <div className="flex flex-col gap-1">
                    <label className="text-sm font-bold text-brand-yellow">Apellido</label>
                    <input type="text" required value={apellido} onChange={(e) => setApellido(e.target.value)} placeholder="Apellido" className="w-full bg-white text-gray-900 rounded-xl px-4 py-3 outline-none" />
                  </div>
                </div>

                <div className="flex flex-col gap-1">
                  <label className="text-sm font-bold text-brand-yellow">Correo</label>
                  <input type="email" required value={email} onChange={(e) => setEmail(e.target.value)} placeholder="correo@ejemplo.com" className="w-full bg-white text-gray-900 rounded-xl px-4 py-3 outline-none" />
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                  <div className="flex flex-col gap-1">
                    <label className="text-sm font-bold text-brand-yellow">Contraseña</label>
                    <input type="password" required value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Contraseña" className="w-full bg-white text-gray-900 rounded-xl px-4 py-3 outline-none" />
                  </div>
                  <div className="flex flex-col gap-1">
                    <label className="text-sm font-bold text-brand-yellow">Confirmar contraseña</label>
                    <input type="password" required value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} placeholder="Contraseña" className="w-full bg-white text-gray-900 rounded-xl px-4 py-3 outline-none" />
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                  <div className="flex flex-col gap-1">
                    <label className="text-sm font-bold text-brand-yellow">Alias</label>
                    <input type="text" required value={alias} onChange={(e) => setAlias(e.target.value)} placeholder="Alias" className="w-full bg-white text-gray-900 rounded-xl px-4 py-3 outline-none" />
                  </div>
                  <div className="flex flex-col gap-1">
                    <label className="text-sm font-bold text-brand-yellow">Celular</label>
                    <input type="tel" required value={celular} onChange={(e) => setCelular(e.target.value)} placeholder="+507 0000-0000" className="w-full bg-white text-gray-900 rounded-xl px-4 py-3 outline-none" />
                  </div>
                </div>

                <div className="flex flex-col gap-1">
                  <label className="text-sm font-bold text-brand-yellow">Fecha de nacimiento</label>
                  <input type="date" required value={fechaNacimiento} onChange={(e) => setFechaNacimiento(e.target.value)} className="w-full bg-white text-gray-900 rounded-xl px-4 py-3 outline-none" />
                </div>

                <div className="flex items-start gap-3 mt-2">
                  <input type="checkbox" id="terms" required checked={termsAccepted} onChange={(e) => setTermsAccepted(e.target.checked)} className="mt-1 w-4 h-4 rounded text-brand-blue" />
                  <label htmlFor="terms" className="text-xs text-white/80 leading-tight">
                    Acepto los términos y condiciones del programa de lealtad y autorizo el uso de mis datos personales conforme a la política de privacidad.
                  </label>
                </div>
              </>
            )}

            {isLogin && (
              <>
                <div className="flex flex-col gap-1">
                  <label className="text-base font-bold text-brand-yellow">Correo</label>
                  <input type="email" required value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Correo electrónico" className="w-full bg-white text-gray-900 rounded-xl px-4 py-4 outline-none text-base" />
                </div>

                <div className="flex flex-col gap-1 mt-2">
                  <label className="text-base font-bold text-brand-yellow">Contraseña</label>
                  <input type="password" required value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Contraseña" className="w-full bg-white text-gray-900 rounded-xl px-4 py-4 outline-none text-base" />
                  <div className="text-right mt-1">
                    <a href="#" className="text-white text-sm hover:underline">¿Olvidaste tu contraseña?</a>
                  </div>
                </div>
              </>
            )}

            <div className="flex justify-center mt-2">
              <ReCAPTCHA
                ref={recaptchaRef}
                sitekey={import.meta.env.VITE_RECAPTCHA_SITE_KEY || '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI'}
                onChange={(value) => setCaptchaValue(value)}
                theme="light"
              />
            </div>

            <button
              type="submit"
              disabled={loading}
              className="mt-6 w-full bg-brand-yellow text-brand-blue font-bold text-xl py-4 rounded-full hover:bg-brand-yellow/90 active:scale-[0.98] transition-all flex items-center justify-center gap-2 shadow-[0_0_20px_rgba(255,201,0,0.5)] disabled:opacity-70 disabled:pointer-events-none"
            >
              {loading ? <Loader2 className="animate-spin" /> : (isLogin ? 'Login' : 'Crear cuenta')}
            </button>
          </form>

          <div className="mt-8 text-center relative z-10 text-white/80 shrink-0 flex items-center justify-center gap-1">
            {isLogin ? (
              <>¿No tienes cuenta? <button type="button" onClick={() => { setIsLogin(false); setError(null); recaptchaRef.current?.reset(); setCaptchaValue(null); }} className="text-white font-bold underline decoration-white/50 hover:decoration-white">Regístrate</button></>
            ) : (
              <>¿Ya tienes cuenta? <button type="button" onClick={() => { setIsLogin(true); setError(null); recaptchaRef.current?.reset(); setCaptchaValue(null); }} className="text-white font-bold underline decoration-white/50 hover:decoration-white">Iniciar Sesión</button></>
            )}
          </div>

        </div>
      </div>
    </div>
  );
}
