import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form'
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import {
    Button,
    Input,
    InputAdornment,
    IconButton,
    Icon
} from '@sofaltaeu/sofaltaeu-components'
import { Form, ContainerButton } from './styled'
import { CreateAccount } from '../../../interfaces/services/ICreateUser'
import { validarDadosUsuario } from '../../../services';
import { useMutation } from 'react-query';


const emailPattern = /^[a-zA-Z0-9._-]+$/;
const formLoginSchema = z
	.object({
		usuario: z
			.string()
			.min(3, "Deve conter pelo menos 3 caracteres")
			.max(100, "Deve conter no máximo 100 caracteres")
			.refine((usuario: string) => emailPattern.test(usuario), {
				message:
					"Somente letras (a-z), numeros(0-9) e pontos(.) são permitidos",
			}),
		senha: z.string().min(8),
		confirmPassword: z.string().min(8),
	})
	.superRefine(({ senha, confirmPassword }, ctx) => {
		if (confirmPassword !== senha) {
			ctx.addIssue({
				code: z.ZodIssueCode.custom,
				path: ["confirmPassword"],
				message: "A senha e a confirmação de senha não correspondem.",
			});
		}
	})



type FormLoginSchema = z.infer<typeof formLoginSchema>

interface FormLoginProps {
    nextSetp: () => void
    prevSetp: () => void
    state: CreateAccount
    setState: (payload:CreateAccount) => void,
    dominioSFE:string
    preconta?: boolean
}
export const FormLogin = ({state, nextSetp, prevSetp, setState, dominioSFE, preconta}:FormLoginProps) => {
    const getUsername = (email:string, usuario:string) => {
        if(usuario){
            return usuario
        }

        return email.split("@")[0]
    }

	const {
		register, handleSubmit, formState: { errors }, setFocus, setError, clearErrors } = useForm<FormLoginSchema>({
		resolver: zodResolver(formLoginSchema),
		mode: "onBlur",
        defaultValues: {
            usuario: getUsername(state.email, state.usuario),
            senha: state.senha,
            confirmPassword: state.senha
        }
	});
    const [showPwd, setShowPwd] = useState(false);
    useEffect(()=>{
        setFocus('usuario')
    }, [setFocus])

    const submit = (data:FormLoginSchema) => {
        const newState = {...state, ...data}
        setState(newState)
        nextSetp()
    }

    const validatorDadosUsuarioMutation = useMutation(
		({ usuario	}: { usuario: string }) => validarDadosUsuario({ apiUrl: dominioSFE, usuario }),
		{
			onError: ({ response }) => response,
		}
	);

    const validatorUsuario = (usuario:string) => {
        validatorDadosUsuarioMutation.mutate({usuario}, {
            onError: ({response}) => {
                if(response.status === 409){
                    setError('usuario', {message:'Esse usuário já está vinculado a uma conta'})
                }
                if(response.status === 404){
                    clearErrors('usuario')
                }
            }

        })
    }

    return (
        <Form onSubmit={handleSubmit(submit)}>
            <Input
                label="Usuário"
                variant={errors.usuario ? "error" : "standard"}
                helperText={errors.usuario?.message}
                required
                {...register("usuario")}
                onBlur={(event)=>validatorUsuario(event.target.value)}

            />
            <Input
                label="senha"
                variant={errors.senha ? "error" : "standard"}
                helperText={errors.senha?.message}
                required
                type={showPwd ? "text" : "password"}
                InputProps={{
                    endAdornment: (
                        <InputAdornment position="end">
                            <IconButton onClick={() => setShowPwd((showPwd)=>!showPwd)}>
                                <Icon icon={showPwd ? "mdiEyeOutline" : "mdiEyeOffOutline"} />
                            </IconButton>
                        </InputAdornment>
                    ),
                }}
                {...register("senha")}
            />
            <Input
                label="Confirme sua senha"
                variant={
                    errors.confirmPassword ? "error" : "standard"
                }
                helperText={errors.confirmPassword?.message}
                required
                type={showPwd ? "text" : "password"}
                InputProps={{
                    endAdornment: (
                        <InputAdornment position="end">
                            <IconButton onClick={() => setShowPwd((showPwd)=>!showPwd)}>
                                <Icon icon={showPwd ? "mdiEyeOutline" : "mdiEyeOffOutline"} />
                            </IconButton>
                        </InputAdornment>
                    ),
                }}
                {...register("confirmPassword")}
            />
            <ContainerButton>
                {!preconta &&
                    <Button
                        onClick={() => prevSetp()}
                        fullWidth
                        variant="outlined"
                    >
                        Voltar
                    </Button>
                }
                <Button type='submit' fullWidth>
                    Proximo
                </Button>
            </ContainerButton>
        </Form >

    )
}