import * as React from 'react';
import PropTypes from 'prop-types';
import Tabs from '@mui/material/Tabs';
import Tab from '@mui/material/Tab';
import Box from '@mui/material/Box';
import PerfilController from '../Tools/Perfil';
import { DataGrid } from '@mui/x-data-grid';
import Grid from '@mui/material/Grid';
import Card from '@mui/material/Card';
import CardHeader from '@mui/material/CardHeader';
import ListItemButton from '@mui/material/ListItemButton';
import ListItemIcon from '@mui/material/ListItemIcon';
import Checkbox from '@mui/material/Checkbox';
import Button from '@mui/material/Button';
import Divider from '@mui/material/Divider';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import PromocoesController from '@/Tools/Promocoes';
import AlertasGenericos from '../Components/Alertas';
import Paper from '@mui/material/Paper';
import CriaNovaPromocao from '../Components/CriarPromocao'
import DeleteIcon from '@mui/icons-material/Delete'; // Importa o ícone de lixeira
import { useState } from 'react';
import LoaderGenerico from '../Components/LoaderGenerico';

// Função para identificar os dias com promoção ativa
function diasDePromocao(dados) {
    const dias = {
        segunda: 'Segunda',
        terca: 'Terça',
        quarta: 'Quarta',
        quinta: 'Quinta',
        sexta: 'Sexta',
        sabado: 'Sábado',
        domingo: 'Domingo',
    };

    // Filtra os dias em que a promoção está ativa ('S') e junta-os em uma string separada por vírgula
    return Object.keys(dias)
        .filter(dia => dados[dia] === 'S')
        .map(dia => dias[dia])
        .join(', ');
}

// Componentes de troca de abas
function CustomTabPanel(props) {
    const { children, value, index, ...other } = props;

    return (
        <div
            role="tabpanel"
            hidden={value !== index}
            id={`simple-tabpanel-${index}`}
            aria-labelledby={`simple-tab-${index}`}
            {...other}
        >
            {value === index && <Box sx={{ p: 3 }}>{children}</Box>}
        </div>
    );
}

CustomTabPanel.propTypes = {
    children: PropTypes.node,
    index: PropTypes.number.isRequired,
    value: PropTypes.number.isRequired,
};

function a11yProps(index) {
    return {
        id: `simple-tab-${index}`,
        'aria-controls': `simple-tabpanel-${index}`,
    };
}

// Função para buscar os dados de promoção
async function getDadoPromocoes() {
    let resposta = await PerfilController.GetItensEmPromocao();
    if (resposta.status === 'erro') {
        console.log("Erro ao buscar dados");
        return [];
    }
    return resposta.data.dados;
}

// Pega todos os grupos e subgrupos e produtos.
async function getDados() {

    let resposta = await PerfilController.GetProdutosGuposSubgrupos();
    return resposta;
}




export default function Descontos() {


    const columns = [
        {
            field: 'id',
            headerName: 'ID',
            width: 100,
            headerAlign: 'center',
        },
        {
            field: 'cd_produto',
            headerName: 'Código produto',
            width: 150,
            editable: true,
            headerAlign: 'center',
        },
        {
            field: 'nome',
            headerName: 'Nome Produto',
            width: 150,
            editable: true,
            headerAlign: 'center',
        },
        {
            field: 'valor',
            headerName: 'Preço original',
            headerAlign: 'center',
            type: 'number',
            width: 150,
            editable: true,
            renderCell: (params) => {
                return (
                    <div style={{
                        color: 'green',
                        textAlign: 'center',
                        display: 'flex',
                        justifyContent: 'center',
                        width: '100%'
                    }}>
                        {params.value.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })}
                    </div>
                );
            }
        },
        {
            field: 'vr_promo',
            headerName: 'Preço promocional',
            type: 'number',
            width: 150,
            editable: true,
            headerAlign: 'center',
            renderCell: (params) => {
                return (
                    <div style={{
                        color: 'blue',
                        textAlign: 'center',
                        fontWeight: 'bold',
                        display: 'flex',
                        justifyContent: 'center',
                        width: '100%'
                    }}>
                        {params.value.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })}
                    </div>
                );
            }
        },
        {
            headerAlign: 'center',
            field: 'dias_promocao',
            headerName: 'Dias de promoção',
            width: 150,
            editable: false,
            renderCell: (params) => {
                return (
                    <div style={{
                        color: 'red',
                        textAlign: 'center',
                        display: 'flex',
                        justifyContent: 'center',
                        width: '100%'
                    }}>
                        {params.value}
                    </div>
                );
            }
        },
        {
            headerAlign: 'center',
            field: 'dt_fim_promo',
            headerName: 'Validade',
            type: 'number',
            width: 100,
            editable: true,
        },
        {
            field: 'excluir',
            headerName: 'Excluir', // Nova coluna para a lixeira
            width: 100,
            headerAlign: 'center',
            renderCell: (params) => {
                return (
                    <DeleteIcon
                        style={{ cursor: 'pointer', color: 'red' }}
                        onClick={() => handleExcluir(params.row)} // Chama a função ao clicar
                    />
                );
            }
        },
    ];

    const [value, setValue] = React.useState(0);
    const [dadosDaTabela, setDadosDaTabela] = React.useState([]);
    const [grupos, setGrupos] = React.useState([]);
    const [subGrupos, setSubGrupos] = React.useState([]);
    const [produtos, setProdutos] = React.useState([]);

    // MODAL
    const [alertaAberto, setAlertaAberto] = React.useState(false);
    const [alertaTexto, setAlertaTexto] = React.useState('');
    const [tipoAlerta, setTipoAlerta] = React.useState('');


    // Loading
    const [abirLoader, setAbirLoader] = React.useState(false);

    const handleChange = (event, newValue) => {
        setValue(newValue);
    };

    // Função para lidar com exclusão de um item
    async function handleExcluir(linha) {

        mostrarloaders();
        let resposta = await axios.post(route('excluir.produto.da.promocao'), { id: linha.id });
        if (resposta.data.original.status == 'erro') {
            setTipoAlerta('warning');
            mostrarAlerta(resposta.data.original.msg);
            handleCloseLoader()
            return
        }


        // Coloco os dados na tabela sem o excluido.
        let novos_dados = dadosDaTabela.filter(prods => prods.id != linha.id);
        setDadosDaTabela(novos_dados);
        setTipoAlerta('success');
        mostrarAlerta("Item deletado com sucesso");
        handleCloseLoader()

    };

    //Função para excluir todas as promoções 
    async function ExcluirTodasAsPromocoes() {
        mostrarloaders();
        let resposta = await axios.post(route('excluir.todas.as.promocoes'));

        if (resposta.data.original.status == 'erro') {
            setTipoAlerta('warning');
            mostrarAlerta(resposta.data.original.msg);
            handleCloseLoader()
            return
        }

        setDadosDaTabela([]);
        setTipoAlerta('success');
        mostrarAlerta(resposta.data.original.msg);
        handleCloseLoader()


    }

    React.useEffect(() => {
        const fetchDados = async () => {
            mostrarloaders();

            const dados = await getDadoPromocoes();
            const dadosComDias = dados.map(item => ({
                ...item,
                dias_promocao: diasDePromocao(item), // Adiciona os dias da promoção ativos
            }));
            setDadosDaTabela(dadosComDias);
            handleCloseLoader();

        };
        fetchDados();
    }, []);

    React.useEffect(() => {
        if (value === 1) {
            const fetchProdutosGuposSubgrupos = async () => {
                let dados = await getDados();
                setGrupos(dados.grupos);
                setSubGrupos(dados.sub_grupos);
                setProdutos(dados.produtos);
            };
            fetchProdutosGuposSubgrupos();
        }
    }, [value]);

    //ALERTAS
    const handleCloseAlerta = (event, reason) => {
        if (reason === 'clickaway') {
            return;
        }
        setAlertaAberto(false);
    };

    const mostrarAlerta = (texto) => {
        setAlertaTexto(texto);
        setAlertaAberto(true);
    };
    const mostrarloaders = () => {
        setAbirLoader(true);
    };

    const handleCloseLoader = (event, reason) => {
        if (reason === 'clickaway') {
            return;
        }
        setAbirLoader(false);
    };

    return (
        <>

            <LoaderGenerico
                aberto={abirLoader}
                handleClose={handleCloseLoader}
            />

            <AlertasGenericos
                aberto={alertaAberto}
                texto={alertaTexto}
                handleClose={handleCloseAlerta}
                tipo={tipoAlerta}
            />

            <Box sx={{ width: '100%', marginBottom: 2 }}>
                <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
                    <Tabs value={value} onChange={handleChange} aria-label="basic tabs example">
                        <Tab label="Ver promoções" {...a11yProps(0)} />
                        <Tab label="Adicionar promoções" {...a11yProps(1)} />
                    </Tabs>
                </Box>

                <CustomTabPanel value={value} index={0}>

                    <Box
                        sx={{
                            height: 590,
                            width: '90%',
                            margin: 'auto',
                        }}
                    >

                        <Button
                            sx={{ marginBottom: 2 }}
                            variant='contained'
                            color='error'
                            endIcon={<DeleteIcon></DeleteIcon>}
                            onClick={ExcluirTodasAsPromocoes}
                        >
                            Excluir tudo
                        </Button>

                        <DataGrid
                            rows={dadosDaTabela}
                            columns={columns}
                            initialState={{
                                pagination: {
                                    paginationModel: {
                                        pageSize: 15,
                                    },
                                },
                            }}
                            pageSizeOptions={[15]}
                            // checkboxSelection
                            disableRowSelectionOnClick
                        />
                    </Box>
                </CustomTabPanel>

                <CustomTabPanel value={value} index={1}>
                    <CriaNovaPromocao />
                </CustomTabPanel>
            </Box>
        </>
    );
}

