'use client';

import Link from 'next/link';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { signUp, useSession } from '@/lib/better-auth';
import { AuthShell } from '@/components/auth/auth-shell';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';

export default function SignUpPage() {
  const router = useRouter();
  const { data: session, isPending: sessionPending } = useSession();

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

  useEffect(() => {
    if (!sessionPending && session?.user) {
      router.replace('/');
    }
  }, [sessionPending, session, router]);

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setLoading(true);
    setError(null);

    try {
      const result = await signUp.email({
        name,
        email,
        password
      });

      if (result.error) {
        setError(result.error.message || 'Unable to create account');
      } else {
        router.replace('/');
        router.refresh();
      }
    } catch {
      setError('Sign up failed');
    } finally {
      setLoading(false);
    }
  };

  return (
    <AuthShell
      title="Create account"
      subtitle="Provision an analyst workspace with Better Auth sessions."
      footer={(
        <>
          Already registered?{' '}
          <Link href="/auth/signin" className="text-[color:var(--accent)] hover:text-[color:var(--accent-strong)]">
            Sign in
          </Link>
        </>
      )}
    >
      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label className="mb-1 block text-sm text-[color:var(--terminal-muted)]">Name</label>
          <Input required value={name} onChange={(event) => setName(event.target.value)} placeholder="Operator name" />
        </div>

        <div>
          <label className="mb-1 block text-sm text-[color:var(--terminal-muted)]">Email</label>
          <Input type="email" required value={email} onChange={(event) => setEmail(event.target.value)} placeholder="you@company.com" />
        </div>

        <div>
          <label className="mb-1 block text-sm text-[color:var(--terminal-muted)]">Password</label>
          <Input
            type="password"
            required
            minLength={8}
            value={password}
            onChange={(event) => setPassword(event.target.value)}
            placeholder="Minimum 8 characters"
          />
        </div>

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

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