import { useMutation } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";

import { api } from "../api/client";
import { useWalkupContext } from "../hooks/useWalkupContext";
import { clearOfflineCache } from "../lib/offlineCache";
import { formatMemberName, formatTeamLabel } from "../lib/teamsnapHelpers";
import { queryClient } from "../lib/queryClient";

export function ProfilePage() {
  const navigate = useNavigate();
  const walkup = useWalkupContext();
  const logoutMutation = useMutation({
    mutationFn: api.logout,
    onSuccess: async () => {
      clearOfflineCache();
      queryClient.clear();
      navigate("/signin");
    },
  });

  async function reconnect() {
    const auth = await api.startTeamSnap(window.location.pathname);
    window.location.href = auth.authorize_url;
  }

  return (
    <section className="container-fluid py-4 d-grid gap-4">
      <div className="row g-4">
        <div className="col-12 col-lg-6">
          <div className="card shadow-sm h-100">
            <div className="card-body d-grid gap-3">
              <h2 className="h4 mb-0">Session</h2>
              <div className="text-body-secondary">Provider: {walkup.sessionQuery.data?.provider ?? "none"}</div>
              <div className="text-body-secondary">Authenticated: {walkup.sessionQuery.data?.authenticated ? "yes" : "no"}</div>
              <div className="text-body-secondary">
                Player: {walkup.currentPlayer ? formatMemberName(walkup.currentPlayer) : "No matching player on the selected team"}
              </div>
              <div className="d-flex flex-wrap gap-2">
                {walkup.isTeamSnap ? (
                  <button type="button" className="btn btn-outline-secondary" onClick={() => void reconnect()}>
                    Reconnect TeamSnap
                  </button>
                ) : null}
                <button type="button" className="btn btn-outline-secondary" onClick={() => void logoutMutation.mutateAsync()}>
                  {logoutMutation.isPending ? "Signing out..." : "Sign out"}
                </button>
              </div>
            </div>
          </div>
        </div>
        <div className="col-12 col-lg-6">
          <div className="card shadow-sm h-100">
            <div className="card-body d-grid gap-3">
              <h2 className="h4 mb-0">Selected team</h2>
              {walkup.isTeamSnap ? (
                <>
                  <label className="form-label d-grid gap-2">
                    <span>Team and season</span>
                    <select
                      className="form-select"
                      value={walkup.selectedTeamId}
                      onChange={(event) => walkup.selectTeam(event.target.value)}
                      disabled={walkup.teamsQuery.isLoading}
                    >
                      <option value="">Select a team</option>
                      {walkup.teamsQuery.data?.map((team) => (
                        <option key={String(team.id)} value={String(team.id)}>
                          {formatTeamLabel(team)}
                        </option>
                      ))}
                    </select>
                  </label>
                  <div className="text-body-secondary">
                    {walkup.hasSelectedTeam
                      ? `Current selection: ${formatTeamLabel(walkup.selectedTeam)}`
                      : "Pick a team to continue into the app."}
                  </div>
                </>
              ) : (
                <div className="text-body-secondary">Team selection is available for TeamSnap-backed sessions.</div>
              )}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
