import * as React from "react";
import { Box } from "@mui/material";
import DataGridElement from "./DataGridElement";
import ModalMini from "./ModalMini";
import ModalPackage from "./ModalPackage";
import { ReactNode } from "react";
import CustomButton from "./CustomButton";
import CustomHeader from "./CustomHeader";
import { ArrayProps, Tariff } from "../../../../model/tariff";
import { useTariffStore } from "../../../../stores/tariffs";


const ButtonContainer: React.FC<{ children: ReactNode; }> = ({ children }) => {
    return <Box sx={{
        marginTop: "35px",
        display: "grid",
        gridTemplateColumns: "repeat(2, 1fr)",
        gridGap: "20px",
        marginBottom: "120px",
    }}>
        {children}
    </Box>;
};

const Tariffs: React.FC = () => {
    const [openModalMini, setOpenModalMini] = React.useState(false);

    const handleOpenModalMini = () => { setOpenModalMini(true); };
    const handleCloseModalMini = () => { setOpenModalMini(false); };

    const [type, setType] = React.useState(100);
    const [variant, setVariant] = React.useState(100);
    const setUpModalMini = (type: number, num: number) => {
        setType(type);
        setVariant(num);
        handleOpenModalMini();
    };

    const getData = localStorage.getItem("tariffs");
    const tariffsArray = useTariffStore(state => state.tariffs);
    const tariffsArraySet = useTariffStore(state => state.setTariffs);
    const tariffsSelectedRowsData = useTariffStore(state => state.tariffsSelectedRowsData);

    if (getData && !tariffsArray.length) {
        const rows: Array<ArrayProps> = JSON.parse(getData);
        if (rows.length) { tariffsArraySet(rows); };
    }

    const [openModalPackage, setOpenModalPackage] = React.useState(false);

    const handleOpenModalPackage = () => { setOpenModalPackage(true); };
    const handleCloseModalPackage = () => { setOpenModalPackage(false); };

    const newPackage = (name: string) => {
        const tariffs: Array<Tariff> = [];

        tariffsSelectedRowsData.forEach((item) => {
            if (item.type === "package" && item.tariffs) {
                tariffs.push(...item.tariffs);
            } else {
                tariffs.push(item);
            }
        });

        const uniqueArray: Array<Tariff> = [];
        tariffs.forEach((tariff) => {
            if (uniqueArray.findIndex((a) => a.id === tariff.id) < 0) {
                uniqueArray.push(tariff);
            }
        });

        const packageCreated: ArrayProps = {
            name,
            id: new Date().getTime(),
            type: "package",
            tariffs: uniqueArray,
            service: "",
            disk: 0,
            time: 0,
            points: 0,
            price: 0
        };

        tariffsArraySet([...tariffsArray, packageCreated]);
        handleCloseModalPackage();
    };

    return (
        <>
            <Box sx={{
                width: "90%",
                display: "flex",
                flexDirection: "column",
                justifyContent: "center",
                alignItems: "center"
            }}>
                <CustomHeader>Шаблонизатор документов</CustomHeader>
                <ButtonContainer>
                    <CustomButton onClick={() => setUpModalMini(1, 1)}>Создать тариф на время</CustomButton>
                    <CustomButton onClick={() => setUpModalMini(1, 0)}>Создать тариф на объем</CustomButton>
                    <CustomButton onClick={() => setUpModalMini(1, 2)}>Создать тариф на гигабайты</CustomButton>
                    <CustomButton>Изменить тариф</CustomButton>
                </ButtonContainer>
                <CustomHeader>Опросник</CustomHeader>
                <ButtonContainer>
                    <CustomButton sx={{ padding: '11px 43px' }} onClick={() => setUpModalMini(2, 1)}>Создать тариф на время</CustomButton>
                    <CustomButton sx={{ padding: '11px 43px' }} onClick={() => setUpModalMini(2, 0)}>Создать тариф на объем</CustomButton>
                    <CustomButton sx={{ padding: '11px 43px' }}>Изменить тариф </CustomButton>
                </ButtonContainer>
                <CustomHeader>Сокращатель ссылок</CustomHeader>
                <ButtonContainer>
                    <CustomButton onClick={() => setUpModalMini(3, 1)} sx={{ padding: '11px 65px' }}>
                        Создать тариф <br /> на аналитику время
                    </CustomButton>
                    <CustomButton onClick={() => setUpModalMini(3, 1)} sx={{ padding: '11px 65px' }}>
                        Создать тариф <br /> на a/b тесты время
                    </CustomButton>
                    <CustomButton sx={{ padding: '11px 65px' }}>
                        Изменить тариф
                    </CustomButton>
                </ButtonContainer>
                <DataGridElement openModal={handleOpenModalPackage} />
            </Box>
            <ModalMini open={openModalMini} type={type} variant={variant} close={handleCloseModalMini} />
            <ModalPackage open={openModalPackage} newPackage={newPackage} close={handleCloseModalPackage} />
        </>
    );
};


export default Tariffs;
