import * as React from "react";
import { Box } from "@mui/material";
import Templater from "./Templater";
import Quiz from "./Quiz";
import Contractor from "./Contractor";
import DataGridElement from "./DataGridElement";
import ModalMini from "./ModalMini";
import ModalPackage from "./ModalPackage";
import { ArrayProps, Tariff } from "./types";
import useStore from "../../../../store";
import theme from "../../../../theme";


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 store = useStore( (state) => state );

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

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

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

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

    store.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: "",
        time: "",
        points: "",
        price: 0
    }

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

  return (
    <React.Fragment>
      <Box sx={{ 
        width: "90%",
        display: "flex",
        flexDirection: "column",
        justifyContent: "center",
        alignItems: "center"
      }}>
        <Templater openModal={ setUpModalMini } />
        <Quiz openModal={ setUpModalMini } />
        <Contractor openModal={ setUpModalMini } />
        <DataGridElement openModal={ handleOpenModalPackage } />
      </Box>

      <ModalMini open={ openModalMini } type={ type } variant={ variant } close={ handleCloseModalMini } />
      <ModalPackage open={ openModalPackage } newPackage={ newPackage } close={ handleCloseModalPackage } />
    </React.Fragment>
  );
}


export default Tariffs;