'use client';

import Link from 'next/link';
import { Suspense, type FormEvent, useEffect, useMemo, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { AuthShell } from '@/components/auth/auth-shell';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { authClient } from '@/lib/auth-client';

function sanitizeNextPath(value: string | null) {
  if (!value || !value.startsWith('/')) {
    return '/';
  }

  return value;
}

export default function SignUpPage() {
  return (
    <Suspense fallback={<div className="flex min-h-screen items-center justify-center text-sm text-[color:var(--terminal-muted)]">Loading sign up...</div>}>
      <SignUpPageContent />
    </Suspense>
  );
}

function SignUpPageContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const nextPath = useMemo(() => sanitizeNextPath(searchParams.get('next')), [searchParams]);
  const { data: rawSession, isPending } = authClient.useSession();
  const session = (rawSession ?? null) as { user?: { id?: string } } | null;

  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    if (!isPending && session?.user?.id) {
      router.replace(nextPath);
    }
  }, [isPending, nextPath, router, session]);

  const signUp = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setError(null);

    if (password !== confirmPassword) {
      setError('Passwords do not match.');
      return;
    }

    setBusy(true);

    const { error: signUpError } = await authClient.signUp.email({
      name: name.trim(),
      email: email.trim(),
      password,
      callbackURL: nextPath
    });

    setBusy(false);

    if (signUpError) {
      setError(signUpError.message || 'Unable to create account.');
      return;
    }

    router.replace(nextPath);
  };

  return (
    <AuthShell
      title="Create Account"
      subtitle="Set up your operator profile to access portfolio and filings intelligence."
      footer={(
        <>
          Already registered?{' '}
          <Link href={`/auth/signin${nextPath !== '/' ? `?next=${encodeURIComponent(nextPath)}` : ''}`} className="text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]">
            Sign in
          </Link>
        </>
      )}
    >
      <form className="space-y-4" onSubmit={signUp}>
        <div>
          <label className="mb-1 block text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Name</label>
          <Input
            type="text"
            autoComplete="name"
            value={name}
            onChange={(event) => setName(event.target.value)}
            required
          />
        </div>

        <div>
          <label className="mb-1 block text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Email</label>
          <Input
            type="email"
            autoComplete="email"
            value={email}
            onChange={(event) => setEmail(event.target.value)}
            required
          />
        </div>

        <div>
          <label className="mb-1 block text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Password</label>
          <Input
            type="password"
            autoComplete="new-password"
            value={password}
            onChange={(event) => setPassword(event.target.value)}
            required
            minLength={8}
          />
        </div>

        <div>
          <label className="mb-1 block text-xs uppercase tracking-[0.2em] text-[color:var(--terminal-muted)]">Confirm Password</label>
          <Input
            type="password"
            autoComplete="new-password"
            value={confirmPassword}
            onChange={(event) => setConfirmPassword(event.target.value)}
            required
            minLength={8}
          />
        </div>

        {error ? <p className="text-sm text-[#ff9f9f]">{error}</p> : null}

        <Button type="submit" className="w-full" disabled={busy}>
          {busy ? 'Creating account...' : 'Create account'}
        </Button>
      </form>
    </AuthShell>
  );
}
