import * as React from 'react';
import { Component } from 'react';
// import { withRouter } from 'react-router';
import { Redirect, withRouter } from 'react-router-dom';
import { getAndStoreParameters, getProfile, getIdToken, getEmail, getName } from '../utils/auth';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';

const signIn = gql`
	mutation($workspace_id: String) {
		signIn(workspace_id: "") {
			slack_id
		}
	}
`;

const userQuery = gql`
	query {
		viewer {
			slack_id
		}
	}
`;
class Callback extends Component {
	props: {
		signIn: typeof signIn;
		location: any;
		data: any;
	};
	state = {
		redirectToReferrer: false
	};
	componentDidMount() {
		getAndStoreParameters();
		this.createUser();
	}

	createUser = () => {
		const variables = {
			idToken: getIdToken()
		};

		this.props
			.signIn({ variables })
			.then((response) => {
				console.log('Response from create user', response);
			})
			.catch((e) => {
				console.error('Error of life ', e);
			});
	};

	render() {
		const { from } = this.props.location.state || { from: { pathname: '/' } };
		const { redirectToReferrer } = this.state;

		if (redirectToReferrer) {
			return <Redirect to={from} />;
		} else {
			return null;
		}
	}
}

export default graphql(signIn, { name: 'signIn' })(
	graphql(userQuery, { options: { fetchPolicy: 'network-only' } })(Callback)
);
