import React, { useEffect, useState } from 'react';
import Head from 'next/head';
import { useRouter } from 'next/router';
import { useSession, signIn } from 'next-auth/react';

export default function SignUpPage() {
  const router = useRouter();
  const { data: session, status } = useSession();
  const [username, setUsername] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [providers, setProviders] = useState<any>(null);

  useEffect(() => {
    if (status === 'authenticated') {
      router.replace('/');
    }
  }, [status]);

  useEffect(() => {
    async function fetchProviders() {
      try {
        const r = await fetch('/api/auth/providers');
        if (r.ok) setProviders(await r.json());
      } catch {}
    }
    fetchProviders();
  }, []);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      const r = await fetch('/api/auth/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username: username || null, email, password }),
      });
      const j = await r.json();
      if (!r.ok) throw new Error(j.error || 'Sign up failed');
      // Auto sign-in after signup (if email provided, attempt credentials with email)
      const idOrEmail = email || username;
      if (idOrEmail) {
        await signIn('credentials', { redirect: false, username: idOrEmail, password });
      }
      router.push('/');
    } catch (err: any) {
      setError(err?.message || 'Sign up failed');
    } finally {
      setLoading(false);
    }
  }

  async function handleGoogle() {
    await signIn('google');
  }

  return (
    <>
      <Head>
        <title>Sign up - Gregory AI</title>
      </Head>
      <div style={{ minHeight:'100vh', display:'flex', alignItems:'center', justifyContent:'center', background:'linear-gradient(180deg,#f8fafc,#f1f5f9)' }}>
        <div style={{ width: '100%', maxWidth: 480, background:'#fff', border:'1px solid #e5e7eb', borderRadius:16, padding:24, boxShadow:'0 12px 30px rgba(2,6,23,0.08)' }}>
          <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:16 }}>
            <img src="/logo.png" alt="Gregory AI" width={40} height={40} style={{ borderRadius:12 }} />
            <h1 style={{ margin:0, fontSize:22 }}>Create your account</h1>
          </div>
          <p style={{ marginTop:0, color:'#6b7280', fontSize:14 }}>Enjoy 5 free queries without an account. Sign up to continue and save your chats.</p>
          <form onSubmit={handleSubmit}>
            <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
              <input value={username} onChange={e=>setUsername(e.target.value)} placeholder="Username (optional)" style={{ padding:'12px 14px', borderRadius:10, border:'1px solid #e5e7eb' }} />
              <input value={email} onChange={e=>setEmail(e.target.value)} placeholder="Email" type="email" required style={{ padding:'12px 14px', borderRadius:10, border:'1px solid #e5e7eb' }} />
              <input value={password} onChange={e=>setPassword(e.target.value)} placeholder="Password" type="password" style={{ padding:'12px 14px', borderRadius:10, border:'1px solid #e5e7eb' }} />
              {error && <div style={{ color:'#ef4444', fontSize:12 }}>{error}</div>}
              <button type="submit" disabled={loading} style={{ padding:'12px 14px', borderRadius:10, border:'1px solid #e6e6e6', background:'#10b981', color:'#fff', cursor:'pointer' }}>{loading ? 'Creating account...' : 'Create account'}</button>
              {providers?.google && (
                <button type="button" onClick={handleGoogle} style={{ padding:'12px 14px', borderRadius:10, border:'1px solid #e6e6e6', background:'#fff', cursor:'pointer' }}>Sign up with Google</button>
              )}
            </div>
          </form>
          <div style={{ marginTop:12, color:'#6b7280', fontSize:14 }}>
            Already have an account? <a href="/auth/signin" style={{ color:'#2563eb', textDecoration:'none' }}>Sign in</a>
          </div>
        </div>
      </div>
    </>
  );
}
