import { Controller, useForm } from 'react-hook-form'
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import { validator } from '@sofaltaeu/sofaltaeu-utils'
import {
    Button,
    Input,
    Typography,
    Checkbox,
    FormControlLabel
} from '@sofaltaeu/sofaltaeu-components'
import { ContainerButton, Form } from './styled'
import { CreateAccount } from '../../../interfaces/services/ICreateUser'
import { useState } from 'react';
import { useMutation } from 'react-query';
import { validarDadosUsuario } from '../../../services';

const cpfValidator = z.string().refine((cpf) => validator.isCpf(cpf), 'CPF inválido');
const formDadosPessoaisSchema = z.object({
    nome: z.string().min(3, 'Deve conter pelo menos 3 caracteres').max(100, 'Deve conter no máximo 100 caracteres'),
    sobrenome: z.string().min(3, 'Deve conter pelo menos 3 caracteres').max(100, 'Deve conter no máximo 100 caracteres'),
    email: z.string().email('Formato de e-mail inválido'),
})

const cpfSchema = formDadosPessoaisSchema.merge(z.object({
    cpf: cpfValidator
}))

type FormCpfSchema = z.infer<typeof cpfSchema>


const identificacaoSchema = formDadosPessoaisSchema.merge(z.object({
    identificacao: z.string()
}))
type FormIdentificacaoSchema = z.infer<typeof identificacaoSchema>

interface FormDadosPessoaisProps {
    nextSetp: ()=>void
    prevSetp: ()=>void
    state: CreateAccount
    setState: (payload:CreateAccount)=>void
    dominioSFE: string
}
export const FormDadosPessoais = ({state, nextSetp, prevSetp, setState, dominioSFE}:FormDadosPessoaisProps) => {
    const [isCpf, setIsCpf] = useState(!state.identificacao);

	const {
		register, handleSubmit, formState: { errors }, control, setError, clearErrors, setValue  } = useForm<FormCpfSchema & FormIdentificacaoSchema>({
		resolver: zodResolver(isCpf ? cpfSchema : identificacaoSchema),
		mode: "onBlur",
        defaultValues: {
            nome: state.nome,
            sobrenome: state.sobrenome,
            email: state.email,
            cpf: state.cpf,
            identificacao: state.identificacao
        }
	});

    const validatorDadosUsuarioMutation = useMutation(
		({
			email,
			cpf,
			identificacao,
		}: {
			email?: string;
			cpf?: string;
			identificacao?: string;
		}) => validarDadosUsuario({ apiUrl: dominioSFE, email, cpf, identificacao }),
		{
			onError: ({ response }) => response,
		}
	);

    const submit = (data:FormCpfSchema | FormIdentificacaoSchema) => {
        const newState = {...state, ...data}

        if(isCpf){
            newState.identificacao = undefined
            newState.isEstrangeiro = true
        }else{
            newState.isEstrangeiro = false
            newState.cpf = undefined
        }

        setState(newState)
        nextSetp()
    }

    const handleChangeCheckbox = () =>{
        setIsCpf((isCpf)=>!isCpf);

        if(errors.identificacao && !isCpf){
            clearErrors('identificacao')
            setValue('identificacao', '')
        }else{
            clearErrors('cpf')
            setValue('cpf', '')
        }
    }

    const validatorEmail = (email:string) => {
        validatorDadosUsuarioMutation.mutate({email}, {
            onError: ({response}) => {
                if(response.status === 409){
                    setError('email', {message:'Esse E-mail já está vinculado a uma conta'})
                }
                if(response.status === 404){
                    clearErrors('email')
                }
            }

        })
    }

    const validatorCpf = (cpf:string) => {
        const stringWithoutDotsAndDashes = cpf.replace(/[.-]/g, '');

        validatorDadosUsuarioMutation.mutate({cpf:stringWithoutDotsAndDashes}, {
            onError: ({response}) => {
                if(response.status === 409){
                    setError('cpf', {message:'CPF vinculado a uma conta'})
                }
                if(response.status === 404){
                    clearErrors('cpf')
                }
            }

        })
    }

    const validatorIdentificacao = (identificacao:string) => {
        validatorDadosUsuarioMutation.mutate({identificacao}, {
            onError: ({response}) => {
                if(response.status === 409){
                    setError('identificacao', {message:'identificacao vinculado a uma conta'})
                }
                if(response.status === 404){
                    clearErrors('identificacao')
                }
            }

        })
    }

    const isError = Object.keys(errors).length > 0
    return (
        <Form onSubmit={handleSubmit(submit)}>
            <Input
                label="Nome"
                variant={errors.nome ? "error" : "standard"}
                helperText={errors.nome?.message}
                required
                {...register("nome")}
                placeholder='João'
                InputProps={{
                    autoComplete:"nofill"
                }}
            />
            <Input
                label="Sobrenome"
                variant={errors.sobrenome ? "error" : "standard"}
                helperText={errors.sobrenome?.message}
                required
                {...register("sobrenome")}
                placeholder='Silva'
                InputProps={{
                    autoComplete:"nofill"
                }}
            />
            <Input
                label="E-mail"
                variant={errors.email ? "error" : "standard"}
                helperText={errors.email?.message}
                required
                type="email"
                {...register("email")}
                onBlur={(event)=>validatorEmail(event.target.value)}
                placeholder='mail@mail.com'
                InputProps={{
                    autoComplete:"nofill"
                }}
            />
             <FormControlLabel
                control={
                    <Checkbox
                        checked={!isCpf}
                    />
                }
                label={
                    <Typography variant='body2'>Não possui CPF?</Typography>
                }
                onChange={handleChangeCheckbox}
            />

            {isCpf ? (
                <Controller
                    name="cpf"
                    control={control}
                    render={({ field: { onChange, value } }) => {
                        const stringWithoutDotsAndDashes = value.replace(/[.-]/g, '');
                        const valor = stringWithoutDotsAndDashes.length >= 11 ? validator.cpfMask(value) : value
                        return(<Input
                            label="CPF"
                            variant={errors.cpf ? "error" : "standard"}
                            helperText={errors.cpf?.message}
                            required
                            onChange={(event)=>onChange(event)}
                            value={valor}
                            placeholder='0000.000.000-00'
                            onBlur={(event)=>validatorCpf(event.target.value)}
                        />)

                    }}
                />

            ) : (
                <Input
                    label="Rg, CNPJ, Passaporte ou identificação"
                    variant={errors.identificacao ? "error" : "standard"}
                    helperText={errors.identificacao?.message}
                    required
                    {...register("identificacao")}
                    onBlur={(event)=>validatorIdentificacao(event.target.value)}
                />
            )
            }
            <ContainerButton>
                <Button
                    onClick={() => prevSetp()}
                    fullWidth
                    variant="outlined"
                >
                    Voltar
                </Button>
                <Button type='submit' fullWidth disabled={isError}>
                    Proximo
                </Button>
            </ContainerButton>
        </Form >

    )
}