import { FormEvent, useEffect, useState } from "react";
import { apiAuth, loadPlayers, User } from "./api";
import { useSession } from "./Session";

export const TeamPanel = () => {
  const { teams } = useSession();
  const newPlayerTemplate = {
    id: 0,
    username: "",
    display_name: "",
    number: "",
    email: "",
  } as User;
  const [error, setError] = useState("");
  const [players, setPlayers] = useState<User[] | null>(null);
  const [player, setPlayer] = useState(newPlayerTemplate);

  useEffect(() => {
    if (teams) {
      loadPlayers(teams.activeTeam).then((data) => setPlayers(data));
    }
  }, [teams]);

  async function handleSubmit(e: FormEvent) {
    e.preventDefault();
    if (teams) {
      const r = await apiAuth(
        `player/add/${teams?.activeTeam}`,
        player,
        "POST"
      );
      if (r.detail) setError(r.detail);
    }
  }

  if (teams) {
    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)}
                  >
                    {p.display_name}
                  </button>
                ))}
              <button
                className="team-player new-player"
                key="add-player"
                onClick={() => setPlayer(newPlayerTemplate)}
              >
                +
              </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, ""),
                  })
                }
              />
            </div>
            <div>
              <label>username</label>
              <input
                type="text"
                required
                value={player.username}
                onChange={(e) =>
                  setPlayer({ ...player, username: e.target.value })
                }
              />
            </div>
            <div>
              <label>number</label>
              <input
                type="text"
                value={player.number}
                onChange={(e) =>
                  setPlayer({ ...player, number: e.target.value })
                }
              />
            </div>
            <div>
              {error && (
                <span style={{ color: "red", margin: "auto" }}>{error}</span>
              )}
            </div>
            <button className="team-player new-player">
              {player.id === 0 ? "add player" : "modify player"}
            </button>
          </form>
        </div>
      </div>
    );
  } else <span className="loader" />;
};
