'use client';

import { Suspense, useState } from 'react';
import { signIn } from 'next-auth/react';
import { useRouter, useSearchParams } from 'next/navigation';

function LoginForm() {
    const router = useRouter();
    const params = useSearchParams();
    const callbackUrl = params.get('callbackUrl') || '/';

    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [showPw, setShowPw] = useState(false);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');

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

        const result = await signIn('credentials', {
            redirect: false,
            email: email.trim().toLowerCase(),
            password,
        });

        setLoading(false);

        if (result?.ok) {
            router.replace(callbackUrl);
        } else {
            setError('Invalid email or password.');
        }
    };

    return (
        <div className="min-h-screen flex items-center justify-center" style={{ backgroundColor: '#0f0f12' }}>
            {/* Ambient glow */}
            <div className="fixed inset-0 pointer-events-none overflow-hidden">
                <div className="absolute top-1/4 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[600px] h-[400px] rounded-full opacity-10"
                    style={{ background: 'radial-gradient(ellipse, #ef4444 0%, transparent 70%)' }} />
                <div className="absolute bottom-1/4 left-1/2 -translate-x-1/2 translate-y-1/2 w-[400px] h-[300px] rounded-full opacity-8"
                    style={{ background: 'radial-gradient(ellipse, #7c3aed 0%, transparent 70%)' }} />
            </div>

            <div className="relative z-10 w-full max-w-md px-6">
                {/* Logo / Brand */}
                <div className="text-center mb-8">
                    <div className="inline-flex items-center gap-2 bg-red-500/10 border border-red-500/20 text-red-400 px-3 py-1 rounded-full text-xs font-medium mb-5">
                        <span className="w-1.5 h-1.5 rounded-full bg-red-500 animate-pulse inline-block" />
                        Secured Access
                    </div>
                    <h1 className="text-4xl font-black tracking-tight mb-2"
                        style={{ background: 'linear-gradient(135deg, #fff 30%, #f97316)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent' }}>
                        Niche Finder Pro
                    </h1>
                    <p className="text-sm" style={{ color: '#555' }}>Sign in to access your dashboard</p>
                </div>

                {/* Card */}
                <div className="rounded-2xl p-8" style={{ background: '#16161f', border: '1px solid rgba(255,255,255,0.07)', boxShadow: '0 25px 60px rgba(0,0,0,0.5)' }}>
                    <form onSubmit={handleSubmit} className="space-y-5" autoComplete="off">

                        {/* Error */}
                        {error && (
                            <div className="rounded-xl px-4 py-3 flex items-center gap-2"
                                style={{ background: 'rgba(239,68,68,0.08)', border: '1px solid rgba(239,68,68,0.2)' }}>
                                <span className="text-red-400 text-lg">⚠</span>
                                <p className="text-red-400 text-sm font-medium">{error}</p>
                            </div>
                        )}

                        {/* Email */}
                        <div>
                            <label className="block text-xs font-bold mb-2 uppercase tracking-wider" style={{ color: '#555' }}>
                                Email Address
                            </label>
                            <input
                                type="email"
                                value={email}
                                onChange={e => setEmail(e.target.value)}
                                placeholder="admin@devtrixx.com"
                                required
                                autoComplete="off"
                                className="w-full rounded-xl px-4 py-3 text-sm outline-none transition-all"
                                style={{
                                    background: '#0f0f12',
                                    border: '1px solid rgba(255,255,255,0.07)',
                                    color: '#e8e8f0',
                                    caretColor: '#f97316',
                                }}
                                onFocus={e => e.currentTarget.style.borderColor = 'rgba(249,115,22,0.4)'}
                                onBlur={e => e.currentTarget.style.borderColor = 'rgba(255,255,255,0.07)'}
                            />
                        </div>

                        {/* Password */}
                        <div>
                            <label className="block text-xs font-bold mb-2 uppercase tracking-wider" style={{ color: '#555' }}>
                                Password
                            </label>
                            <div className="relative">
                                <input
                                    type={showPw ? 'text' : 'password'}
                                    value={password}
                                    onChange={e => setPassword(e.target.value)}
                                    placeholder="••••••••••"
                                    required
                                    autoComplete="new-password"
                                    className="w-full rounded-xl px-4 py-3 pr-12 text-sm outline-none transition-all"
                                    style={{
                                        background: '#0f0f12',
                                        border: '1px solid rgba(255,255,255,0.07)',
                                        color: '#e8e8f0',
                                        caretColor: '#f97316',
                                    }}
                                    onFocus={e => e.currentTarget.style.borderColor = 'rgba(249,115,22,0.4)'}
                                    onBlur={e => e.currentTarget.style.borderColor = 'rgba(255,255,255,0.07)'}
                                />
                                <button type="button" tabIndex={-1}
                                    onClick={() => setShowPw(v => !v)}
                                    className="absolute right-3 top-1/2 -translate-y-1/2 text-lg select-none"
                                    style={{ color: '#444' }}>
                                    {showPw ? '🙈' : '👁'}
                                </button>
                            </div>
                        </div>

                        {/* Submit */}
                        <button
                            type="submit"
                            disabled={loading}
                            className="w-full font-bold py-3 rounded-xl text-sm transition-all disabled:opacity-60 disabled:cursor-not-allowed"
                            style={{
                                background: loading ? '#1e1e2c' : 'linear-gradient(135deg, #ef4444, #f97316)',
                                color: '#fff',
                                boxShadow: loading ? 'none' : '0 0 30px rgba(249,115,22,0.25)',
                            }}>
                            {loading
                                ? <span className="flex items-center justify-center gap-2"><span className="w-4 h-4 rounded-full border-2 border-white/30 border-t-white animate-spin inline-block" /> Signing in...</span>
                                : 'Sign In →'}
                        </button>
                    </form>
                </div>

                <p className="text-center text-xs mt-6" style={{ color: '#333' }}>
                    © {new Date().getFullYear()} Devtrixx · All rights reserved
                </p>
            </div>
        </div>
    );
}

export default function LoginPage() {
    return (
        <Suspense fallback={
            <div className="min-h-screen flex items-center justify-center" style={{ backgroundColor: '#0f0f12' }}>
                <span className="text-white opacity-50 text-sm">Loading...</span>
            </div>
        }>
            <LoginForm />
        </Suspense>
    );
}
