// @flow
import * as React from 'react';
import Heading from './Heading';
import Form from './Form';
import TextInputBig from './TextInputBig';
import Error from './Error';
import { SignInButton, SignUpButton } from './buttons';
import SigninMutation from '../../mutations/SigninMutation';
import SignupMutation from '../../mutations/SignupMutation';
import Router from 'next/router';
import Mutation from './Mutation';
import * as validation from '../../server/validation';
import { setCookie } from '../app/cookie';
import type { Errors } from '../../server/error';
import { defineMessages, type IntlShape } from 'react-intl';
import type { Href } from '../app/sitemap';
import withIntl from './withIntl';
import { View } from 'react-native';
import Row from './Row';
import Block from './Block';

const messages = defineMessages({
  emailPlaceholder: {
    defaultMessage: 'email',
    id: 'auth.emailPlaceholder',
  },
  passwordPlaceholder: {
    defaultMessage: 'password',
    id: 'auth.passwordPlaceholder',
  },
});

type AuthProps = {|
  redirectUrl?: Href,
  intl: IntlShape,
|};

type Fields = {|
  email: string,
  password: string,
|};

type AuthState = {|
  ...Fields,
  errors: Errors<Fields>,
|};

// https://stackoverflow.com/questions/2781549/removing-input-background-colour-for-chrome-autocomplete/32505530#32505530
const DisableWebkitAutofillColor = () => (
  <style jsx global>{`
    input:-webkit-autofill,
    input:-webkit-autofill:hover,
    input:-webkit-autofill:focus,
    input:-webkit-autofill:active {
      -webkit-transition: 'color 9999s ease-out, background-color 9999s ease-out';
      -webkit-transition-delay: 9999s;
    }
  `}</style>
);

class Auth extends React.PureComponent<AuthProps, AuthState> {
  static initialState = {
    email: '',
    password: '',
    errors: {},
  };

  state = Auth.initialState;

  setEmail = email => this.setState({ email });
  setPassword = password => this.setState({ password });

  setFocusOnError(errors: Errors<Fields>) {
    const field = Object.keys(errors)[0];
    if (!field) return;
    let current;
    switch (field) {
      case 'email':
        current = this.emailRef.current;
        break;
      case 'password':
        current = this.passwordRef.current;
        break;
      default:
        // eslint-disable-next-line no-unused-expressions
        (field: empty);
    }
    if (current) current.focus();
  }

  setErrors(errors: Errors<Fields>) {
    this.setState({ errors });
    this.setFocusOnError(errors);
  }

  handleCompleted = (response: *) => {
    // http://graphql.org/learn/best-practices/#nullability
    const payload = response.signin || response.signup || null;
    // https://flow.org/en/docs/lang/refinements
    if (payload == null) return;
    const { token } = payload;
    setCookie({ token });
    if (Router.query.redirectUrl) {
      Router.replace(Router.query.redirectUrl);
    } else if (this.props.redirectUrl) {
      Router.replace(this.props.redirectUrl);
    } else {
      Router.replace({
        pathname: Router.pathname,
        query: Router.query,
      });
    }
  };

  handleError = (errors: *) => {
    this.setErrors(errors);
  };

  auth = (mutate: *, isSignUp?: boolean) => () => {
    const variables = {
      email: this.state.email,
      password: this.state.password,
    };

    const errors = validation.validateEmailPassword(variables);
    if (errors) {
      this.setErrors(errors);
      return;
    }

    if (isSignUp === true) {
      mutate(
        SignupMutation.commit,
        variables,
        this.handleCompleted,
        this.handleError,
      );
    } else {
      mutate(
        SigninMutation.commit,
        variables,
        this.handleCompleted,
        this.handleError,
      );
    }
  };

  // $FlowFixMe
  emailRef = React.createRef();

  // $FlowFixMe
  passwordRef = React.createRef();

  render() {
    const { intl } = this.props;
    return (
      <Mutation>
        {({ mutate, pending }) => (
          <View>
            <DisableWebkitAutofillColor />
            <Heading size={3}>Auth</Heading>
            <Form onSubmit={this.auth(mutate)}>
              <Block>
                <TextInputBig
                  autoComplete="email"
                  disabled={pending}
                  error={<Error>{this.state.errors.email}</Error>}
                  keyboardType="email-address"
                  name="email"
                  onChangeText={this.setEmail}
                  placeholder={intl.formatMessage(messages.emailPlaceholder)}
                  value={this.state.email}
                  inputRef={this.emailRef}
                />
                <TextInputBig
                  disabled={pending}
                  error={<Error>{this.state.errors.password}</Error>}
                  name="password"
                  onChangeText={this.setPassword}
                  placeholder={intl.formatMessage(messages.passwordPlaceholder)}
                  secureTextEntry
                  value={this.state.password}
                  inputRef={this.passwordRef}
                />
              </Block>
              <Row>
                <SignInButton
                  disabled={pending}
                  onPress={this.auth(mutate)}
                  color="primary"
                />
                <SignUpButton
                  disabled={pending}
                  onPress={this.auth(mutate, true)}
                />
              </Row>
            </Form>
          </View>
        )}
      </Mutation>
    );
  }
}

export default withIntl(Auth);

@@ -1212,473 +1212,8 @@
 %7D;%0A%0A
-// https://stackoverflow.com/questions/2781549/removing-input-background-colour-for-chrome-autocomplete/32505530#32505530%0Aconst DisableWebkitAutofillColor = () =%3E (%0A  %3Cstyle jsx global%3E%7B%60%0A    input:-webkit-autofill,%0A    input:-webkit-autofill:hover,%0A    input:-webkit-autofill:focus,%0A    input:-webkit-autofill:active %7B%0A      -webkit-transition: 'color 9999s ease-out, background-color 9999s ease-out';%0A      -webkit-transition-delay: 9999s;%0A    %7D%0A  %60%7D%3C/style%3E%0A);%0A%0A
 clas
@@ -3537,51 +3537,8 @@
 ew%3E%0A
-            %3CDisableWebkitAutofillColor /%3E%0A
     

Remove DisableWebkitAutofillColor