import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { supabase, isSupabaseConfigured } from '../../lib/supabaseClient';
import { Button } from '../../components/Button';
import { Mail, ArrowLeft, AlertCircle, CheckCircle, RefreshCw, Send } from 'lucide-react';

export const ForgotPassword: React.FC = () => {
  const [email, setEmail] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

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

    try {
      if (!isSupabaseConfigured) {
        await new Promise(resolve => setTimeout(resolve, 1000));
        setSuccess(true);
        return;
      }

      const redirectUrl = `${window.location.origin}/#/auth/reset-password`;

      const { error } = await supabase.auth.resetPasswordForEmail(email, {
        redirectTo: redirectUrl,
      });

      if (error) {
        setError(error.message);
      } else {
        setSuccess(true);
      }
    } catch (err: any) {
      setError('Váratlan hiba történt.');
    } finally {
      setLoading(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 tracking-tight">Jelszó visszaállítása</h2>
          <p className="mt-2 text-sm text-gray-600 font-medium">Küldünk egy linket a jelszava megváltoztatásához.</p>
        </div>

        <div className="bg-white py-10 px-6 md:px-10 shadow-xl rounded-[32px] border border-gray-100">
          {success ? (
            <div className="text-center animate-fade-in">
              <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-6">
                <CheckCircle className="w-8 h-8 text-green-600" />
              </div>
              <h3 className="text-xl font-bold text-gray-900 mb-2">E-mail elküldve!</h3>
              <p className="text-gray-600 mb-8 text-sm leading-relaxed">
                Ellenőrizze a(z) <strong>{email}</strong> postaládáját a visszaállításhoz szükséges linkért.
              </p>
              <Link to="/auth/login" className="block">
                <Button fullWidth>Vissza a bejelentkezéshez</Button>
              </Link>
            </div>
          ) : (
            <form className="space-y-6" onSubmit={handleSubmit}>
              {error && (
                <div className="rounded-xl bg-red-50 p-4 border border-red-100 flex items-start animate-fade-in">
                  <AlertCircle className="h-5 w-5 text-red-400 shrink-0 mt-0.5" />
                  <p className="ml-3 text-sm font-medium text-red-800">{error}</p>
                </div>
              )}

              <div>
                <label htmlFor="email" className="block text-xs font-black text-gray-400 uppercase tracking-widest mb-2">E-mail cím</label>
                <div className="relative">
                   <Mail className="absolute left-3 top-3.5 w-5 h-5 text-gray-300" />
                   <input
                    id="email"
                    type="email"
                    required
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    className="appearance-none block w-full pl-10 pr-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>
                <Button type="submit" fullWidth disabled={loading} size="lg" className="shadow-lg shadow-primary/20">
                  {loading ? (
                    <RefreshCw className="w-5 h-5 animate-spin" />
                  ) : (
                    <>Link küldése <Send className="ml-2 w-4 h-4" /></>
                  )}
                </Button>
              </div>

              <div className="text-center pt-2">
                <Link to="/auth/login" className="text-sm font-bold text-gray-400 hover:text-primary transition-colors flex items-center justify-center group">
                  <ArrowLeft className="w-4 h-4 mr-2 group-hover:-translate-x-1 transition-transform" /> Vissza a bejelentkezéshez
                </Link>
              </div>
            </form>
          )}
        </div>
      </div>
    </div>
  );
};