/* @aztlan/generator-front 3.1.2 */
import * as React from 'react'
import * as PropTypes from 'prop-types'
import { InferProps } from 'prop-types'
import {
  useLocation, Link,
} from 'react-router-dom'
import { graphql } from 'react-relay'
import {
  defineMessages, useIntl,
} from 'react-intl'
import {
  LoginButton,
  useAuthenticationResource,
  useApplicationContext,
  useViewer,
} from '@aztlan/ui'

const m = defineMessages({
  title:{
    // id: `${messagesPrefix}.title`,
    description   :'Message to greet the user.',
    defaultMessage:'Login',
  },
  login:{
    description   :'Message to greet the user.',
    defaultMessage:'Please click on the button to log in.',
  },
})

function RawLogin({
  FRAGMENT,
  data,
  resource,
}: {
  FRAGMENT:any;
  data    :any;
  resource:string;
}) {
  const location = useLocation()

  const { formatMessage } = useIntl()
  return (
    <div className="container">
      {location.state?.reason && (
      <p>
        {' '}
        {location.state.reason}
      </p>
      )}
      <LoginButton
        FRAGMENT={FRAGMENT}
        data={data}
      />

      <p>{formatMessage(m.login)}</p>
      <p>
        After login you will be redirected to
        {resource}
      </p>
    </div>
  )
}

export { RawLogin }

function Login({ FRAGMENT }: { FRAGMENT: any }) {
  const {
    data, defaultRedirectionAfterLogin,
  } = useApplicationContext()
  const { data: viewerData } = useViewer()
  const resource = useAuthenticationResource()
  if (!viewerData?.id) {
    return (
      <RawLogin
        FRAGMENT={FRAGMENT}
        data={data}
        resource={resource}
      />
    )
  }
  return (
    <p>
      You are already logged in.
      <Link to={defaultRedirectionAfterLogin}>Login</Link>
    </p>
  )
}

export default Login
