import { TreeItem, TreeView } from "@mui/lab";
import { Checkbox, FormControlLabel } from "@mui/material";
import React, { useEffect } from "react";
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import ChevronRightIcon from '@mui/icons-material/ChevronRight';
import { useGetCategoriesAllQuery } from "../../../store/categoriesApi";

let defaultExpandedArr = ["0"]

const fullTree = (arrCategories) => {
    arrCategories = JSON.parse(JSON.stringify(arrCategories));
    const recursion = (categoryObj) => {
      defaultExpandedArr.push(categoryObj._id)
     categoryObj.children = []
    

    if (categoryObj.subCategories !== null && categoryObj.subCategories?.length !== 0 ) {
        categoryObj.subCategories.forEach(element =>{
            arrChild.forEach( (value) => { if (value._id === element._id) {
                categoryObj.children.push(value)
                recursion(value)
            }} )
        })
        } 
    }
    
    const arrParent = arrCategories.filter((value) => value.parent === null )
    const arrChild = arrCategories.filter((value) => value.parent !== null )
   

    arrParent.forEach(recursion)
    
    return arrParent
    }
  

 const RecursiveTreeView = ({callback, selectedCat = []}) => {
  // console.log('selectedCat', selectedCat)
  const [selected, setSelected] = React.useState(selectedCat);
  // console.log('setSelect', selected)

  const {data: payloaddata} = useGetCategoriesAllQuery()
  const categories = payloaddata?.CategoryFind
  
useEffect((()=>setSelected(selectedCat)),[selectedCat])
  
  let data = {}

  if (categories) {
 
  

  data = {
        _id: "0",
        name: "Все категории",
        children: fullTree(categories)
  }
}

  // console.log('data', data)
  
 
  function getChildById(node, _id) {
    let array = [];

    function getAllChild(nodes) {
      if (nodes === null) return [];
      array.push(nodes._id);
      if (Array.isArray(nodes.children)) {
        nodes.children.forEach(node => {
          array = [...array, ...getAllChild(node)];
          array = array.filter((v, i) => array.indexOf(v) === i);
        });
      }
      return array;
    }

    function getNodeById(nodes, _id) {
      if (nodes._id === _id) {
        return nodes;
      } else if (Array.isArray(nodes.children)) {
        let result = null;
        nodes.children.forEach(node => {
          if (!!getNodeById(node, _id)) {
            result = getNodeById(node, _id);
          }
        });
        return result;
      }

      return null;
    }

    return getAllChild(getNodeById(node, _id));
  }

  function getOnChange(checked, nodes) {
    const allNode = getChildById(data, nodes._id);
    let array = checked
      ? [...selected, ...allNode]
      : selected.filter(value => !allNode.includes(value));

    array = array.filter((v, i) => array.indexOf(v) === i);

    callback(array)
    setSelected(array);
    
  }

  const renderTree = (nodes) => {

    return (
    <TreeItem
      key={nodes._id}
      nodeId={nodes._id}
      label={
        <FormControlLabel
          control={
            <Checkbox
              checked={selected.some(item => item === nodes._id)}
              onChange={event =>
                getOnChange(event.currentTarget.checked, nodes)
              }
              onClick={e => e.stopPropagation()}
            />
          }
          label={<>{nodes.name}</>}
          key={nodes._id}
        />
      }
    >
      {Array.isArray(nodes.children)
        ? nodes.children.map(node => renderTree(node))
        : null}
    </TreeItem>
  )};

  return (
    <TreeView
      defaultCollapseIcon={<ExpandMoreIcon />}

      defaultExpanded={defaultExpandedArr}
      defaultExpandIcon={<ChevronRightIcon />}
      
      
    >
      {renderTree(data)}
    </TreeView>
  );
}

export default RecursiveTreeView