import { useMutation } from "@apollo/client";
import styled from "@emotion/styled";
import React, { useState } from "react";
import { CurrentUser_me } from "../graphql/generated/types";
import { UPDATE_USER } from "../graphql/mutations";
import withPlatform, { PlatformProps } from "../platform/withPlatform";

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

function ProfileSettings(props: Props) {
  const [profilePicture, setProfilePicture] = useState<File | null>(null);
  const [updateUser, { loading: updateUserLoading }] = useMutation(UPDATE_USER);

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

  return (
    <Container>
      <input
        type="file"
        onChange={(event) => {
          if (event?.target?.files?.length) {
            setProfilePicture(event.target.files[0]);
          }
        }}
      />
      <button onClick={saveUserSettings as any}>Upload</button>
    </Container>
  );
}

export default withPlatform(ProfileSettings);

const Container = styled.div`
  height: 100%;
  width: 100%;
`;
