'use client';

import { useRouter } from 'next/navigation';
import { useState } from 'react';

import Link from 'next/link';

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

export default function AdminLoginPage() {
  const router = useRouter();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
        credentials: 'include',
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setError((data as { error?: string }).error ?? 'Login failed');
        setLoading(false);
        return;
      }
      router.push('/admin');
      router.refresh();
    } catch {
      setError('Network error');
    }
    setLoading(false);
  }

  return (
    <div className={style.card}>
      <h1 className={style.title}>Admin login</h1>
      <p className={style.sub}>
        No account? <Link href="/admin/register">Register</Link> — an administrator must approve you before you can sign in.
      </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
          <input
            className={style.input}
            type="password"
            autoComplete="current-password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
          />
        </label>
        {error ? <p className={style.error}>{error}</p> : null}
        <button className={style.btn} type="submit" disabled={loading}>
          {loading ? 'Signing in…' : 'Sign in'}
        </button>
      </form>
    </div>
  );
}
