import { LogIn } from 'lucide-react';
import { useState } from 'react';
import { api, errorMessage } from '../api.js';

export function Login({ onLogin }) {
  const [username, setUsername] = useState('admin');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [busy, setBusy] = useState(false);

  async function submit(event) {
    event.preventDefault();
    setBusy(true);
    setError('');
    try {
      await api.post('/auth/login', { username, password });
      await onLogin();
    } catch (requestError) {
      setError(errorMessage(requestError));
    } finally {
      setBusy(false);
    }
  }

  return (
    <main className="flex min-h-screen items-center justify-center bg-zinc-950 px-4 text-zinc-100">
      <form className="w-full max-w-sm rounded-md border border-zinc-800 bg-zinc-900/70" onSubmit={submit}>
        <div className="border-b border-zinc-800 px-4 py-3">
          <h1 className="text-sm font-semibold">Incus Backup Control</h1>
        </div>
        <div className="space-y-4 p-4">
          {error ? <div className="rounded-md border border-red-900 bg-red-950/50 px-3 py-2 text-sm text-red-200">{error}</div> : null}
          <label className="block text-sm text-zinc-300">
            Username
            <input
              className="mt-2 h-10 w-full rounded-md border border-zinc-700 bg-zinc-950 px-3 text-zinc-100 outline-none focus:border-cyan-600"
              onChange={(event) => setUsername(event.target.value)}
              value={username}
            />
          </label>
          <label className="block text-sm text-zinc-300">
            Password
            <input
              className="mt-2 h-10 w-full rounded-md border border-zinc-700 bg-zinc-950 px-3 text-zinc-100 outline-none focus:border-cyan-600"
              onChange={(event) => setPassword(event.target.value)}
              type="password"
              value={password}
            />
          </label>
        </div>
        <div className="flex justify-end border-t border-zinc-800 px-4 py-3">
          <button
            className="inline-flex h-9 items-center gap-2 rounded-md border border-cyan-800 bg-cyan-950 px-3 text-sm text-cyan-100 hover:bg-cyan-900"
            disabled={busy}
            type="submit"
          >
            <LogIn className="h-4 w-4" />
            Login
          </button>
        </div>
      </form>
    </main>
  );
}
