import React, { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { supabase, isSupabaseConfigured } from '../../lib/supabaseClient';
import { Button } from '../../components/Button';
import { useAuth } from '../../context/AuthContext';
import { LogIn, AlertCircle, ArrowLeft, RefreshCw, Mail, ShieldCheck } from 'lucide-react';

export const Login: React.FC = () => {
  const navigate = useNavigate();
  const { refreshDemoUser } = useAuth();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [needsConfirmation, setNeedsConfirmation] = useState(false);
  const [resendLoading, setResendLoading] = useState(false);
  const [resendSuccess, setResendSuccess] = useState(false);

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    setNeedsConfirmation(false);

    try {
      if (!isSupabaseConfigured) {
        await new Promise(resolve => setTimeout(resolve, 1000));
        const demoUser = {
          user: {
            id: 'demo-user-123',
            email: email,
            user_metadata: { date_of_birth: '1990-01-01' }
          },
          access_token: 'demo-token',
        };
        localStorage.setItem('demo_user_session', JSON.stringify(demoUser));
        refreshDemoUser();
        navigate('/dashboard');
        return;
      }

      const { error } = await supabase.auth.signInWithPassword({
        email,
        password,
      });

      if (error) {
        console.error('Login error:', error);
        if (error.message.includes('Invalid login credentials')) {
          setError('Helytelen e-mail cím vagy jelszó. Kérjük, győződjön meg róla, hogy megerősítette az e-mail címét!');
          setNeedsConfirmation(true);
        } else if (error.message.includes('Email not confirmed')) {
          setError('Az e-mail cím még nincs megerősítve.');
          setNeedsConfirmation(true);
        } else {
          setError('Hiba történt a bejelentkezés során: ' + error.message);
        }
      } else {
        navigate('/dashboard');
      }
    } catch (err: any) {
      setError('Váratlan hiba történt.');
    } finally {
      setLoading(false);
    }
  };

  const handleResendConfirmation = async () => {
    if (!email) {
      setError('Kérjük, először adja meg az e-mail címét!');
      return;
    }
    setResendLoading(true);
    setResendSuccess(false);
    setError(null);

    try {
      const redirectUrl = `${window.location.origin}/#/auth/login`;
      const { error } = await supabase.auth.resend({
        type: 'signup',
        email: email,
        options: { emailRedirectTo: redirectUrl }
      });

      if (error) {
        setError('Hiba az újraküldéskor: ' + error.message);
      } else {
        setResendSuccess(true);
      }
    } catch (err: any) {
      setError('Hiba történt.');
    } finally {
      setResendLoading(false);
    }
  };

  return (
    <div className="min-h-screen pt-20 pb-12 bg-gray-50 flex flex-col items-center justify-center px-4 sm:px-6 lg:px-8">
      <div className="w-full max-w-md">
        <div className="text-center mb-8">
          <h2 className="text-3xl font-extrabold text-gray-900">Bejelentkezés</h2>
          <p className="mt-2 text-sm text-gray-600 font-medium">Jelentkezzen be fiókjába a folytatáshoz.</p>
        </div>

        <div className="bg-white py-8 px-4 shadow-xl rounded-[24px] sm:px-10 border border-gray-100">
          <form className="space-y-6" onSubmit={handleLogin}>
            {error && (
              <div className="rounded-lg bg-red-50 p-4 border border-red-100 flex flex-col items-start">
                <div className="flex items-start">
                  <div className="flex-shrink-0"><AlertCircle className="h-5 w-5 text-red-400" /></div>
                  <div className="ml-3"><h3 className="text-sm font-medium text-red-800">{error}</h3></div>
                </div>
                {needsConfirmation && (
                  <div className="mt-4 w-full p-4 bg-white/80 rounded-xl border border-red-200">
                    <button type="button" onClick={handleResendConfirmation} disabled={resendLoading} className="text-xs font-bold text-primary hover:text-primary-dark underline flex items-center">
                      {resendLoading ? <RefreshCw className="w-3 h-3 animate-spin mr-1" /> : <Mail className="w-3 h-3 mr-1" />}
                      Megerősítő e-mail újraküldése
                    </button>
                  </div>
                )}
              </div>
            )}

            {resendSuccess && (
              <div className="rounded-lg bg-green-50 p-4 border border-green-100 flex items-start animate-fade-in">
                <div className="flex-shrink-0"><Mail className="h-5 w-5 text-green-400" /></div>
                <div className="ml-3"><p className="text-sm font-medium text-green-800">A megerősítő e-mailt újraküldtük!</p></div>
              </div>
            )}

            <div>
              <label htmlFor="email" className="block text-sm font-medium text-gray-700">E-mail cím</label>
              <div className="mt-1">
                <input id="email" type="email" required value={email} onChange={(e) => setEmail(e.target.value)} className="appearance-none block w-full px-4 py-3 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm bg-white text-gray-900" />
              </div>
            </div>

            <div>
              <div className="flex justify-between items-center mb-1">
                <label htmlFor="password" className="block text-sm font-medium text-gray-700">Jelszó</label>
                <Link to="/auth/forgot-password" size="sm" className="text-xs font-bold text-primary hover:underline">Elfelejtette?</Link>
              </div>
              <div className="mt-1">
                <input id="password" type="password" required value={password} onChange={(e) => setPassword(e.target.value)} className="appearance-none block w-full px-4 py-3 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-primary focus:border-primary sm:text-sm bg-white text-gray-900" />
              </div>
            </div>

            <div>
              <Button type="submit" fullWidth disabled={loading} className="flex justify-center items-center">
                {loading ? <RefreshCw className="w-5 h-5 animate-spin" /> : <>Bejelentkezés <LogIn className="ml-2 w-4 h-4" /></>}
              </Button>
            </div>
          </form>

          <div className="mt-6">
            <div className="relative"><div className="absolute inset-0 flex items-center"><div className="w-full border-t border-gray-300" /></div><div className="relative flex justify-center text-sm"><span className="px-2 bg-white text-gray-500">Nincs még fiókod?</span></div></div>
            <div className="mt-6 text-center">
              <Link to="/auth/register" className="font-medium text-primary hover:text-secondary transition-colors underline-offset-4 hover:underline">Regisztrálj ingyenesen</Link>
            </div>
          </div>
        </div>
        
        <div className="mt-8 text-center">
          <Link to="/" className="text-sm text-gray-500 hover:text-gray-900 flex items-center justify-center group">
             <ArrowLeft className="w-4 h-4 mr-1 group-hover:-translate-x-1 transition-transform" /> Vissza a főoldalra
          </Link>
        </div>
      </div>
    </div>
  );
}