import { useState, useEffect } from 'react';
import { useSubmit, useNavigation, useActionData, useNavigate, redirect } from 'react-router';
import type { Route } from './+types/login';
import { pb } from '~/lib/pocketbase';
import { Lock, Mail, Eye, EyeOff, Loader2, ArrowRight } from 'lucide-react';
import { Input } from '~/components/ui/input';
import { Button } from '~/components/ui/button';
import { Label } from '~/components/ui/label';
import { Card } from '~/components/ui/card';
import { toast } from 'sonner';

export async function clientLoader() {
    if (pb.authStore.isValid) {
        return redirect('/');
    }
    return null;
}

export async function clientAction({ request }: Route.ClientActionArgs) {
    const formData = await request.formData();
    const email = formData.get('email') as string;
    const password = formData.get('password') as string;

    if (!email || !password) {
        return { error: 'Please enter both email and password' };
    }

    try {
        await pb.collection('users').authWithPassword(email, password);
        return redirect('/');
    } catch (err: any) {
        return { error: err?.message || 'Invalid email or password' };
    }
}

export default function Login() {
    const navigate = useNavigate();
    const submit = useSubmit();
    const navigation = useNavigation();
    const actionData = useActionData<typeof clientAction>();

    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [showPassword, setShowPassword] = useState(false);
    const [localError, setLocalError] = useState('');

    const isLoading = navigation.state !== 'idle';

    // Already-authenticated redirect fallback
    useEffect(() => {
        if (pb.authStore.isValid) {
            navigate('/', { replace: true });
        }
    }, [navigate]);

    // Handle authentication feedback
    useEffect(() => {
        if (actionData) {
            if (actionData.error) {
                setLocalError(actionData.error);
                toast.error(actionData.error);
            } else {
                toast.success('Logged in successfully');
            }
        }
    }, [actionData]);

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

        setLocalError('');
        const formData = new FormData();
        formData.append('email', email);
        formData.append('password', password);

        submit(formData, { method: 'post' });
    };

    return (
        <div className="relative min-h-screen bg-[#0D0D0D] flex items-center justify-center p-4 overflow-hidden select-none font-sans text-white">
            <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">
                <div className="text-center mb-8">
                    <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>

                <Card className="p-8 shadow-2xl">
                    <form onSubmit={handleLogin} className="space-y-6">
                        {(localError || actionData?.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">
                                {localError || actionData?.error}
                            </div>
                        )}

                        <div className="space-y-1.5">
                            <Label className="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"
                                    name="email"
                                    required
                                    className="pl-10"
                                    placeholder="admin@thob.studio"
                                    value={email}
                                    onChange={(e) => setEmail(e.target.value)}
                                />
                            </div>
                        </div>

                        <div className="space-y-1.5">
                            <Label className="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'}
                                    name="password"
                                    required
                                    className="pl-10 pr-10"
                                    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>

                        <Button
                            type="submit"
                            disabled={isLoading}
                            className="w-full py-6 text-sm font-bold uppercase tracking-wider"
                        >
                            {isLoading ? (
                                <Loader2 size={16} className="animate-spin text-black" />
                            ) : (
                                <>
                                    <span>Sign In</span>
                                    <ArrowRight size={15} />
                                </>
                            )}
                        </Button>
                    </form>
                </Card>

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