'use client';

import { Suspense, useState, useEffect } from 'react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import Header from '@/components/Header';
import Footer from '@/components/Footer';
import SocialAuthButtons from '@/components/auth/SocialAuthButtons';
import { createClient } from '@/lib/supabase/client';

function safeNext(next: string | null): string {
  if (!next) return '/forum';
  if (!next.startsWith('/') || next.startsWith('//')) return '/forum';
  return next;
}

function ForumLoginInner() {
  const router = useRouter();
  const params = useSearchParams();
  const next = safeNext(params.get('next'));
  const supabase = createClient();

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    supabase.auth.getUser().then(({ data: { user } }) => {
      if (user) router.replace(next);
    });
  }, [next, router, supabase]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    if (!email || !password) {
      setError('Email and password are required.');
      return;
    }
    setLoading(true);
    const { error: signInError } = await supabase.auth.signInWithPassword({ email, password });
    setLoading(false);
    if (signInError) {
      setError(signInError.message);
      return;
    }
    window.location.href = next;
  };

  return (
    <>
      <Header />
      <main className="min-h-screen bg-gradient-to-b from-[#F8FAFC] via-[#F8FAFC] to-[#F8FAFC]">
        <div className="max-w-md mx-auto px-4 py-16">
          <div className="text-center mb-6">
            <div className="text-[10px] uppercase tracking-widest text-[#1D4ED8] font-mono mb-2">Welcome back</div>
            <h1 className="text-3xl font-heading font-bold text-[#0F172A]">Sign in to AV Beat</h1>
            <p className="text-[#888] font-body text-sm mt-2">
              Your account covers the forum, newsletter preferences, and saved articles.
            </p>
          </div>
          <form
            onSubmit={handleSubmit}
            className="bg-[#FFFFFF] border border-[#DCE6F2] rounded-lg p-6 space-y-4 shadow-2xl"
          >
            {error && (
              <div className="bg-[#2a0a0a] border border-[#1D4ED8] text-[#ff8a8a] font-body text-sm px-3 py-2 rounded">
                {error}
              </div>
            )}
            <div>
              <label className="block text-xs font-body uppercase tracking-wider text-[#888] mb-1.5">
                Email
              </label>
              <input
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                autoComplete="email"
                required
                className="w-full bg-[#F8FAFC] border border-[#DCE6F2] rounded-lg px-3 py-2 text-[#0F172A] font-body text-sm focus:outline-none focus:border-[#1D4ED8]"
              />
            </div>
            <div>
              <label className="block text-xs font-body uppercase tracking-wider text-[#888] mb-1.5">
                Password
              </label>
              <input
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                autoComplete="current-password"
                required
                className="w-full bg-[#F8FAFC] border border-[#DCE6F2] rounded-lg px-3 py-2 text-[#0F172A] font-body text-sm focus:outline-none focus:border-[#1D4ED8]"
              />
            </div>
            <button
              type="submit"
              disabled={loading}
              className="w-full bg-[#1D4ED8] hover:bg-[#1E3A8A] disabled:opacity-50 text-white font-body font-semibold text-sm px-5 py-2.5 rounded-lg transition-colors"
            >
              {loading ? 'Signing in…' : 'Sign In'}
            </button>
            <div className="text-right text-xs font-body">
              <Link
                href={`/forum/forgot-password?email=${encodeURIComponent(email)}`}
                className="text-[#888] hover:text-[#1D4ED8] hover:underline"
              >
                Forgot password?
              </Link>
            </div>
            <SocialAuthButtons next={next} />
            <div className="text-center text-xs font-body text-[#888] pt-2">
              No account yet?{' '}
              <Link
                href={`/forum/register?next=${encodeURIComponent(next)}`}
                className="text-[#1D4ED8] hover:underline"
              >
                Create one
              </Link>
            </div>
          </form>
        </div>
      </main>
      <Footer />
    </>
  );
}

export default function ForumLoginPage() {
  return (
    <Suspense fallback={null}>
      <ForumLoginInner />
    </Suspense>
  );
}
