import { Options } from '../interfaces/IOptions'
import { lightTheme, Typography, ThemeProvider } from '@sofaltaeu/sofaltaeu-components'
import { Paper, ContainerForm, ContainerImage, Divider, Header, LogoSofaltaeu } from './styled'
import { FormLogin } from './Login'
import { GoogleOAuthProvider } from '@react-oauth/google';
import { FacebookProvider } from 'react-facebook';

import { useMutation, useQuery } from 'react-query'
import { isOnline, tipoUsuario, usuarioPreconta } from '../services';
import Loader from './Loader';
import Error from './Error';
import { useEffect, useMemo, useState } from 'react';
import { FormEnum, useSwitchFormContext } from '../context/switchForm'
import { RecoveryPassword } from './RecoverPassword'
import { RegisterForm } from './Register'
import { NewCreateAccountProps } from '../utils/createAccount'

const clientId = "74301071159-rlp34s238k4h0u7q94rjtdhafbsaq3s0.apps.googleusercontent.com"
const FacebookAppId = '465768531975447'

//DEV --- SOCIAL
// const clientId = '482031521600-7afpm1s7ii0l1qs5l16l91rr6nsjkqfu.apps.googleusercontent.com'
// const FacebookAppId = '704023874180350'
//DEV --- SOCIAL


interface RegisterProps {
    options: Options
}
export const Register = ({ options }:RegisterProps) => {
    const logo = 'https://sofaltaeuimagens.s3.sa-east-1.amazonaws.com/sofaltaeu_logo-2.svg'
    const [isOffline, setIsOffline] = useState(false)
    const [userPreconta, setUserPreconta] = useState<NewCreateAccountProps | undefined>(undefined)
    const { form, handleFormSwitch } = useSwitchFormContext()

    const { isLoading } = useQuery({
		queryKey: ['online'],
		queryFn: ()=>isOnline(options.dominioSFE),
        onSuccess: () => { setIsOffline(false) },
        onError: () => { setIsOffline(true) },
	})

	const onlineMutation = useMutation(()=>isOnline(options.dominioSFE), {
        onSuccess: () => { setIsOffline(false) },
        onError: () => { setIsOffline(true) },
    })

    const usuarioPreContaMutation = useMutation((usuario:string)=>usuarioPreconta({ apiUrl:options.dominioSFE, usuario }), {
        onSuccess:({usuario})=>{
            const preconta = {
                usuario: usuario.usuario,
                email: usuario.email,
                sexo: 'uninf'
            }
            setUserPreconta(preconta)
            handleFormSwitch(FormEnum.register)
        }
    })

    const tipoUsuarioMutation = useMutation((usuario:string)=>tipoUsuario({ apiUrl:options.dominioSFE, usuario}), {
        onError: ({response}) => {
            if(response.status === 303 && options.identificador){
                usuarioPreContaMutation.mutate(options.identificador)
            }

            if(response.status === 409){
                const preconta = {
                    usuario: options.identificador
                }
                setUserPreconta(preconta)
            }
         },
    })


    const getLocation = () => {
        const localizacao = {
            latitude: 0,
            longitude: 0
        }

        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition((position)=>{ localizacao.latitude = position.coords.latitude, localizacao.longitude = position.coords.longitude })
            return localizacao
        }

        return localizacao
    }
    const geolocation = useMemo(getLocation,[])

    const renderForms = () =>{


        if(isOffline){
            return (<Error onClick={()=>onlineMutation.mutate()}/>)
        }

        switch (form) {
            case FormEnum.register:
                return (
                    <RegisterForm
						dominioSFE={options.dominioSFE}
                        preConta={userPreconta}
                    />
                )
            case FormEnum.recover:
                return (
                    <RecoveryPassword
						dominioSFE={options.dominioSFE}
                    />
                )
			default:
				return (
					<FormLogin
						dominioSFE={options.dominioSFE}
						empreendimento={options.empreendimento}
						plataforma={options.plataforma}
						latitude={geolocation.latitude}
						longitude={geolocation.longitude}
						onSuccess={options.callback}
                        isRegister={options.register}
                        preConta={userPreconta}
					/>
				);
		}
    }

    const titleHeader = useMemo(()=>{
        switch (form) {
            case FormEnum.register:
                return 'Crie sua conta'
            case FormEnum.recover:
                return 'Recuperar Senha'
            default:
                return 'Entrar'
        }
    },[form])

    useEffect(()=>{
        if(options.identificador){
            tipoUsuarioMutation.mutate(options.identificador)
        }
    },[])

    const renderContentContainerForm = () => {

        if(isLoading){
            return (<Loader/>)
        }

        return (
			<>
				<Header>
					<Typography variant="h5">{titleHeader}</Typography>
					<LogoSofaltaeu src={logo} />
				</Header>
				<Divider variant="fullWidth" />
				{renderForms()}
			</>
		);
    }

    return (
        <ThemeProvider theme={lightTheme}>
            <GoogleOAuthProvider clientId={clientId}>
                <FacebookProvider appId={FacebookAppId}>
                    <Paper>
                        <ContainerImage backgroundimage={options?.imagemBackground}/>
                        <ContainerForm>
                            {renderContentContainerForm()}
                        </ContainerForm>
                    </Paper>
                </FacebookProvider>
            </GoogleOAuthProvider>
        </ThemeProvider>

    )
}