import React, { useState, useEffect } from 'react';
import { Database, Lock, User, ArrowRight, ShieldCheck, Loader2 } from 'lucide-react';
import { HybridBackend } from '../services/backend.ts';

interface LoginViewProps {
    onLoginSuccess: () => void;
}

export const LoginView: React.FC<LoginViewProps> = ({ onLoginSuccess }) => {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');
    const [isInitializing, setIsInitializing] = useState(true);

    useEffect(() => {
        const timer = setTimeout(() => setIsInitializing(false), 3000);
        return () => clearTimeout(timer);
    }, []);

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

        try {
            const success = await HybridBackend.login(email, password);
            if (success) {
                onLoginSuccess();
            } else {
                setError('CREDENCIAIS INVÁLIDAS. VERIFIQUE EMAIL E SENHA.');
            }
        } catch (err) {
            setError('ERRO DE CONEXÃO. TENTE NOVAMENTE.');
        } finally {
            setLoading(false);
        }
    };

    if (isInitializing) {
        return (
            <div className="min-h-screen bg-gray-50 flex flex-col items-center justify-center p-4">
                <Loader2 className="animate-spin text-blue-600 mb-4" size={48} />
                <h2 className="text-gray-500 font-bold uppercase tracking-widest text-sm">Inicializando Sistema...</h2>
                <span className="text-gray-400 text-xs mt-2 font-mono font-bold bg-gray-200 px-2 py-1 rounded">V1.0.2</span>
            </div>
        );
    }

    return (
        <div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
            <div className="max-w-md w-full bg-white rounded-2xl shadow-xl overflow-hidden border border-gray-100">
                <div className="bg-blue-600 p-8 text-center">
                    <div className="w-16 h-16 bg-white/20 rounded-xl flex items-center justify-center text-white mx-auto backdrop-blur-sm mb-4">
                        <Database size={32} />
                    </div>
                    <h1 className="text-2xl font-bold text-white uppercase tracking-wide">SCOREODONTO</h1>
                    <p className="text-blue-100 text-xs font-bold uppercase mt-1">SISTEMA INTEGRADO POSTGRESQL + GOOGLE</p>
                </div>
                
                <div className="p-8">
                    <h2 className="text-lg font-bold text-gray-800 uppercase mb-6 text-center flex items-center justify-center gap-2">
                         <Lock size={18} className="text-blue-600"/> ACESSO RESTRITO
                    </h2>

                    <form onSubmit={handleSubmit} className="space-y-4">
                        <div>
                            <label className="block text-xs font-bold text-gray-500 mb-1 uppercase">USUÁRIO / EMAIL</label>
                            <div className="relative">
                                <User className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
                                <input 
                                    type="email" 
                                    required
                                    value={email}
                                    onChange={(e) => setEmail(e.target.value)}
                                    className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none transition-all text-sm font-medium"
                                    placeholder="ex: usuario@email.com"
                                />
                            </div>
                        </div>

                        <div>
                            <label className="block text-xs font-bold text-gray-500 mb-1 uppercase">SENHA DE ACESSO</label>
                            <div className="relative">
                                <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
                                <input 
                                    type="password" 
                                    required
                                    value={password}
                                    onChange={(e) => setPassword(e.target.value)}
                                    className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none transition-all text-sm font-medium"
                                    placeholder="••••••••"
                                />
                            </div>
                        </div>

                        {error && (
                            <div className="p-3 bg-red-50 text-red-600 text-xs font-bold uppercase rounded-lg border border-red-100 text-center">
                                {error}
                            </div>
                        )}

                        <button 
                            type="submit" 
                            disabled={loading}
                            className="w-full bg-blue-600 hover:bg-blue-700 text-white py-3 rounded-lg font-bold uppercase flex items-center justify-center gap-2 transition-all shadow-lg hover:shadow-xl disabled:opacity-70 disabled:cursor-not-allowed mt-4"
                        >
                            {loading ? (
                                <span>VERIFICANDO...</span>
                            ) : (
                                <>ENTRAR NO SISTEMA <ArrowRight size={18} /></>
                            )}
                        </button>
                    </form>

                    <div className="mt-8 flex flex-col items-center justify-center gap-2 text-gray-400 text-[10px] font-bold uppercase">
                        <div className="flex items-center gap-1">
                            <ShieldCheck size={12}/> AMBIENTE SEGURO E CRIPTOGRAFADO
                        </div>
                        <span className="bg-gray-100 text-gray-500 px-2 py-1 rounded font-mono">V1.0.2</span>
                    </div>
                </div>
            </div>
        </div>
    );
};