'use client';

import { useState } from 'react';
import { signIn } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { AlertCircle, Loader2 } from 'lucide-react';

export default function LoginForm() {
    const router = useRouter();
    const [error, setError] = useState<string | null>(null);
    const [isLoading, setIsLoading] = useState(false);

    const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        setError(null);
        setIsLoading(true);

        const formData = new FormData(e.currentTarget);
        const username = formData.get('username') as string;
        const password = formData.get('password') as string;

        try {
            const result = await signIn('credentials', {
                username,
                password,
                redirect: false, // Tangani redirect manual agar bisa handle error
            });

            if (result?.error) {
                setError('ERROR ASLI: ' + result.error);
            } else if (result?.ok) {
                // Login berhasil — hard redirect untuk memastikan Vercel Edge Server membaca Cookie Authentication
                window.location.href = '/admin';
            } else {
                setError('Terjadi kesalahan tidak terduga. Coba lagi.');
            }
        } catch (err) {
            setError('Gagal terhubung ke server. Coba lagi.');
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <Card className="w-full max-w-sm mx-auto shadow-[0_16px_64px_0_rgba(0,0,0,0.5)] bg-white/5 backdrop-blur-2xl border border-white/10 ring-1 ring-white/5 text-white overflow-hidden relative rounded-3xl">
            {/* Ambient Lighting di dalam Card */}
            <div className="absolute -top-20 -right-20 w-48 h-48 bg-blue-500/20 rounded-full blur-[60px] pointer-events-none"></div>
            <div className="absolute -bottom-20 -left-20 w-48 h-48 bg-indigo-500/10 rounded-full blur-[60px] pointer-events-none"></div>

            <CardHeader className="space-y-1 relative z-10">
                <CardTitle className="text-3xl font-black text-center font-sans tracking-tight text-white mb-2">Login</CardTitle>
                <CardDescription className="text-center text-gray-400">
                    Sistem informasi untuk Pengurus Bidang dan Administrator.
                </CardDescription>
            </CardHeader>
            <CardContent>
                <form onSubmit={handleSubmit} className="space-y-4">
                    <div className="space-y-2 relative z-10">
                        <Label htmlFor="username" className="text-gray-300">Username</Label>
                        <Input
                            id="username"
                            type="text"
                            name="username"
                            placeholder="username"
                            required
                            disabled={isLoading}
                            className="bg-white/5 border border-white/10 text-white placeholder:text-gray-500 focus-visible:ring-blue-500/50 backdrop-blur-md rounded-xl"
                        />
                    </div>
                    <div className="space-y-2 relative z-10">
                        <Label htmlFor="password" className="text-gray-300">Password</Label>
                        <Input
                            id="password"
                            type="password"
                            name="password"
                            placeholder="••••••••"
                            required
                            minLength={6}
                            disabled={isLoading}
                            className="bg-white/5 border border-white/10 text-white placeholder:text-gray-500 focus-visible:ring-blue-500/50 backdrop-blur-md rounded-xl"
                        />
                    </div>

                    <div className="flex h-8 items-end space-x-1" aria-live="polite" aria-atomic="true">
                        {error && (
                            <>
                                <AlertCircle className="h-5 w-5 text-red-500 flex-shrink-0" />
                                <p className="text-sm text-red-500">{error}</p>
                            </>
                        )}
                    </div>

                    <Button type="submit" className="w-full bg-blue-600 hover:bg-blue-500 text-white shadow-[0_0_20px_rgba(37,99,235,0.4)] border border-blue-400/50 font-bold rounded-xl h-11" disabled={isLoading}>
                        {isLoading ? (
                            <>
                                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                                Memproses...
                            </>
                        ) : 'Login Perangkat'}
                    </Button>
                </form>
            </CardContent>
        </Card>
    );
}
