import { FormEvent, useState } from "react";
import { useNavigate } from "react-router-dom";

import { api } from "../api/client";
import { clearOfflineCache } from "../lib/offlineCache";
import { queryClient } from "../lib/queryClient";

export function AdminPage() {
  const navigate = useNavigate();
  const [username, setUsername] = useState("admin");
  const [password, setPassword] = useState("admin");
  const [error, setError] = useState<string | null>(null);

  async function handleAdminLogin(event: FormEvent) {
    event.preventDefault();
    setError(null);
    try {
      await api.adminLogin({ username, password });
      clearOfflineCache();
      queryClient.clear();
      navigate("/");
    } catch (err) {
      setError(err instanceof Error ? err.message : "Unable to sign in");
    }
  }

  return (
    <section className="container-fluid min-vh-100 d-flex align-items-center justify-content-center py-4">
      <div className="row w-100 justify-content-center g-4">
        <div className="col-12 col-md-8 col-lg-5 col-xl-4">
          <div className="card shadow-sm border-0">
            <div className="card-body p-4 p-lg-5 d-grid gap-4">
              <div className="d-grid gap-2">
                <p className="text-uppercase small text-primary-emphasis mb-0">Support</p>
                <h1 className="h2 mb-0">Admin sign-in</h1>
                <p className="text-body-secondary mb-0">Use local credentials for bootstrap and maintenance.</p>
              </div>
              <form className="d-grid gap-3" onSubmit={handleAdminLogin}>
                <label className="form-label d-grid gap-2">
                  <span>Username</span>
                  <input className="form-control" value={username} onChange={(event) => setUsername(event.target.value)} />
                </label>
                <label className="form-label d-grid gap-2">
                  <span>Password</span>
                  <input
                    className="form-control"
                    type="password"
                    value={password}
                    onChange={(event) => setPassword(event.target.value)}
                  />
                </label>
                <button type="submit" className="btn btn-primary btn-lg">
                  Sign in
                </button>
              </form>
              <div className="small text-body-secondary">TeamSnap sign-in remains the normal entry point.</div>
            </div>
          </div>
        </div>
        {error ? (
          <div className="col-12 col-md-8 col-lg-5 col-xl-4">
            <div className="alert alert-danger mb-0" role="alert">
              {error}
            </div>
          </div>
        ) : null}
      </div>
    </section>
  );
}
