import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router';
import { pb } from '~/lib/pocketbase';
import { Lock, Mail, Eye, EyeOff, Loader2, ArrowRight } from 'lucide-react';

export default function Login() {
    const navigate = useNavigate();
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [showPassword, setShowPassword] = useState(false);
    const [error, setError] = useState('');
    const [loading, setLoading] = useState(false);

    // If already logged in, redirect to dashboard
    useEffect(() => {
        if (pb.authStore.isValid) {
            navigate('/', { replace: true });
        }
    }, [navigate]);

    const handleLogin = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!email || !password) {
            setError('Please enter both email and password');
            return;
        }

        setLoading(true);
        setError('');

        try {
            await pb.collection('users').authWithPassword(email, password);
            navigate('/', { replace: true });
        } catch (err: any) {
            setError(err?.message || 'Invalid email or password');
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="relative min-h-screen bg-[#0D0D0D] flex items-center justify-center p-4 overflow-hidden select-none font-sans text-white">
            {/* Background Decorative Orange Glow */}
            <div className="absolute top-[20%] left-[30%] w-[40%] h-[40%] rounded-full bg-orange-500/5 blur-[130px] pointer-events-none" />

            <div className="w-full max-w-md relative z-10">
                {/* Logo & Header */}
                <div className="text-center mb-8">
                    {/* Logo styled exactly like the AR Viewer top-right logo */}
                    <div className="inline-flex w-14 h-14 bg-black border border-neutral-800 rounded-2xl items-center justify-center shadow-lg shadow-black mb-4">
                        <span className="text-orange-500 font-extrabold text-3xl pl-1 select-none">t.</span>
                    </div>
                    <h1 className="text-2xl font-bold tracking-tight text-white uppercase">AR Management</h1>
                    <p className="mt-1 text-neutral-500 text-xs uppercase tracking-wider">
                        Authorized Access Only
                    </p>
                </div>

                {/* Login Card */}
                <div className="bg-[#121212] border border-neutral-900 rounded-2xl p-8 shadow-2xl">
                    <form onSubmit={handleLogin} className="space-y-6">
                        {error && (
                            <div className="p-4 bg-red-500/10 border border-red-500/25 rounded-xl text-red-400 text-xs font-semibold text-center uppercase tracking-wider">
                                {error}
                            </div>
                        )}

                        {/* Email Input */}
                        <div className="space-y-1.5">
                            <label className="text-xs font-bold text-neutral-400 uppercase tracking-wider ml-1">
                                Email Address
                            </label>
                            <div className="relative">
                                <span className="absolute inset-y-0 left-0 pl-3.5 flex items-center text-neutral-600">
                                    <Mail size={16} />
                                </span>
                                <input
                                    type="email"
                                    required
                                    className="w-full bg-[#181818] border border-neutral-800 rounded-xl pl-10 pr-4 py-3 text-sm text-white placeholder-neutral-700 focus:border-orange-500 focus:outline-none transition-colors duration-200"
                                    placeholder="admin@thob.studio"
                                    value={email}
                                    onChange={(e) => setEmail(e.target.value)}
                                />
                            </div>
                        </div>

                        {/* Password Input */}
                        <div className="space-y-1.5">
                            <label className="text-xs font-bold text-neutral-400 uppercase tracking-wider ml-1">
                                Password
                            </label>
                            <div className="relative">
                                <span className="absolute inset-y-0 left-0 pl-3.5 flex items-center text-neutral-600">
                                    <Lock size={16} />
                                </span>
                                <input
                                    type={showPassword ? 'text' : 'password'}
                                    required
                                    className="w-full bg-[#181818] border border-neutral-800 rounded-xl pl-10 pr-10 py-3 text-sm text-white placeholder-neutral-700 focus:border-orange-500 focus:outline-none transition-colors duration-200"
                                    placeholder="••••••••"
                                    value={password}
                                    onChange={(e) => setPassword(e.target.value)}
                                />
                                <button
                                    type="button"
                                    onClick={() => setShowPassword(!showPassword)}
                                    className="absolute inset-y-0 right-0 pr-3.5 flex items-center text-neutral-500 hover:text-neutral-300 transition-colors cursor-pointer"
                                >
                                    {showPassword ? <EyeOff size={16} /> : <Eye size={16} />}
                                </button>
                            </div>
                        </div>

                        {/* Submit Button */}
                        <button
                            type="submit"
                            disabled={loading}
                            className="w-full flex items-center justify-center gap-2 bg-orange-500 hover:bg-orange-400 text-black font-bold uppercase tracking-wider py-3.5 px-4 rounded-xl shadow-[0_0_24px_rgba(249,115,22,0.15)] hover:shadow-[0_0_32px_rgba(249,115,22,0.3)] active:scale-[0.98] transition-all duration-200 disabled:opacity-55 disabled:pointer-events-none cursor-pointer text-sm"
                        >
                            {loading ? (
                                <Loader2 size={16} className="animate-spin" />
                            ) : (
                                <>
                                    <span>Sign In</span>
                                    <ArrowRight size={15} />
                                </>
                            )}
                        </button>
                    </form>
                </div>

                <div className="mt-8 text-center text-[10px] text-neutral-700 uppercase tracking-widest">
                    SYSTEM IP MONITORED SECURE PORTAL
                </div>
            </div>
        </div>
    );
}
