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

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

  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 });
          reloadPlayers();
        }
      } 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 });
          reloadPlayers();
        }
      }
    }
  }

  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);
          reloadPlayers();
        }
      }
    }
  }

  if (teams && players) {
    const activeTeam = teams.teams.filter(
      (team) => team.id == teams?.activeTeam
    )[0];
    return (
      <>
        <section className="section">
          <h1 className="title">{activeTeam.name}</h1>
          <h2 className="subtitle">
            {activeTeam.location}, {activeTeam.country}
          </h2>
          <div className="box">
            <h2 className="title is-4">Players</h2>
            {players ? (
              <div className="buttons">
                {players.map((p) => (
                  <button
                    className={
                      "button is-primary is-light " +
                      p.gender +
                      (p.id === player.id ? " is-focused is-active" : "")
                    }
                    key={p.id}
                    onClick={() => {
                      setPlayer(p);
                      setError({ ok: true, message: "" });
                    }}
                  >
                    {p.display_name}
                  </button>
                ))}
                <button
                  className="button is-success is-light new-player"
                  key="add-player"
                  onClick={() => {
                    setPlayer(newPlayerTemplate);
                    setError({ ok: true, message: "" });
                  }}
                >
                  +
                </button>
              </div>
            ) : (
              <span className="loader" />
            )}
          </div>

          <form className="container block" onSubmit={handleSubmit}>
            <div className="field">
              <label className="label">name</label>
              <div className="control">
                <input
                  className="input"
                  type="text"
                  required
                  value={player.display_name}
                  onChange={(e) => {
                    setPlayer({
                      ...player,
                      ...(player.id === 0 && {
                        username: e.target.value
                          .toLowerCase()
                          .replace(/\W/g, ""),
                      }),
                      display_name: e.target.value,
                    });
                    setError({ ok: true, message: "" });
                  }}
                />
              </div>
            </div>
            <div className="field">
              <label className="label">username</label>
              <div className="control">
                <input
                  className="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>
            <div className="field">
              <label className="label">gender</label>
              <div className="control">
                <div className="select">
                  <select
                    name="gender"
                    value={player.gender}
                    onChange={(e) => {
                      setPlayer({
                        ...player,
                        gender: e.target.value as Gender,
                      });
                      setError({ ok: true, message: "" });
                    }}
                  >
                    <option value={undefined}></option>
                    <option value="fmp">FMP</option>
                    <option value="mmp">MMP</option>
                  </select>
                </div>
              </div>
            </div>
            <div className="field">
              <label className="label">number (optional)</label>
              <div className="control">
                <input
                  className="input"
                  type="text"
                  value={player.number || ""}
                  onChange={(e) => {
                    setPlayer({ ...player, number: e.target.value });
                    setError({ ok: true, message: "" });
                  }}
                />
              </div>
            </div>
            <div className="field">
              <label className="label">email (optional)</label>
              <div className="control">
                <input
                  className="input"
                  type="email"
                  value={player.email || ""}
                  onChange={(e) => {
                    setPlayer({ ...player, email: e.target.value });
                    setError({ ok: true, message: "" });
                  }}
                />
              </div>
              {error?.message && (
                <p
                  className={"help" + (error.ok ? " is-success" : " is-danger")}
                >
                  {error.message}
                </p>
              )}
            </div>
            <div className="field is-grouped">
              <button
                className={
                  "button is-light" +
                  (player.id === 0 ? " is-success" : " is-link")
                }
              >
                {player.id === 0 ? "add player" : "modify player"}
              </button>
              {player.id !== 0 && (
                <button
                  className="button is-danger is-light"
                  onClick={handleDisable}
                >
                  remove player
                </button>
              )}
            </div>
          </form>
        </section>
        <section className="section">
          <Calendar playerId={player.id} />
        </section>
      </>
    );
  } else <span className="loader" />;
};
export default TeamPanel;
