import React, { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'

import { Box, Button } from '@mui/material'
import Page from 'components/page'

import { useHistory } from 'react-router-dom'
import OverviewGuestButton from '../../components/overviewGuestButton'
import GuestRegisterStep from './registerPage'
import { GuestRegisterCallableMethods } from './guestRegisterCallableMethods'
import { EnteredGuestData } from './enteredGuestData'
import { ContactInformationBySponsor } from './guestDataForm'
import AuthenticationMethod from './authenticationMethod'
import { postJsonOpts } from '../../../utils'

enum SubmitState {
  NotSubmitted,
  Submitted,
  SubmittedError,
}

/*
 * When the guest reaches this page he has already an invite ID set in his session.
 */
export default function GuestRegister() {
  const { t } = useTranslation(['common'])
  const history = useHistory()
  // TODO On submit successful the user should be directed to some page telling h
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [submitState, setSubmitState] = useState<SubmitState>(
    SubmitState.NotSubmitted
  )
  const guestRegisterRef = useRef<GuestRegisterCallableMethods>(null)
  const REGISTER_STEP = 0
  // TODO Set step when user moves between pages
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [activeStep, setActiveStep] = useState(0)

  const [guestFormData, setGuestFormData] =
    useState<ContactInformationBySponsor>({
      first_name: '',
      last_name: '',
      ou_name_en: '',
      ou_name_nb: '',
      role_name_en: '',
      role_name_nb: '',
      role_start: '',
      role_end: '',
      comment: '',
      email: '',
      mobile_phone: '',
      fnr: '',
      passport: '',
      user_information_source: AuthenticationMethod.Feide,
      fnr_verified: false,
    })

  const guestContactInfo = async () => {
    try {
      const response = await fetch('/api/ui/v1/invited')

      if (response.ok) {
        response.json().then((jsonResponse) => {
          const authenticationMethod =
            jsonResponse.meta.form_type === 'manual'
              ? AuthenticationMethod.NationalIdNumberOrPassport
              : AuthenticationMethod.Feide

          const fnrVerified = jsonResponse.meta.fnr_verified === true

          setGuestFormData({
            first_name: jsonResponse.person.first_name,
            last_name: jsonResponse.person.last_name,
            ou_name_en: jsonResponse.role.ou_name_en,
            ou_name_nb: jsonResponse.role.ou_name_nb,
            role_name_en: jsonResponse.role.role_name_en,
            role_name_nb: jsonResponse.role.role_name_nb,
            role_start: jsonResponse.role.start,
            role_end: jsonResponse.role.end,
            comment: jsonResponse.role.comments,

            email: jsonResponse.person.email,
            mobile_phone: jsonResponse.person.mobile_phone,
            fnr: jsonResponse.fnr,
            passport: jsonResponse.passport,

            user_information_source: authenticationMethod,
            fnr_verified: fnrVerified,
          })
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  useEffect(() => {
    guestContactInfo()
  }, [])

  const handleNext = () => {
    // TODO Go to consent page
    // setActiveStep((prevActiveStep) => prevActiveStep + 1)
  }

  const handleSave = () => {
    if (activeStep === 0) {
      if (guestRegisterRef.current) {
        guestRegisterRef.current.doSubmit()
      }
    }
  }

  const handleForwardFromRegister = (
    updateFormData: EnteredGuestData
  ): void => {
    const payload = {
      person: {
        mobile_phone: updateFormData.mobilePhone,
        fnr: updateFormData.nationalIdNumber,
        passport: updateFormData.passportNumber,
      },
    }

    fetch('/api/ui/v1/invited/', postJsonOpts(payload))
      .then((response) => {
        if (response.ok) {
          setSubmitState(SubmitState.Submitted)
        } else {
          setSubmitState(SubmitState.SubmittedError)
          console.error(`Server responded with status: ${response.status}`)
        }
      })
      .catch((error) => {
        console.error(error)
        setSubmitState(SubmitState.SubmittedError)
      })
  }

  const handleCancel = () => {
    history.push('/')
  }

  return (
    <Page>
      <OverviewGuestButton />
      {/* Current page in wizard */}
      <Box sx={{ width: '100%' }}>
        {activeStep === REGISTER_STEP && (
          <GuestRegisterStep
            nextHandler={handleForwardFromRegister}
            guestData={guestFormData}
            ref={guestRegisterRef}
          />
        )}
      </Box>

      <Box
        sx={{
          display: 'flex',
          flexDirection: 'row',
          pt: 2,
          color: 'primary.main',
          paddingBottom: '1rem',
        }}
      >
        {activeStep === REGISTER_STEP && (
          <Button
            data-testid="button-next"
            sx={{ color: 'theme.palette.secondary', mr: 1 }}
            onClick={handleNext}
          >
            {t('button.next')}
          </Button>
        )}

        <Button onClick={handleCancel}>{t('button.cancel')}</Button>

        {/* TODO This button is only for testing while developing */}
        <Button onClick={handleSave}>{t('button.save')}</Button>
      </Box>
    </Page>
  )
}