import { useEffect, useState } from "react";
import { apiAuth } from "./api";
import { PlayerRanking } from "./types";
import RaceChart from "./RaceChart";
import { useSession } from "./Session";
import { useNavigate } from "react-router";

const MVPChart = () => {
  let initialData = {} as PlayerRanking[];
  const [data, setData] = useState(initialData);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [showStd, setShowStd] = useState(false);
  const { user, teams } = useSession();
  const navigate = useNavigate();
  useEffect(() => {
    user?.scopes.includes(`team:${teams?.activeTeam}`) ||
      navigate("/", { replace: true });
  }, [user]);

  async function loadData() {
    setLoading(true);
    if (teams) {
      await apiAuth(`analysis/mvp/${teams?.activeTeam}`, null)
        .then((data) => {
          if (data.detail) {
            setError(data.detail);
            return initialData;
          } else {
            setError("");
            return data as Promise<PlayerRanking[]>;
          }
        })
        .then((data) => {
          setData(data.sort((a, b) => a.rank - b.rank));
        })
        .catch(() => setError("no access"));
      setLoading(false);
    } else setError("team unknown");
  }

  useEffect(() => {
    loadData();
  }, [teams]);

  if (loading) return <span className="loader" />;
  else if (error) return <span>{error}</span>;
  else return <RaceChart std={showStd} players={data} />;
};

export default MVPChart;
