import styled from "@emotion/styled";
import { Button } from "evergreen-ui";
import { inject, observer } from "mobx-react";
import React, { useState } from "react";
import { useMutation, useQuery } from "react-apollo";
import {
  LIGHT_PRIMARY_ONE,
  LIGHT_PRIMARY_THREE,
  LIGHT_SECONDARY_ONE,
  LIGHT_SECONDARY_THREE,
  LIGHT_SECONDARY_TWO,
} from "../../shared/colors";
import {
  CurrentUserWithSettings,
  CurrentUser_me,
} from "../graphql/generated/types";
import { UPDATE_TEAM, UPDATE_USER } from "../graphql/mutations";
import { CURRENT_USER_WITH_SETTINGS } from "../graphql/queries";
import { StoreProps } from "../platform/SlideshowStore";
import withPlatform, { PlatformProps } from "../platform/withPlatform";
import Input from "./shared/InputWithShortcuts";

type Props = {
  user: CurrentUser_me;
} & PlatformProps &
  StoreProps;

const prefilledText = [{ type: "paragraph", children: [{ text: "" }] }];

function SettingsModal(props: Props) {
  const [userName, setUserName] = useState<string>(props.user.name || "");
  const [teamName, setTeamName] = useState<string>(
    props.user.team?.title || ""
  );
  const [email, setEmail] = useState<string>(props.user.email || "");

  const { data: userData, loading: userLoading } = useQuery<
    CurrentUserWithSettings
  >(CURRENT_USER_WITH_SETTINGS);

  const [updateUser, { loading: updateUserLoading }] = useMutation(UPDATE_USER);
  const [updateTeam, { loading: updateTeamLoading }] = useMutation(UPDATE_TEAM);

  const saveUserSettings = async (event?: KeyboardEvent) => {
    await updateUser({
      variables: {
        userId: props.user.id,
        input: {
          name: userName,
          email: email,
        },
      },
    });
    props.setNotification({
      notification: "Saved user settings!",
      timestamp: Date.now(),
    });
    event?.preventDefault();
  };

  const saveTeamSettings = async (event?: KeyboardEvent) => {
    if (!props.user.team) {
      return;
    }
    await updateTeam({
      variables: {
        teamId: props.user.team.id || "",
        input: {
          title: teamName,
        },
      },
    });
    props.setNotification({
      notification: "Saved team settings!",
      timestamp: Date.now(),
    });
    event?.preventDefault();
  };

  if (userLoading) {
    return <div>loading</div>;
  }

  const user = userData?.me!;

  return (
    <Background
      onClick={(e) => {
        props.store.showSettingsModal.set(false);
        e.stopPropagation();
      }}
    >
      <Container onClick={(e) => e.stopPropagation()}>
        <Header>
          <Title>Settings</Title>
        </Header>
        <SectionTitle>Profile</SectionTitle>
        <SectionContent>
          <SectionContentSubtitle>Name</SectionContentSubtitle>
          <StyledInput
            value={userName}
            shortcuts={[{ keys: "mod+s", callback: saveUserSettings }]}
            onChange={(event) => setUserName(event.target.value)}
            placeholder="Name"
          />
          <SectionContentSubtitle style={{ marginTop: "20px" }}>
            Email
          </SectionContentSubtitle>
          <StyledInput
            value={email}
            shortcuts={[{ keys: "mod+s", callback: saveUserSettings }]}
            onChange={(event) => setEmail(event.target.value)}
            placeholder="Email"
          />
          <StyledButton onClick={saveUserSettings}>Save</StyledButton>
        </SectionContent>
        <Separator />
        <SectionTitle>Team</SectionTitle>
        <SectionContent>
          <SectionContentSubtitle>Name</SectionContentSubtitle>
          <StyledInput
            value={teamName}
            shortcuts={[{ keys: "mod+s", callback: saveTeamSettings }]}
            onChange={(event) => setTeamName(event.target.value)}
            placeholder="Name"
          />
          <SectionContentSubtitle style={{ marginTop: "20px" }}>
            Teammates
          </SectionContentSubtitle>
          {user.team?.users.map((user) => {
            return (
              <UserRow key={user.id}>
                <UserRowUserName>{user.name}</UserRowUserName>
                <UserRowUserEmail>{user.email}</UserRowUserEmail>
              </UserRow>
            );
          })}
          <SectionContentSubtitle style={{ marginTop: 20 }}>
            To add more teammates, share the link below:
          </SectionContentSubtitle>
          <StyledButton onClick={saveTeamSettings}>Save</StyledButton>
        </SectionContent>
        <Separator />
        {/* <Separator />
        <SectionTitle>API Key</SectionTitle>
        <SectionContent>
          <APIKey organization={user.organization!} />
        </SectionContent> */}
        <Separator />
      </Container>
    </Background>
  );
}

export default withPlatform(inject("store")(observer(SettingsModal)));

const ContentContainer = styled.div`
  width: calc(100% - 252px);
  margin-left: 126px;
  margin-right: 126px;
  padding-top: 12px;
  border-top: 1px solid rgba(55, 53, 47, 0.09);
  height: 100%;
`;

const HeaderContainer = styled.div`
  margin-top: 80px;
  width: calc(100% - 252px);
  padding-left: 126px;
  padding-right: 126px;
  margin-bottom: 8px;
`;

const Background = styled.div`
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.4);
  z-index: 10;
`;

const Container = styled.div`
  display: flex;
  flex-direction: column;
  position: absolute;
  top: 72px;
  left: 72px;
  right: 72px;
  margin-left: auto;
  margin-right: auto;
  max-width: 975px;
  min-width: 975px;
  height: calc(100% - 144px);
  border-radius: 4px;
  background-color: ${LIGHT_PRIMARY_THREE};
  box-shadow: rgba(15, 15, 15, 0.05) 0px 0px 0px 1px,
    rgba(15, 15, 15, 0.1) 0px 5px 10px, rgba(15, 15, 15, 0.2) 0px 15px 40px;
  z-index: 20;
`;

const Title = styled.div`
  font-size: 40px;
  color: ${LIGHT_SECONDARY_ONE};
`;

const IconHolder = styled.div`
  display: flex;
  align-items: center;
  cursor: pointer;
`;

const Header = styled.div`
  display: flex;
  align-items: center;
  height: 60px;
  margin-left: 126px;
  margin-right: 126px;
  margin-top: 80px;
  margin-bottom: 12px;
`;

const UserRow = styled.div`
  display: flex;
  align-items: center;
  height: 40px;
`;

const UserRowUserName = styled.div`
  color: ${LIGHT_SECONDARY_ONE};
`;

const UserRowUserEmail = styled.div`
  color: ${LIGHT_SECONDARY_ONE};
  margin-left: 40px;
`;

const Separator = styled.div`
  margin-top: 40px;
  margin-bottom: 40px;
  width: 100%;
  height: 1px;
  background-color: ${LIGHT_PRIMARY_ONE};
`;

const SectionTitle = styled.div`
  font-size: 20px;
  color: ${LIGHT_SECONDARY_TWO};
  margin-bottom: 20px;
  margin-left: 126px;
  margin-right: 126px;
`;

const SectionContent = styled.div`
  display: flex;
  flex-direction: column;
  margin-left: 126px;
  margin-right: 126px;
`;

const SectionContentSubtitle = styled.div`
  color: ${LIGHT_SECONDARY_THREE};
  margin-bottom: 6px;
`;

const StyledInput = styled(Input)``;

const StyledButton = styled(Button)`
  display: flex;
  align-items: center;
  margin-top: 20px;
  align-self: flex-start;
`;
