'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 { 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 ForumRegisterInner() {
  const router = useRouter();
  const params = useSearchParams();
  const next = safeNext(params.get('next'));
  const supabase = createClient();

  const [fullName, setFullName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirm, setConfirm] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [info, setInfo] = 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);
    setInfo(null);

    if (!fullName.trim()) return setError('Please enter your name.');
    if (!email) return setError('Email is required.');
    if (password.length < 6) return setError('Password must be at least 6 characters.');
    if (password !== confirm) return setError('Passwords do not match.');

    setLoading(true);
    const { data, error: signUpError } = await supabase.auth.signUp({
      email,
      password,
      options: {
        data: { full_name: fullName.trim(), avatar_url: '' },
        emailRedirectTo: `${window.location.origin}/auth/callback?next=${encodeURIComponent(next)}`,
      },
    });
    setLoading(false);

    if (signUpError) {
      setError(signUpError.message);
      return;
    }

    // If email confirmation is off (auto-confirm), session is already live.
    if (data?.session) {
      window.location.href = next;
      return;
    }

    // Confirmation required path.
    setInfo('Check your email for a confirmation link to finish signing up.');
  };

  return (
    <>
      <Header />
      <main className="min-h-screen bg-[#111111]">
        <div className="max-w-md mx-auto px-4 py-12">
          <div className="text-center mb-6">
            <h1 className="text-2xl font-heading font-bold text-white">Create a Forum Account</h1>
            <p className="text-[#888] font-body text-sm mt-1">
              Post threads, reply, vote, and follow the conversation.
            </p>
          </div>
          <form
            onSubmit={handleSubmit}
            className="bg-[#1a1a1a] border border-[#252525] rounded-lg p-6 space-y-4"
          >
            {error && (
              <div className="bg-[#2a0a0a] border border-[#cc0000] text-[#ff8a8a] font-body text-sm px-3 py-2 rounded">
                {error}
              </div>
            )}
            {info && (
              <div className="bg-[#0a1f2a] border border-[#1e6c8c] text-[#7adbff] font-body text-sm px-3 py-2 rounded">
                {info}
              </div>
            )}
            <div>
              <label className="block text-xs font-body uppercase tracking-wider text-[#888] mb-1.5">
                Full Name
              </label>
              <input
                type="text"
                value={fullName}
                onChange={(e) => setFullName(e.target.value)}
                autoComplete="name"
                required
                className="w-full bg-[#0d0d0d] border border-[#2a2a2a] rounded-lg px-3 py-2 text-white font-body text-sm focus:outline-none focus:border-[#3b82f6]"
              />
            </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-[#0d0d0d] border border-[#2a2a2a] rounded-lg px-3 py-2 text-white font-body text-sm focus:outline-none focus:border-[#3b82f6]"
              />
            </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="new-password"
                required
                minLength={6}
                className="w-full bg-[#0d0d0d] border border-[#2a2a2a] rounded-lg px-3 py-2 text-white font-body text-sm focus:outline-none focus:border-[#3b82f6]"
              />
            </div>
            <div>
              <label className="block text-xs font-body uppercase tracking-wider text-[#888] mb-1.5">
                Confirm Password
              </label>
              <input
                type="password"
                value={confirm}
                onChange={(e) => setConfirm(e.target.value)}
                autoComplete="new-password"
                required
                className="w-full bg-[#0d0d0d] border border-[#2a2a2a] rounded-lg px-3 py-2 text-white font-body text-sm focus:outline-none focus:border-[#3b82f6]"
              />
            </div>
            <button
              type="submit"
              disabled={loading}
              className="w-full bg-[#3b82f6] hover:bg-[#2563eb] disabled:opacity-50 text-white font-body font-semibold text-sm px-5 py-2.5 rounded-lg transition-colors"
            >
              {loading ? 'Creating account…' : 'Create Account'}
            </button>
            <div className="text-center text-xs font-body text-[#888] pt-2">
              Already have an account?{' '}
              <Link
                href={`/forum/login?next=${encodeURIComponent(next)}`}
                className="text-[#3b82f6] hover:underline"
              >
                Sign in
              </Link>
            </div>
          </form>
        </div>
      </main>
      <Footer />
    </>
  );
}

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