import {
  AppBar,
  Button,
  Checkbox,
  FormControlLabel,
  FormGroup,
  IconButton,
  Theme,
  Toolbar,
  Typography
} from "@mui/material";
import ResponsiveDialog from "common/ResponsiveDialog";
import CloseIcon from "@mui/icons-material/Close";
import React, { useState } from "react";
import TeamSearch from "./TeamSearch";
import { useTeamAPI } from "providers/pond/teamAPI";
import { useGlobalState, useUserAPI } from "providers";
import { Team } from "models";
import { makeStyles } from "@mui/styles";

interface Props {
  open: boolean;
  setOpen: (value: React.SetStateAction<boolean>) => void;
  title?: string;
  info?: string;
  hideKey?: string;
}

const useStyles = makeStyles((theme: Theme) => {
  return ({
    title: {
      marginLeft: theme.spacing(2),
      marginRight: theme.spacing(2),
      flex: 1
    },
    searchBar: {
      margin: theme.spacing(1)
    },
    viewingAs: {
      margin: theme.spacing(2)
    }
  })
});

export default function TeamDialog(props: Props) {
  const { open, setOpen, title, info, hideKey } = props;
  const teamAPI = useTeamAPI();
  const userAPI = useUserAPI();
  const [, dispatch] = useGlobalState();
  const [teamKey, setTeamKey] = useState<string>("");
  const [{ team, user }] = useGlobalState();
  const [viewAsTeam, setViewAsTeam] = useState(user.settings.useTeam)
  const [doNotShow, setDoNotShow] = useState(false)
  const classes = useStyles();

  const shouldHide = hideKey ?
    (localStorage.getItem(hideKey) === "true" ? true : false)
  : false

  const setTeam = () => {
    onClose()
    dispatch({ key: "as", value: teamKey });
    if (teamKey === "" || teamKey.includes("auth")) {
      dispatch({ key: "team", value: Team.create() });
      return;
    }
    teamAPI.getTeam(teamKey).then(team => {
      dispatch({ key: "team", value: team });
      user.settings.defaultTeam = team.key();
      user.settings.useTeam = viewAsTeam; //when selecting a team now set to view as team by default
      userAPI.updateUser(user.id(), user.protobuf());
    });
  };

  const onClose = () => {
    console.log("close")
    setOpen(false)
    if (hideKey) localStorage.setItem(hideKey, ""+doNotShow)
  }

  return (
    <ResponsiveDialog open={open && !shouldHide} onClose={onClose}>
      <AppBar position="relative">
        <Toolbar>
          <IconButton
            edge="start"
            color="inherit"
            onClick={() => setOpen(false)}
            aria-label="close">
            <CloseIcon />
          </IconButton>
          <Typography variant="h6" className={classes.title}>
            { title ? title : "Select a Team to View As"}
          </Typography>
          <Button color="inherit" onClick={setTeam} >
            Save
          </Button>
        </Toolbar>
      </AppBar>
      {team.settings.name && (
        <Typography variant="body1" className={classes.viewingAs}>
          Viewing as: {team.name()}
        </Typography>
      )}
      {info && 
        <Typography variant="body1" className={classes.viewingAs}>
          {info}
        </Typography>
      }
      <TeamSearch
        //style={{ width: theme.spacing(32) }}
        className={classes.searchBar}
        loadUsers={user.hasFeature("admin")}
        setTeamCallback={setTeamKey}
      />
      {/* <Checkbox checked={viewAsTeam} onChange={() => setViewAsTeam(!viewAsTeam)}  /> */}
      <FormGroup sx={{ margin: 1, marginLeft: 2 }}>
        <FormControlLabel 
          control={
            <Checkbox 
              checked={viewAsTeam} 
              onChange={() => setViewAsTeam(!viewAsTeam)} 
            />
          } 
          label="View as team" 
        />
      </FormGroup>
      {hideKey && <FormGroup sx={{ margin: 1, marginLeft: 2 }}>
        <FormControlLabel 
          control={
            <Checkbox 
              checked={doNotShow} 
              onChange={() => setDoNotShow(!doNotShow)} 
            />
          } 
          label="Do not show again" 
        />
      </FormGroup>}
    </ResponsiveDialog>
  );
}
