import { useState } from 'react';
import { login, ApiError } from '../../../lib/api';
import { useAuth } from '../../../stores/auth';

export default function Login() {
  const [value, setValue] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const setLoggedIn = useAuth(s => s.setLoggedIn);

  async function handleSubmit(e: React.SyntheticEvent<HTMLFormElement>) {
    e.preventDefault();
    const token = value.trim();
    if (!token) return;
    setBusy(true);
    setError(null);
    try {
      await login(token);
      setLoggedIn(true);
      window.location.href = '/admin';
    } catch (e) {
      if (e instanceof ApiError && e.status === 401) {
        setError('That key does not open this door.');
      } else {
        setError('Could not reach the door. Try again.');
      }
      setBusy(false);
    }
  }

  return (
    <div className="max-w-md mx-auto mt-10 md:mt-20 px-1">
      <div className="glass p-7 sm:p-10">
        <div className="font-display italic text-[var(--subtext0)] text-xs tracking-[0.3em] uppercase mb-3 text-center">
          Artist's entrance
        </div>
        <h1 className="font-display italic text-3xl md:text-4xl font-semibold text-[var(--text)] mb-2 text-center leading-tight">
          Sign in
        </h1>
        <div className="section-rule max-w-[180px] mx-auto mb-6">
          <span className="ornament">✦</span>
        </div>
        <p className="text-[var(--subtext1)] mb-8 text-center font-display italic">
          Present your token to enter the back room.
        </p>
        <form onSubmit={handleSubmit} className="space-y-6" noValidate>
          <div>
            <label htmlFor="token" className="field-label">Admin token</label>
            <input
              type="password"
              id="token"
              required
              value={value}
              onChange={e => setValue(e.target.value)}
              autoComplete="current-password"
              aria-invalid={error ? true : undefined}
              aria-describedby={error ? 'login-error' : undefined}
              className="field-input font-mono tracking-widest"
              placeholder="••••••••••••"
            />
          </div>
          {error && (
            <p
              id="login-error"
              role="alert"
              className="text-sm text-[var(--red)] bg-[var(--red)]/10 border border-[var(--red)]/30 px-3 py-2 font-display italic"
            >
              {error}
            </p>
          )}
          <button
            type="submit"
            disabled={busy}
            className="btn btn--primary btn--block btn--lg"
          >
            {busy ? 'Unlocking…' : 'Enter'}
          </button>
        </form>
      </div>
      <div className="text-center mt-6">
        <a href="/" className="back-link">
          <span className="bl-arrow" aria-hidden="true">←</span>
          Back to the catalogue
        </a>
      </div>
    </div>
  );
}
