import {
  Box,
  Button,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Tab,
  Tabs,
  TextField,
  Typography,
  useTheme,
} from "@mui/material";
import ResponsiveDialog from "common/ResponsiveDialog";
import { Team } from "models";
import { pond } from "protobuf-ts/pond";
import { useSnackbar, useTeamAPI } from "providers";
import React, { useEffect, useState } from "react";
import DeleteButton from "common/DeleteButton";
import { userRoleFromPermissions } from "pbHelpers/User";
import { IconPicker } from "common/IconPicker";
import CancelSubmit from "common/CancelSubmit";

interface Props {
  teamDialogOpen: boolean;
  closeTeamDialogCallback: () => void;
  refreshCallback?: () => void;
  team?: Team;
  permissions?: pond.Permission[];
}

export default function TeamSettings(props: Props) {
  const theme = useTheme();
  const teamAPI = useTeamAPI();
  const { teamDialogOpen, closeTeamDialogCallback, permissions, refreshCallback } = props;
  const [loading, setLoading] = useState<boolean>(false);
  const [nameField, setNameField] = useState<string>("");
  const [infoField, setInfoField] = useState<string>("");
  const [url, setUrl] = useState<string>("");
  const snackbar = useSnackbar();
  const [tab, setTab] = useState(0);
  const [team, setTeam] = useState<Team>();
  const [teamKey, setTeamKey] = useState<string>();
  const [openDelete, setOpenDelete] = useState(false);

  useEffect(() => {
    if (props.team) {
      setTeam(props.team);
      setTeamKey(props.team.key());
    }
  }, [props.team]);

  useEffect(() => {
    if (team) {
      setNameField(team.name());
      setInfoField(team.settings.info);
      setUrl(team.settings.avatar);
    }
  }, [team]);

  const removeTeam = () => {
    if (team?.key())
      teamAPI
        .removeTeam(team?.key())
        .then(() => {
          snackbar.info("Team removed successfully.");
          if (refreshCallback) refreshCallback();
          closeTeamDialogCallback();
        })
        .catch(err => {
          console.log(err);
        });
  };

  const addTeam = () => {
    let team = pond.TeamSettings.create();
    team.name = nameField;
    team.info = infoField;
    setLoading(true);
    teamAPI
      .addTeam(team)
      .then(resp => {
        snackbar.success("Team added successfully!");
        setTab(1);
        let t = pond.Team.create();
        t.settings = team;
        setTeam(Team.create(t));
        setTeamKey(resp.data.team);
        if (refreshCallback) refreshCallback();
      })
      .catch(err => {
        snackbar.error(err);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const updateTeam = () => {
    let newTeam = pond.TeamSettings.create();
    newTeam.name = nameField;
    newTeam.info = infoField;
    newTeam.avatar = url;
    if (teamKey) {
      teamAPI
        .updateTeam(teamKey, newTeam)
        .then(() => {
          snackbar.success("Team update successfully!");
        })
        .catch(err => {
          snackbar.error(err);
        })
        .finally(() => {
          if (refreshCallback) refreshCallback();
          setNameField("");
          setInfoField("");
          setUrl("");
          setTeamKey(undefined);
          setTab(0);
          closeTeamDialogCallback();
        });
    }
  };

  const disableButton = () => {
    if (loading) return true;
    if (nameField === "" || infoField === "") return true;
  };

  const close = () => {
    setNameField("");
    setInfoField("");
    setUrl("");
    closeTeamDialogCallback();
  };

  const isOwner = () => {
    if (permissions) {
      return userRoleFromPermissions(permissions) === "Owner";
    }
    return false;
  };

  const deleteConfirmation = () => {
    return (
      <ResponsiveDialog
        open={openDelete}
        onClose={() => {
          setOpenDelete(false);
        }}>
        <DialogTitle>Delete Team</DialogTitle>
        <DialogContent>
          <Typography>
            Performing this action will delete this team and and any file attachments associated
            with it.
          </Typography>
          <Typography>Are you sure you wish to continue.</Typography>
        </DialogContent>
        <DialogActions>
          <Button
            onClick={() => {
              setOpenDelete(false);
            }}>
            Close
          </Button>
          <DeleteButton onClick={removeTeam}>Confirm</DeleteButton>
        </DialogActions>
      </ResponsiveDialog>
    );
  };

  const teamSettings = () => {
    return (
      <DialogContent>
        <DialogContentText style={{ margin: theme.spacing(1) }}>
          Add more info about your team, business, or company. You can have multiple teams if
          needed.
        </DialogContentText>
        <TextField
          label="Name"
          value={nameField}
          onChange={event => setNameField(event?.target.value)}
          variant="outlined"
          style={{ margin: theme.spacing(1) }}
          fullWidth
        />
        <div style={{ marginTop: theme.spacing(1) }} />
        <TextField
          label="Info"
          value={infoField}
          onChange={event => setInfoField(event?.target.value)}
          variant="outlined"
          style={{ margin: theme.spacing(1) }}
          fullWidth
        />
      </DialogContent>
    );
  };

  let disable = disableButton();
  return (
    <React.Fragment>
      <ResponsiveDialog open={teamDialogOpen} onClose={close}>
        <DialogTitle>{team ? "Update " + team.name() + "?" : "Create New Team?"}</DialogTitle>
        <Box style={{ borderBottom: 1, borderColor: "divider" }}>
          <Tabs
            value={tab}
            onChange={(_, value) => setTab(value)}
            aria-label="basic tabs example"
            centered>
            <Tab label="Name & Info" key={1} />
            <Tab
              label="Team Icon"
              key={2}
              disabled={team?.key() === undefined || team?.key() === ""}
            />
          </Tabs>
        </Box>
        {tab === 0 && teamSettings()}
        {tab === 1 && teamKey !== undefined && (
          <DialogContent>
            <IconPicker setUrl={setUrl} url={url} id={teamKey} />
          </DialogContent>
        )}
        <DialogActions>
          {isOwner() && (
            <DeleteButton
              onClick={() => {
                setOpenDelete(true);
              }}
              aria-label="Cancel"
              style={{ marginRight: "auto", marginLeft: theme.spacing(2) }}>
              Delete
            </DeleteButton>
          )}
          <CancelSubmit 
            onSubmit={teamKey ? updateTeam : addTeam}
            onCancel={close}
            submitDisabled={disable}
            submitText={teamKey ? "Update" : "Submit"}
          />
        </DialogActions>
      </ResponsiveDialog>
      {deleteConfirmation()}
    </React.Fragment>
  );
}
