import {useState, useEffect} from 'react'
import React from 'react'

import axios from 'axios';

import {Snackbar, Alert} from '@mui/material';

import TreeView from '@mui/lab/TreeView';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import ChevronRightIcon from '@mui/icons-material/ChevronRight';
import TreeItem from '@mui/lab/TreeItem';

const baseURL = "http://localhost:8000/api"
const apiURL = "/article/categories/"



const CategoryTree = (props) => {
  const { value, article, onChange } = props;

  const [categories, setCategories] = useState({id: 'root', data: {id: -1, name: ''}});
  const [snackbar, setSnackbar] = useState(null);

  const renderTree = (nodes) => (
    <TreeItem key={nodes.id} nodeId={nodes.id.toString()} label={nodes.data.name}>
      {Array.isArray(nodes.children)
        ? nodes.children.map((node) => renderTree(node))
        : null}
    </TreeItem>
  );

  const handleCloseSnackbar = () => setSnackbar(null);

  const handleNodeSelect = async (e, nodeid) => {
    try {
      //var completeCategory = {};
      const completeCategory = await axios.get(baseURL+"/article/categories/"+nodeid);

      //console.log(completeCategory.data);
      const newArticle = { ...article, 'category': completeCategory.data};
      const sendArticle = await axios.put(baseURL+"/article/"+article.pk, {
          article: newArticle 
      });
      //console.log(newArticle)
      setSnackbar({ children: 'Änderungen erfolgreich gespeichert', severity: 'success' });

      onChange(newArticle);

    } catch (error) {
        setSnackbar({ children: error.message, severity: 'error' });

    }
  };


  useEffect(()=>{      
    axios.get(baseURL+apiURL)
         .then((res) => {
            const data = res.data;
            setCategories(data);
            //console.log(data);
        })

  },[])

  return (
    <div style={{ height: 350, width: '100%' }}>
      <TreeView
        //aria-label="rich object"
        defaultExpanded={value === null ? [] : value.ancestorIds.map(x => String(x)) } 
        defaultExpandIcon={<ChevronRightIcon />}
        defaultCollapseIcon={<ExpandMoreIcon />}
        defaultSelected={value === null ? [''] : value.id.toString()}
        onNodeSelect={handleNodeSelect}
        sx={{ height: 350, flexGrow: 1, overflowY: 'auto' }}
      >
        {renderTree(categories)}
      </TreeView>
      {!!snackbar && (
          <Snackbar
          open
          anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
          onClose={handleCloseSnackbar}
          autoHideDuration={6000}
          >
          <Alert {...snackbar} onClose={handleCloseSnackbar} />
          </Snackbar>
      )}
    </div>
  );
}

export default CategoryTree

