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 } 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);
        
        // Specifikus hibaüzenetek kezelése
        if (error.message.includes('Invalid login credentials')) {
          setError('Helytelen e-mail cím vagy jelszó. Ha most regisztráltál, ellenőrizd a postafiókodat és kattints a megerősítő linkre!');
          setNeedsConfirmation(true);
        } else if (error.message.includes('Email not confirmed')) {
          setError('Az e-mail címed még nincs megerősítve. Kérjük, kattints a regisztrációkor kapott linkre!');
          setNeedsConfirmation(true);
        } else {
          setError('Hiba történt: ' + error.message);
        }
      } else {
        navigate('/dashboard');
      }
    } catch (err: any) {
      setError('Váratlan hiba történt a bejelentkezés során.');
    } 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);
        setNeedsConfirmation(false);
      }
    } catch (err: any) {
      setError('Hiba történt az e-mail újraküldésekor.');
    } 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">Lépjen be fiókjába a kezeléshez.</p>
        </div>

        <div className="bg-white py-8 px-4 shadow-xl rounded-[32px] sm:px-10 border border-gray-100">
          <form className="space-y-6" onSubmit={handleLogin}>
            {error && (
              <div className="rounded-2xl bg-red-50 p-4 border border-red-100 flex flex-col animate-fade-in">
                <div className="flex items-start">
                  <div className="flex-shrink-0"><AlertCircle className="h-5 w-5 text-red-400" /></div>
                  <div className="ml-3"><p className="text-xs font-bold text-red-800 uppercase tracking-tight">{error}</p></div>
                </div>
                {needsConfirmation && (
                  <div className="mt-3 pt-3 border-t border-red-100 w-full">
                    <button type="button" onClick={handleResendConfirmation} disabled={resendLoading} className="text-xs font-black text-primary hover:underline flex items-center gap-2 uppercase tracking-widest">
                      {resendLoading ? <RefreshCw className="w-3 h-3 animate-spin" /> : <Mail className="w-3 h-3" />}
                      Megerősítő levél újraküldése
                    </button>
                  </div>
                )}
              </div>
            )}

            {resendSuccess && (
              <div className="rounded-2xl bg-green-50 p-4 border border-green-100 flex items-start animate-fade-in shadow-sm">
                <div className="flex-shrink-0"><Mail className="h-5 w-5 text-green-400" /></div>
                <div className="ml-3"><p className="text-xs font-bold text-green-800 uppercase tracking-tight">A megerősítő linket újra elküldtük!</p></div>
              </div>
            )}

            <div className="space-y-4">
              <div>
                <label htmlFor="email" className="block text-xs font-black text-gray-400 uppercase tracking-widest mb-1">E-mail cím</label>
                <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-200 rounded-xl shadow-sm focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary sm:text-sm bg-white text-gray-900 font-medium" placeholder="pelda@email.hu" />
              </div>

              <div>
                <div className="flex justify-between items-center mb-1">
                  <label htmlFor="password" className="block text-xs font-black text-gray-400 uppercase tracking-widest">Jelszó</label>
                  {/* Fixed: removed invalid 'size' prop from Link component */}
                  <Link to="/auth/forgot-password" className="text-[10px] font-black text-primary hover:underline uppercase tracking-widest">Elfelejtette?</Link>
                </div>
                <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-200 rounded-xl shadow-sm focus:outline-none focus:ring-4 focus:ring-primary/10 focus:border-primary sm:text-sm bg-white text-gray-900 font-medium" placeholder="••••••••" />
              </div>
            </div>

            <div>
              <Button type="submit" fullWidth disabled={loading} size="lg" className="shadow-lg shadow-primary/20">
                {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-8 pt-6 border-t border-gray-100 text-center">
            <p className="text-sm text-gray-500 font-medium mb-2">Nincs még fiókod?</p>
            <Link to="/auth/register" className="text-sm font-bold text-primary hover:text-secondary transition-colors underline-offset-4 hover:underline">Regisztrálj ingyenesen</Link>
          </div>
        </div>
        
        <div className="mt-8 text-center">
          <Link to="/" className="text-sm font-bold text-gray-400 hover:text-gray-900 flex items-center justify-center group transition-colors">
             <ArrowLeft className="w-4 h-4 mr-2 group-hover:-translate-x-1 transition-transform" /> Vissza a főoldalra
          </Link>
        </div>
      </div>
    </div>
  );
}