import Head from 'next/head';
import Link from 'next/link';
import { useRouter } from 'next/router';
import { FormEvent, useState } from 'react';
import { useAuth } from '../lib/auth-context';

export default function RegisterPage() {
  const { register } = useAuth();
  const router = useRouter();
  const [form, setForm] = useState({ name: '', email: '', password: '', orgName: '' });
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);

  const set = (key: keyof typeof form) => (e: { target: { value: string } }) =>
    setForm((f) => ({ ...f, [key]: e.target.value }));

  const onSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setError(null);
    setSubmitting(true);
    try {
      await register(form);
      router.push('/');
    } catch (err: any) {
      setError(err.message || 'Registration failed');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <main style={{ fontFamily: 'sans-serif', maxWidth: 360, margin: '10vh auto', padding: '0 1rem' }}>
      <Head>
        <title>Register · UlHub</title>
      </Head>
      <h1>Create your account</h1>
      <p style={{ color: '#666' }}>Registering creates a new organization with you as its admin.</p>
      <form onSubmit={onSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '0.75rem' }}>
        <label>
          Your name
          <input value={form.name} onChange={set('name')} required style={{ width: '100%', padding: '0.5rem' }} />
        </label>
        <label>
          Email
          <input
            type="email"
            value={form.email}
            onChange={set('email')}
            required
            style={{ width: '100%', padding: '0.5rem' }}
          />
        </label>
        <label>
          Password (min 8 chars)
          <input
            type="password"
            value={form.password}
            onChange={set('password')}
            required
            minLength={8}
            style={{ width: '100%', padding: '0.5rem' }}
          />
        </label>
        <label>
          Organization name
          <input value={form.orgName} onChange={set('orgName')} required style={{ width: '100%', padding: '0.5rem' }} />
        </label>
        {error && <p style={{ color: '#c62828', margin: 0 }}>{error}</p>}
        <button type="submit" disabled={submitting} style={{ padding: '0.6rem' }}>
          {submitting ? 'Creating…' : 'Create account'}
        </button>
      </form>
      <p>
        Already registered? <Link href="/login">Log in</Link>
      </p>
    </main>
  );
}
