import styled from "@emotion/styled";
import React, { useState } from "react";
import { useMutation, useQuery } from "react-apollo";
import { RouteComponentProps, withRouter } from "react-router-dom";
import { CreateSlideshow, CurrentUser } from "../graphql/generated/types";
import { CREATE_SLIDESHOW } from "../graphql/mutations";
import { CURRENT_USER } from "../graphql/queries";
import withPlatform, { PlatformProps } from "../platform/withPlatform";

type Props = {} & PlatformProps & RouteComponentProps;

function MainPage(props: Props) {
  const { data } = useQuery<CurrentUser>(CURRENT_USER);
  const [createSlideshow] = useMutation<CreateSlideshow>(CREATE_SLIDESHOW);
  const [title, setTitle] = useState<string>("");

  if (!data || !data.me) {
    return <Container>Not logged in</Container>;
  }

  const user = data.me;

  const attemptCreateSlideshow = async () => {
    await createSlideshow({
      variables: {
        input: {
          title: title,
          teamId: user.team.id,
        },
      },
    });
  };

  if (user.team.slideshows.length) {
    /*
     * TODO: FIXME: At current time of writing, only support one slideshow at a time.
     * But if you have multiple then the order received is random, causing the screen
     *   to render a random one on page load. Sort right now to standardize which one
     *   shows up.
     */
    const sortedSlideshows = user.team.slideshows.sort((a, b) => {
      return a.id.localeCompare(b.id);
    });
    // props.history.push(`/slideshow/${sortedSlideshows[0].id}`);
  }

  return (
    <Container>
      <div>Logged In!</div>
      <div>Name: {user.name}</div>
      <input
        placeholder="Slideshow Title"
        value={title}
        onChange={(e) => setTitle(e.target.value)}
      />
      <button onClick={attemptCreateSlideshow}>Create Slideshow</button>
      <SlideshowList>
        {user.team.slideshows.map((slideshow, index) => (
          <div
            onClick={() => props.history.push(`/slideshow/${slideshow.id}`)}
            key={index}
          >
            Slideshow: {slideshow.id}
          </div>
        ))}
      </SlideshowList>
    </Container>
  );
}

export default withRouter(withPlatform(MainPage));

const Container = styled.div``;

const SlideshowList = styled.div`
  display: flex;
  flex-direction: column;
`;
