import { FormEvent, useEffect, useState } from "react";
import { apiAuth, loadPlayers, User } from "./api";
import { useSession } from "./Session";
import { ErrorState } from "./types";
import { useNavigate } from "react-router";

const TeamPanel = () => {
  const { user, teams } = useSession();
  const navigate = useNavigate();
  useEffect(() => {
    user?.scopes.includes(`team:${teams?.activeTeam}`) ||
      navigate("/", { replace: true });
  }, [user]);
  const newPlayerTemplate = {
    id: 0,
    username: "",
    display_name: "",
    number: "",
    email: "",
  } as User;
  const [error, setError] = useState<ErrorState>();
  const [players, setPlayers] = useState<User[] | null>(null);
  const [player, setPlayer] = useState(newPlayerTemplate);

  useEffect(() => {
    if (teams) {
      setError({ ok: true, message: "" });
      loadPlayers(teams.activeTeam).then((data) => setPlayers(data));
    }
  }, [teams]);

  async function handleSubmit(e: FormEvent) {
    e.preventDefault();
    if (teams) {
      if (player.id === 0) {
        const r = await apiAuth(`player/${teams?.activeTeam}`, player, "POST");
        if (r.detail) setError({ ok: false, message: r.detail });
        else {
          setError({ ok: true, message: r });
          loadPlayers(teams.activeTeam).then((data) => setPlayers(data));
        }
      } else {
        const r = await apiAuth(`player/${teams?.activeTeam}`, player, "PUT");
        if (r.detail) setError({ ok: false, message: r.detail });
        else {
          setError({ ok: true, message: r });
          loadPlayers(teams.activeTeam).then((data) => setPlayers(data));
        }
      }
    }
  }

  async function handleDisable(e: FormEvent) {
    e.preventDefault();
    if (teams && player.id !== 0) {
      var confirmation = confirm("are you sure?");
      if (confirmation) {
        const r = await apiAuth(
          `player/${teams?.activeTeam}`,
          { player_id: player.id },
          "DELETE"
        );
        if (r.detail) setError({ ok: false, message: r.detail });
        else {
          setError({ ok: true, message: r });
          setPlayer(newPlayerTemplate);
          loadPlayers(teams.activeTeam).then((data) => setPlayers(data));
        }
      }
    }
  }

  if (teams && players) {
    const activeTeam = teams.teams.filter(
      (team) => team.id == teams?.activeTeam
    )[0];
    return (
      <div className="team-panel">
        <h1>{activeTeam.name}</h1>
        <div>
          <input type="text" value={activeTeam.location || ""} disabled />
          <br />
          <input type="text" value={activeTeam.country || ""} disabled />
          <hr style={{ width: "100%" }} />

          <h2>players</h2>
          {players ? (
            <div
              style={{
                display: "flex",
                flexWrap: "wrap",
                justifyContent: "center",
              }}
            >
              {players &&
                players.map((p) => (
                  <button
                    className="team-player"
                    key={p.id}
                    onClick={() => {
                      setPlayer(p);
                      setError({ ok: true, message: "" });
                    }}
                  >
                    {p.display_name}
                  </button>
                ))}
              <button
                className="team-player new-player"
                key="add-player"
                onClick={() => {
                  setPlayer(newPlayerTemplate);
                  setError({ ok: true, message: "" });
                }}
              >
                +
              </button>
            </div>
          ) : (
            <span className="loader" />
          )}
          <hr style={{ width: "100%" }} />

          <form className="new-player-inputs" onSubmit={handleSubmit}>
            <div>
              <label>name</label>
              <input
                type="text"
                required
                value={player.display_name}
                onChange={(e) => {
                  setPlayer({
                    ...player,
                    display_name: e.target.value,
                    username: e.target.value.toLowerCase().replace(/\W/g, ""),
                  });
                  setError({ ok: true, message: "" });
                }}
              />
            </div>
            <div>
              <label>username</label>
              <input
                type="text"
                required
                disabled={player.id !== 0}
                value={player.username}
                onChange={(e) => {
                  setPlayer({ ...player, username: e.target.value });
                  setError({ ok: true, message: "" });
                }}
              />
            </div>
            <div>
              <label>number (optional)</label>
              <input
                type="text"
                value={player.number || ""}
                onChange={(e) => {
                  setPlayer({ ...player, number: e.target.value });
                  setError({ ok: true, message: "" });
                }}
              />
            </div>
            <div>
              <label>email (optional)</label>
              <input
                type="email"
                value={player.email || ""}
                onChange={(e) => {
                  setPlayer({ ...player, email: e.target.value });
                  setError({ ok: true, message: "" });
                }}
              />
            </div>
            <div style={{ margin: "auto" }}>
              {error?.message && (
                <span
                  style={{
                    color: error.ok ? "green" : "red",
                  }}
                >
                  {error.message}
                </span>
              )}
            </div>
            <div style={{ margin: "auto" }}>
              <button className="team-player new-player">
                {player.id === 0 ? "add player" : "modify player"}
              </button>
            </div>
            {player.id !== 0 && (
              <div style={{ margin: "auto" }}>
                <button
                  className="team-player disable-player"
                  onClick={handleDisable}
                >
                  remove player
                </button>
              </div>
            )}
          </form>
        </div>
      </div>
    );
  } else <span className="loader" />;
};
export default TeamPanel;
