'use client';

import { useState } from 'react';

import Link from 'next/link';

import style from '@/styles/admin.module.scss';

export default function AdminRegisterPage() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [loading, setLoading] = useState(false);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError('');
    setSuccess('');
    setLoading(true);
    try {
      const res = await fetch('/api/auth/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setError((data as { error?: string }).error ?? 'Registration failed');
        setLoading(false);
        return;
      }
      setSuccess((data as { message?: string }).message ?? 'Registered.');
      setEmail('');
      setPassword('');
    } catch {
      setError('Network error');
    }
    setLoading(false);
  }

  return (
    <div className={style.card}>
      <h1 className={style.title}>Register</h1>
      <p className={style.sub}>
        After registering, wait for an administrator to approve your account. Then you can{' '}
        <Link href="/admin/login">sign in</Link>.
      </p>
      <form className={style.form} onSubmit={onSubmit}>
        <label className={style.label}>
          Email
          <input
            className={style.input}
            type="email"
            autoComplete="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
          />
        </label>
        <label className={style.label}>
          Password (min. 8 characters)
          <input
            className={style.input}
            type="password"
            autoComplete="new-password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            minLength={8}
            required
          />
        </label>
        {error ? <p className={style.error}>{error}</p> : null}
        {success ? <p className={style.success}>{success}</p> : null}
        <button className={style.btn} type="submit" disabled={loading}>
          {loading ? 'Submitting…' : 'Register'}
        </button>
      </form>
    </div>
  );
}
