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

import { api } from "../api/client";

export function SignInPage() {
  const navigate = useNavigate();
  const location = useLocation();
  const [error, setError] = useState<string | null>(null);

  async function handleTeamSnapStart() {
    try {
      const routeState = location.state as { from?: { pathname?: string; search?: string } } | null;
      const from = routeState?.from;
      const returnTo =
        from?.pathname && from.pathname !== "/signin"
          ? `${from.pathname}${from.search ?? ""}`
          : "/";
      const data = await api.startTeamSnap(returnTo);
      window.location.href = data.authorize_url;
    } catch (err) {
      setError(err instanceof Error ? err.message : "Unable to start TeamSnap 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">WalkUp</p>
                <h1 className="h2 mb-0">Sign in</h1>
                <p className="text-body-secondary mb-0">Use TeamSnap to continue into your team dashboard.</p>
              </div>
              <div className="d-grid gap-3">
                <p className="text-body-secondary mb-0">
                  After sign-in, you will choose your team and land in the app with your session ready.
                </p>
                <button type="button" className="btn btn-primary btn-lg w-100" onClick={handleTeamSnapStart}>
                  Sign in with TeamSnap
                </button>
              </div>
              <div className="small text-body-secondary">TeamSnap sign-in is the primary access path.</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>
  );
}
