import { useEffect } from 'react';
import * as React from 'react';
import InputError from '@/Components/InputError';
import InputLabel from '@/Components/InputLabel';
import PrimaryButton from '@/Components/PrimaryButton';
import TextInput from '@/Components/TextInput';
import { Head, Link, useForm } from '@inertiajs/react';
import Grid from '@mui/material/Grid';
import Box from '@mui/material/Box';
import { router } from '@inertiajs/react'
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
import CardMedia from '@mui/material/CardMedia';
import Typography from '@mui/material/Typography';
import Button from '@mui/material/Button';
import PerfilController from '../../Tools/Perfil';
import LoaderGenerico from '../../Components/LoaderGenerico'
import AlertasGenericos from '../../Components/Alertas'

// EVITAR DOIS CLIQUE NOS BTN DE ADCINAR NO CARRINHO 
// endereço colocar 60
// numero 5
// quando aperta no lápis a observação não fica no campo de edição

export default function Register({bairros}) {
    const [abirLoader, setAbirLoader] = React.useState(false);
    const [alertaAberto, setAlertaAberto] = React.useState(false);
    const [quantidadeDeItensNoCarrinho, setQuantidadeDeItensNoCarrinho] = React.useState(0)
    const [alertaTexto, setAlertaTexto] = React.useState('');
    const [tipoAlerta, setTipoAlerta] = React.useState('');
  
    const { data, setData, post, processing, errors, reset } = useForm({
        name: '',
        email: '',
        password: '',
        password_confirmation: '',
        telefone: '',
        logradouro: '',
        endereco: '',
        numero: '',
        complemento: '',
        bairro: '',
        cidade: 'Uberlândia',
        uf: 'MG',
        referencia: '',
        CEP :''
    });


    useEffect(() => {
        return () => {
            reset('password', 'password_confirmation');
        };
    }, []);

    const submit = (e) => {

        e.preventDefault();

        // verifica se está faltando dados 
        if(data.endereco == "" ){
            setTipoAlerta('warning');
            mostrarAlerta("Escreva o cep e verifique se os campos de Endereço e Bairro estão preenchidos.")
            return
        }

        if(data.bairro == ""){
            setTipoAlerta('warning');
            mostrarAlerta("Escreva o cep e verifique se os campos de Endereço e Bairro estão preenchidos.")
            return
        }

        post(route('register'));
    };


    function mascaraTelefones(inputValue) {
        // Remova caracteres não numéricos
        const numericValue = inputValue.replace(/\D/g, '');
        const limitedValue = numericValue.slice(0, 11);
        let formattedValue = limitedValue;

        if (limitedValue.length == 10) {
            formattedValue = '(' + limitedValue.slice(0, 2) + ') ' + limitedValue.slice(2, 6) + '-' + limitedValue.slice(6, 10);
        }

        if (limitedValue.length == 11) {
            formattedValue = '(' + limitedValue.slice(0, 2) + ') ' + limitedValue.slice(2, 7) + '-' + limitedValue.slice(7, 11);
        }

        return formattedValue;
    }

    function mascaraCep(dado) {
        let valor_sem_espacos = dado.trim().replace(/\D/g, ''); // Remove caracteres não numéricos
        let primeiros_numeros = valor_sem_espacos.slice(0, 5);
        let numero_finais = valor_sem_espacos.slice(5, 8);
        let quantidade_de_itens = valor_sem_espacos.length;

        if (quantidade_de_itens === 8) {
            getCepUsuario(valor_sem_espacos)
            let valor_formatado = `${primeiros_numeros}-${numero_finais}`;
            return valor_formatado;
        }
        return valor_sem_espacos; // Retorna o valor sem máscara quando incompleto
    }

    // Volta para home 
    function VoltarParaHome() {
        router.get(route('Pagina.de.inicio'));
    }


    // FUNÇÃO QUE PEGA OS DADOS NO VIA CEP;
    // QUANDO TIVER 8 DÍGITOS VAI PESQUISAR O CEP.
    async function getCepUsuario(cep){

        mostrarloaders();
        try {
        
            let resposta = await PerfilController.GetCep(cep);
            if('erro' in resposta){
                setTipoAlerta('warning');
                mostrarAlerta("O CEP digitado não foi encontrado.")
            
                // lIMPA OS ESTADOS 
                await setData(prevData =>({
                    ...prevData,
                    endereco: "",
                    bairro: "",
                }))
                
                return
            }
            
            // Verifica se o nome do bairro retornado existe na minha tabela
            let RespostabairroCadastrado = await PerfilController.VerificarBairro(resposta.bairro, resposta.localidade);
            if(RespostabairroCadastrado.status == 'erro'){
                setTipoAlerta('warning');
                mostrarAlerta(RespostabairroCadastrado.msg)  
                handleCloseLoader()

                // lIMPA OS ESTADOS 
                await setData(prevData =>({
                    ...prevData,
                    endereco: '',
                    bairro: '',
                }))
                return
            }

            setarDadosCep(resposta, RespostabairroCadastrado);
            handleCloseLoader()
        } catch (error) {
            handleCloseLoader()
            setTipoAlerta('warning');
            mostrarAlerta("Ocorreu um erro tente maist tarde.")  
        }finally{
            handleCloseLoader()
        }
    }
    

    async function setarDadosCep(dados_via_cep, dados_banco){
    
        await setData(prevData => ({
            ...prevData, // mantém todos os outros estados intactos
            endereco: dados_via_cep.logradouro,
            bairro: dados_banco.dados.cod_bairro
        }));

    }


    const handleCloseLoader = (event, reason) => {
        if (reason === 'clickaway') {
            return;
        }
        setAbirLoader(false);
    };

    const mostrarloaders = () => {
        setAbirLoader(true);
    };

    const handleClose = (event, reason) => {
        if (reason === 'clickaway') {
          return;
        }
        setAlertaAberto(false);
    };
    const mostrarAlerta = (texto) => {
        setAlertaTexto(texto);
        setAlertaAberto(true);
    };

    return (
        <>
            <div style={{ margin:'auto', width:'90%', marginTop:5, cursor:'pointer' }} onClick={VoltarParaHome}>
                <ArrowBackIcon sx={{ color: 'red', fontSize: 30 }}></ArrowBackIcon>
            </div>

            <LoaderGenerico
                aberto={abirLoader}
                handleClose={handleCloseLoader}
            />

           

         <Box
        sx={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            marginBottom:25,
            marginTop:3,
        }}
    >

         
        <Card elevation={7} sx={{ width: '90%', minHeight:500,maxHeight:1200}}>
            {/* ALERTAS*/}
            <AlertasGenericos
                aberto={alertaAberto}
                texto={alertaTexto}
                handleClose={handleClose}
                tipo={tipoAlerta}
            />
            <form onSubmit={submit}>
                <CardContent>
                    <Typography gutterBottom variant="h5" component="div">
                        Cadastro
                    </Typography>
                    <Grid sx={{marginTop:3 , margin:'auto'}} container  xs={12} md={12} spacing={2}>          
                        <Grid item xs={12} md={6}>
                            <Head title="Register" />
                                <div style={{ width:'95%' }}>
                                    <InputLabel htmlFor="Nome completo" value="* Nome completo" />

                                    <TextInput
                                        id="name"
                                        type="Text"
                                        name="name"
                                        value={data.name}
                                        className="mt-1 block w-full"
                                        isFocused={true}
                                        onChange={(e) => setData('name', e.target.value.slice(0, 50))}
                                        required
                                    />

                                <InputError message={errors.name} className="mt-2" />
                            </div>
                        </Grid>

                        <Grid  item xs={12} md={6}>
                            <div  style={{ width:'95%' }}>
                                <InputLabel htmlFor="email" value="* Email" />
                                <TextInput
                                    id="email"
                                    type="email"
                                    name="email"
                                    value={data.email}
                                    className="mt-1 block w-full"
                                    onChange={(e) => setData('email', e.target.value.slice(0, 50))}
                                    required
                                />

                                <InputError message={errors.email} className="mt-2" />
                            </div>
                            
                        </Grid>
                        <Grid  item xs={12} md={6}>
                            <div style={{ width:'95%' }}>
                            <InputLabel htmlFor="telefone" value="* Telefone (com DDD)" />
                            <TextInput
                                id="telefone"
                                type="tel"
                                name="telefone"
                                value={data.telefone}
                                className="mt-1 block w-full"
                                onChange={(e) => setData('telefone', mascaraTelefones( e.target.value))}
                                required
                            />

                            <InputError message={errors.telefone} className="mt-2" />
                            </div>  
                        </Grid>


                        <Grid  item xs={12} md={6}>
                            <div style={{ width:'95%' }}>
                                <InputLabel htmlFor="Senha" value="* Senha (mínimo 5 dígitos)" />
                                <TextInput
                                    id="password"
                                    type="password"
                                    name="password"
                                    value={data.senha}
                                    className="mt-1 block w-full"
                                    onChange={(e) => setData('password', e.target.value)}
                                    required
                                />

                                <InputError message={errors.password} className="mt-2" />
                            </div>
                        </Grid>

                        <Grid  item xs={12} md={6}>
                            <div style={{ width:'95%' }}>
                                <InputLabel htmlFor="Confirmar senha" value="* Confirme sua senha" />
                                <TextInput
                                    id="password_confirmation"
                                    type="password"
                                    name="password_confirmation"
                                    value={data.password_confirmation}
                                    className="mt-1 block w-full"
                                    onChange={(e) => setData('password_confirmation', e.target.value)}
                                    required
                                />
                                <InputError message={errors.password_confirmation} className="mt-2" />
                            </div>
                        </Grid>

                        <Grid item xs={12} md={6}>
                            <div style={{ width:'95%' }}>
                                <InputLabel htmlFor="CEP" value="* CEP" />

                                <TextInput
                                    id="CEP"
                                    type={'Text'}
                                    name="CEP"
                                    value={data.CEP}
                                    required
                                    // inputProps={{ maxLength: 7 }}
                                    className="mt-1 block w-full"
                                    onChange={(e) => setData('CEP', mascaraCep(e.target.value.slice(0, 9)))}
                                
                                />
                            </div>
                        </Grid>
                        <Grid  item xs={12} md={12}>
                            <div style={{ width:'98%' }}>
                            <InputLabel htmlFor="Endereço" value="* Endereço" />


                            <TextInput
                                style={{backgroundColor:'#e1e1e1'}}
                                id="endereco"
                                type="text"
                                name="endereco"
                                value={data.endereco}
                                className="mt-1 block w-full"
                                // onChange={(e) => setData('endereco', e.target.value.slice(0, 60))}
                                required
                                disabled
                            />

                            <InputError message={errors.endereco} className="mt-2" />
                            </div>
                        </Grid>

                    
                        <Grid  item xs={12} md={12}>
                            <div style={{ width:'98%' }}>
                                <InputLabel htmlFor="Número" value="* Número" />

                                <TextInput
                                    id="numero"
                                    type="number"
                                    name="numero"
                                    value={data.numero}
                                    className="mt-1 block w-full"
                                    onChange={(e) => setData('numero', e.target.value.slice(0, 5))}
                                    required
                                />

                                <InputError message={errors.numero} className="mt-2" />
                            </div>
                        </Grid>

                        
                        <Grid  item xs={12} md={12}>
                            <div style={{ width:'98%' }}>
                                <InputLabel htmlFor="Complemento" value="Complemento" />

                                <TextInput
                                    id="complemento"
                                    type="Text"
                                    name="complemento"
                                    value={data.complemento}
                                    className="mt-1 block w-full"
                                    onChange={(e) => setData('complemento', e.target.value.slice(0, 30))}
                                    />

                                <InputError message={errors.complemento} className="mt-2" />
                            </div>     
                        </Grid>
                        <Grid  item xs={12} md={6}>
                            <div style={{ width:'95%' }}>
                                <InputLabel htmlFor="Bairro" value="* Bairro" />

                                <select
                                    id="bairro"
                                    name="bairro"
                                    value={data.bairro}
                                    className="mt-1 block w-full"
                                    style={{ borderRadius: '0.375rem', backgroundColor:'#e1e1e1' }}
                                    // onChange={(e) => setData('bairro', e.target.value)}
                                    required
                                    disabled
                                >
                                    {bairros.map((item,index)=>{
                                        return(
                                            <option value={item.cod_bairro}>
                                                {item.cod_bairro == data.bairro ? item.nome : ''}
                                            </option>
                                        )
                                    })}
                                </select>

                                <InputError message={errors.bairro} className="mt-2" />
                            </div>
                        </Grid>
                        <Grid item xs={12} md={6}>
                            <div style={{ width:'95%' }}>
                                <InputLabel htmlFor="Referencia" value="* Ponto de referência" />

                                <TextInput
                                    id="referencia"
                                    type="Text"
                                    name="referencia"
                                    value={data.referencia}
                                    className="mt-1 block w-full"
                                    onChange={(e) => setData('referencia', e.target.value.slice(0, 40))}
                                    
                                />

                                <InputError message={errors.referencia} className="mt-2" />
                            </div>
                        </Grid>

                        {/* <Grid item xs={12} md={6}>
                            
                            <div style={{ width:'95%' }}>
                                <InputLabel htmlFor="logradouro" value="* Logradouro" />

                                    <select
                                    id="logradouro"
                                    name="logradouro"
                                    value={data.logradouro}
                                    className="mt-1 block w-full"
                                    style={{ borderRadius: '0.375rem', borderColor: 'rgb(209 213 219)' }}
                                    onChange={(e) => setData('logradouro', e.target.value)}
                                    required
                                >
                                    <option value="" disabled>Selecione uma opção</option>
                                        <option value="ALA">ALA</option>
                                        <option value="AV.">AV.</option>
                                        <option value="PRC">PRC</option>
                                        <option value="RUA">RUA</option>
                                        <option value="ROD">ROD</option>
                                        <option value="TRV">TRV</option> 
                                        <option value="EST">EST</option>
                                        <option value="LGO">LGO</option>                      
                                </select>
                                <InputError message={errors.logradouro} className="mt-2" />
                            </div>
                        </Grid> */}

                        <Grid item xs={6} md={6}>
                            <div style={{ width:'95%' }}>
                                <InputLabel htmlFor="cidade" value="* Cidade" />
                                <TextInput
                                    style={{backgroundColor:'#e1e1e1'}}
                                    disabled={true}
                                    id="cidade"
                                    type="Text"
                                    name="cidade"
                                    value={"Uberlândia"}
                                    className="mt-1 block w-full"
                                    required
                                />
                            </div>
                        </Grid>

                        <Grid item xs={6} md={6}>

                            <div style={{ width:'95%' }}>
                                <InputLabel htmlFor="UF" value="* UF" />
                                <TextInput
                                     style={{backgroundColor:'#e1e1e1'}}
                                    disabled={true}
                                    id="uf"
                                    type="Text"
                                    name="uf"
                                    value={"MG"}
                                    className="mt-1 block w-full"
                                    required
                                />
                            </div>
                        </Grid>

                       

                        <Grid sx={{ display: 'flex', justifyContent: 'flex-end' }} item xs={12} md={12}>
                            <PrimaryButton className="ms-4 bg-danger" disabled={processing}>
                                Registrar
                            </PrimaryButton>
                        </Grid>

                    </Grid>
                </CardContent>
            </form>
        </Card>
     </Box>
       
                
     </>
    );
}



// import { useEffect } from 'react';
// import GuestLayout from '@/Layouts/GuestLayout';
// import InputError from '@/Components/InputError';
// import InputLabel from '@/Components/InputLabel';
// import PrimaryButton from '@/Components/PrimaryButton';
// import TextInput from '@/Components/TextInput';
// import { Head, Link, useForm } from '@inertiajs/react';

// export default function Register() {
//     const { data, setData, post, processing, errors, reset } = useForm({
//         name: '',
//         email: '',
//         password: '',
//         password_confirmation: '',
//     });

//     useEffect(() => {
//         return () => {
//             reset('password', 'password_confirmation');
//         };
//     }, []);

//     const submit = (e) => {
//         e.preventDefault();

//         post(route('register'));
//     };

//     return (
//         <GuestLayout>
//             <Head title="Register" />

//             <form onSubmit={submit}>
//                 <div>
//                     <InputLabel htmlFor="name" value="Nome completo" />

//                     <TextInput
//                         id="name"
//                         name="name"
//                         value={data.name}
//                         className="mt-1 block w-full"
//                         autoComplete="name"
//                         isFocused={true}
//                         onChange={(e) => setData('name', e.target.value)}
//                         required
//                     />

//                     <InputError message={errors.name} className="mt-2" />
//                 </div>

//                 <div className="mt-4">
//                     <InputLabel htmlFor="email" value="Email" />

//                     <TextInput
//                         id="email"
//                         type="email"
//                         name="email"
//                         value={data.email}
//                         className="mt-1 block w-full"
//                         autoComplete="username"
//                         onChange={(e) => setData('email', e.target.value)}
//                         required
//                     />

//                     <InputError message={errors.email} className="mt-2" />
//                 </div>

//                 <div className="mt-4">
//                     <InputLabel htmlFor="password" value="telefone" />

//                     <TextInput
//                         id="password"
//                         type="password"
//                         name="password"
//                         value={data.password}
//                         className="mt-1 block w-full"
//                         autoComplete="new-password"
//                         onChange={(e) => setData('password', e.target.value)}
//                         required
//                     />

//                     <InputError message={errors.password} className="mt-2" />
//                 </div>
                
//                 <div className="mt-4">
//                     <InputLabel htmlFor="s" value="Senha" />

//                     <TextInput
//                         id="password"
//                         type="password"
//                         name="password"
//                         value={data.password}
//                         className="mt-1 block w-full"
//                         autoComplete="new-password"
//                         onChange={(e) => setData('password', e.target.value)}
//                         required
//                     />

//                     <InputError message={errors.password} className="mt-2" />
//                 </div>

//                 <div className="mt-4">
//                     <InputLabel htmlFor="password_confirmation" value="Confirm Password" />

//                     <TextInput
//                         id="password_confirmation"
//                         type="password"
//                         name="password_confirmation"
//                         value={data.password_confirmation}
//                         className="mt-1 block w-full"
//                         autoComplete="new-password"
//                         onChange={(e) => setData('password_confirmation', e.target.value)}
//                         required
//                     />

//                     <InputError message={errors.password_confirmation} className="mt-2" />
//                 </div>

//                 <div className="flex items-center justify-end mt-4">
//                     <Link
//                         href={route('login')}
//                         className="underline text-sm text-gray-600 hover:text-gray-900 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
//                     >
//                         Already registered?
//                     </Link>

//                     <PrimaryButton className="ms-4" disabled={processing}>
//                         Register
//                     </PrimaryButton>
//                 </div>
//             </form>
//         </GuestLayout>
//     );
// }
