import * as React from 'react';
import Button from '@mui/material/Button';
import { styled } from '@mui/material/styles';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import DialogActions from '@mui/material/DialogActions';
import IconButton from '@mui/material/IconButton';
import CloseIcon from '@mui/icons-material/Close';
import Typography from '@mui/material/Typography';
import CheckIcon from '@mui/icons-material/Check';
import Box from '@mui/material/Box';
import Paper from '@mui/material/Paper';
import Grid from '@mui/material/Grid';
import AlertasGenericos from '../Components/Alertas'
import { router } from '@inertiajs/react';
import CarrinhoController from '@/Tools/Carrinho';
import LoginIcon from '@mui/icons-material/Login';

const BootstrapDialog = styled(Dialog)(({ theme }) => ({
    '& .MuiDialogContent-root': {
        padding: theme.spacing(2),
    },
    '& .MuiDialogActions-root': {
        padding: theme.spacing(1),
    },
}));

export default function MostrarModalPontos({ open, onClose, prod, log_user, ponto, onresult }) {


    const [alertaAberto, setAlertaAberto] = React.useState(false);
    const [alertaTexto, setAlertaTexto] = React.useState('');
    const [tipoModal, setTipoModal] = React.useState('');
    const [tipoAlerta, setTipoAlerta] = React.useState('');


    const mostrarAlerta = (texto) => {
        setAlertaTexto(texto);
        setAlertaAberto(true);
        setTipoAlerta('warning');
    };

    const handleCloseLoader = (event, reason) => {
        if (reason === 'clickaway') {
            return;
        }
        setAbirLoader(false);
    };

    const handleClose = (event, reason) => {
        if (reason === 'clickaway') {
            return;
        }
        setAlertaAberto(false);
    };


    // Lida com o gerenciamento de pontos;

    React.useEffect(() => {

        async function gerenciarPontos() {
            let total_pontos_user = ponto
            let total_pontos_user_localsotage = await localStorage.getItem("user_pt");

            if (total_pontos_user_localsotage == null && log_user) {

                await localStorage.setItem("user_pt", total_pontos_user);
                await localStorage.setItem("default_pt", total_pontos_user);
                return
            }
        }
        gerenciarPontos()
    }, [])

    async function VerificarPontos() {
        // Verifico se o cara está logado.
        if (!log_user) {
            router.get(route('get.user.pontos'));
            return;
        }

        let pontos_de_troca_do_produto = Number(prod.produto_principal.pontos_troca);
        let total_pontos_user = await Number(localStorage.getItem('user_pt'));

        if (total_pontos_user < pontos_de_troca_do_produto) {
            mostrarAlerta(`Não é possível conseguir desconto neste item. Seus pontos são insuficientes.`)
            return
        }

        if ('trocado_por_ptn' in prod) {
            mostrarAlerta(`Você já adicionou seu desconto nesse item.`)
            return
        }

        let resposta = await CarrinhoController.AddDescontoPorPontos(prod, total_pontos_user);
        if (resposta == 'sucesso') {
            setAlertaAberto(true);
            setAlertaTexto('Sucesso! seus pontos foram convertidos em descontos.');
            setTipoAlerta('success');
            onresult("sucesso");
            onClose();
        }

    }

    return (
        <>
            {/* ALERTAS*/}
            <AlertasGenericos
                aberto={alertaAberto}
                texto={alertaTexto}
                handleClose={handleClose}
                tipo={tipoAlerta}
            />

            <BootstrapDialog
                onClose={onClose}
                aria-labelledby="customized-dialog-title"
                open={open}
                PaperProps={{
                    style: {
                        width: '90%', // Ajuste a largura conforme necessário
                        maxWidth: 'none', // Remove o limite máximo de largura padrão
                    }
                }}
            >
                <DialogTitle sx={{ m: 0, p: 2 }} id="customized-dialog-title">
                    Meus pontos
                    <IconButton
                        aria-label="close"
                        onClick={onClose}
                        sx={{
                            position: 'absolute',
                            right: 8,
                            top: 8,
                            color: (theme) => theme.palette.grey[500],
                        }}
                    >
                        <CloseIcon />
                    </IconButton>
                </DialogTitle>

                {log_user ?

                    <>
                        <DialogContent dividers>
                            <Box sx={{ flexGrow: 1 }}>
                                <Grid container spacing={{ xs: 2, md: 3 }} columns={{ xs: 4, sm: 6, md: 8 }}>
                                    <Grid item xs={2} sm={4} md={4} key={1}>
                                        <Typography sx={{ textAlign: 'center' }}>Saldo atual</Typography>
                                    </Grid>
                                    <Grid item xs={2} sm={4} md={4} key={2}>
                                        <Typography sx={{ textAlign: 'center' }}>Custo para troca</Typography>
                                    </Grid>
                                    <Grid item xs={2} sm={4} md={4} key={4}>
                                        <Typography sx={{ textAlign: 'center' }}>{ponto}</Typography>
                                    </Grid>
                                    <Grid item xs={2} sm={4} md={4} key={6}>
                                        <Typography sx={{ textAlign: 'center' }}>
                                            {prod.produto_principal != undefined ? prod.produto_principal.pontos_troca : 'sem dados'}
                                        </Typography>
                                    </Grid>
                                </Grid>
                            </Box>
                        </DialogContent>
                        <DialogActions>
                            <Button endIcon={<CloseIcon />} color="error" variant="contained" autoFocus onClick={onClose}>
                                Fechar
                            </Button>
                            <Button endIcon={<CheckIcon />} color="success" variant="contained" autoFocus onClick={VerificarPontos}>
                                Trocar pontos
                            </Button>
                        </DialogActions>
                    </>
                    :
                    <>
                        <DialogContent dividers>
                            <Box sx={{ flexGrow: 1, display:'flex', flexDirection:'column', alignItems:'center'}}>
                                <Typography sx={{ textAlign: 'center' }}>Para trocar esse produto por pontos faça login.</Typography>
                                <Button sx={{ width:'100%', marginTop:5 }} endIcon={<LoginIcon />}  variant="contained" autoFocus onClick={VerificarPontos}>
                                    Fazer login 
                                </Button>
                            </Box>
                        </DialogContent>


                    </>
                }

            </BootstrapDialog>
        </>

    );
}
