import { useDeviceAPI, useMobile, useUserAPI } from "hooks";
import PageContainer from "./PageContainer";
import { useEffect, useState } from "react";
import { Button, CircularProgress, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, Divider, Typography } from "@mui/material";
import { useBinAPI, useGlobalState, useTeamAPI } from "providers";
import { CheckCircleOutline } from "@mui/icons-material";
import { green } from "@mui/material/colors";
import Tour, { TourStep } from "common/Tour";
import Emoji from "react-emoji-render";
import { getWhitelabel, IsAdaptiveAgriculture } from "services/whiteLabel";
// import { color } from "framer-motion";

// interface Props {

// }

// export default function SignupCallback (props: Props) {
export default function SignupCallback () {
  const userAPI = useUserAPI();
  const teamAPI = useTeamAPI()
  const deviceAPI = useDeviceAPI();
  const binAPI = useBinAPI();
  const isMobile = useMobile()
  const [{ user }] = useGlobalState();
  const whiteLabel = getWhitelabel()

  const [loading, setLoading] = useState(false)
  const [signupDialogOpen, setSignupDialogOpen] = useState(true)
  const [hasTeams, setHasTeams] = useState(false)
  const [hasDevices, setHasDevices] = useState(false)
  const [hasBins, setHasBins] = useState(false)
  const [isTourRunning, setIsTourRunning] = useState(false);
  const [stepIndex, setStepIndex] = useState(0)

  const [doneBins, setDoneBins] = useState(false)
  const [doneTeams, setDoneTeams] = useState(false)
  const [doneDevices, setDoneDevices] = useState(false)

  useEffect(() => {
    setLoading(true)
    userAPI.completeSignup().then(() => {
      teamAPI.listTeams(1, 0).then(resp => {
        setHasTeams(resp.data.teams.length > 0)
      }).finally(() => setDoneTeams(true))
      deviceAPI.list(1, 0).then(resp => {
        setHasDevices(resp.data.devices.length > 0)
      }).finally(() => setDoneDevices(true))
      binAPI.listBins(1, 0).then(resp => {
        setHasBins(resp.data.bins.length > 0)
      }).finally(() => setDoneBins(true))
    }).finally(() => setLoading(false))
  }, [])

  const loadingComplete = () => {
    return loading === false && doneBins && doneTeams && doneDevices
  }

  const content = () => {
    return (
      <DialogContent sx={{ margin: "auto", textAlign: "center" }}>
        { loadingComplete() ? 
          <CheckCircleOutline sx={{ fontSize: 64, color: green[500] }}/>
        : 
          <CircularProgress size={64}/>
        }
        <DialogContentText sx={{marginTop: 2}}>
          {hasTeams && "Teams found!"}
          <br/>
          {hasDevices && "Devices found!"}
          <br/>
          {hasBins && "Bins found!"}
        </DialogContentText>
      </DialogContent>
    )
  }

  const getTourSteps = (): TourStep[] => {
    let steps: TourStep[] = [
      {
        title: (
          <>
            Welcome to {whiteLabel.name}
            <Emoji text=" 🎉" />
          </>
        ),
        content: (
          <>
            <Typography variant="subtitle2" gutterBottom>
              {"Hello " + user.name()}
              <Emoji text=" 👋" />
            </Typography>
            <Typography variant="body2">
              Thank you for signing up! Let me give you the tour 
              <Emoji text=" 😊" />
            </Typography>
          </>
        ),
        target: "body",
        placement: "center",
        disableBeacon: true,
      },
      {
        title: "User Menu",
        content: (
          <>
            <Typography variant="body2" >
              In the user menu, you can make changes to your profile, and adjust unit preferences.
            </Typography>
            <br/>
            <Typography variant="body2" >
              If you are part of a team, you can select it here as well.
            </Typography>
          </>
        ),
        target: "#tour-user-menu",
        placement: "bottom",
        disableBeacon: true,
        // onNext: () => setDoneFirst(true)
      },
      // {
      //   title: 
      // }
    ];
    if (hasTeams) steps.push({
      title: "Teams",
      content: (
        <>
          <Typography variant="body2" >
            Here, you can view your team(s), access their settings, and choose your favourite.
          </Typography>
        </>
      ),
      target: "#tour-teams",
      placement: "right",
      // spotlightPadding: 50,
    })
    steps.push({
      title: "Devices",
      content: (
        <>
          <Typography variant="body2" >
            You can view your devices and their readings here.
          </Typography>
          <br/>
          <Typography>
            If you are viewing as a team, your team's devices will be displayed here instead.
          </Typography>
        </>
      ),
      target: "#tour-dashboard",
      placement: "right"
    })
    if (IsAdaptiveAgriculture()) steps.push({
      title: "Bins",
      content: (
        <>
          <Typography variant="body2" >
            You can view your bins and their inventory here.
          </Typography>
          <br/>
          <Typography>
            If you are viewing as a team, your team's bins will be displayed here instead.
          </Typography>
        </>
      ),
      target: "#tour-bins",
      placement: "right",
      disableBeacon: true,
    })
    return steps;
  };

  const endTour = () => {
    setIsTourRunning(false);
    // if (user) {
    //   user.status.finishedBinIntro = moment().toJSON();
    //   userAPI
    //     .updateUser(userID, user.protobuf())
    //     .then(() => dispatch({ key: "user", value: user }))
    //     .catch((err: any) => error(err));
    // }
  };

  const closeDialog = () => {
    setSignupDialogOpen(false)
    setIsTourRunning(true)
  }

  useEffect(() => {
    console.log(stepIndex)
  }, [stepIndex])

  return (
    <PageContainer spacing={1}>
      <Dialog open={signupDialogOpen} fullScreen={isMobile} >
        <DialogTitle>
          Finishing Signup
        </DialogTitle>
        <Divider sx={{ marginBottom: 2 }}/>
        { content() }
        <DialogActions>
          {loadingComplete() && 
            <Button onClick={closeDialog}> 
              Done
            </Button>
          }
        </DialogActions>
      </Dialog>
      <Tour 
        setStepIndex={setStepIndex} 
        spotlightStyle={{ marginTop: stepIndex!==1 ? 74 : 1 }} 
        run={isTourRunning} steps={getTourSteps()} 
        endTourCallback={endTour} 
      />
    </PageContainer>
  )
}