import React, { useState, useEffect, useCallback } from 'react';
import CheckboxTree from 'react-checkbox-tree';
import 'react-checkbox-tree/lib/react-checkbox-tree.css';
import { ContextMenu, MenuItem, ContextMenuTrigger } from 'react-contextmenu';
import axios from 'axios';
import {
  FaFile,
  FaFolder,
  FaUpload,
  FaPencilAlt,
  FaTrashAlt,
} from 'react-icons/fa';
import './FileTree.css';
import AddFilePopup from '../Popup/AddFilePopup/AddFilePopup';
import Popup from 'reactjs-popup';

export default function FileTree({ onFileChange }) {
  const [nodes, setNodes] = useState([
    {
      value: '/app',
      label: (
        <>
          <ContextMenuTrigger id={'SIMPLE'}>app</ContextMenuTrigger>
          <ContextMenu id={'SIMPLE'}>
            <MenuItem data={{ item: 'item 1' }}>Rename</MenuItem>
            <MenuItem data={{ item: 'item 2' }}>Delete</MenuItem>
            <MenuItem divider />
            <MenuItem data={{ item: 'item 3' }}>New File</MenuItem>
            <MenuItem data={{ item: 'item 3' }}>New Folder</MenuItem>
            <MenuItem data={{ item: 'item 3' }}>Upload File</MenuItem>
          </ContextMenu>
        </>
      ),
      showCheckbox: false,
      children: [
        {
          value: '/app/Http',
          label: 'Http',
          showCheckbox: false,
          children: [
            {
              value: '/app/Http/Controllers',
              label: 'Controllers',
              showCheckbox: false,
              children: [
                {
                  value: '/app/Http/Controllers/WelcomeController.js',
                  label: 'WelcomeController.js',
                  showCheckbox: false,
                },
              ],
            },
            {
              value: '/app/Http/routes.js',
              label: 'routes.js',
              showCheckbox: false,
            },
          ],
        },
        {
          value: '/app/Providers',
          label: 'Providers',
          showCheckbox: false,
          children: [
            {
              value: '/app/Providers/EventServiceProvider.js',
              label: 'EventServiceProvider.js',
              showCheckbox: false,
            },
          ],
        },
      ],
    },
    {
      value: '/.env',
      label: (
        <>
          <ContextMenuTrigger id={'SIMPL'}>.env</ContextMenuTrigger>
          <ContextMenu id={'SIMPL'}>
            <MenuItem data={{ item: 'item 1' }}>Rename</MenuItem>
            <MenuItem data={{ item: 'item 2' }}>Delete</MenuItem>
          </ContextMenu>
        </>
      ),
      showCheckbox: false,
    },
    {
      value: '/.gitignore',
      label: (
        <>
          <ContextMenuTrigger id={'SIMP'}>.gitignore</ContextMenuTrigger>
          <ContextMenu id={'SIMP'}>
            <MenuItem data={{ item: 'item 1' }}>Rename</MenuItem>
            <MenuItem data={{ item: 'item 2' }}>Delete</MenuItem>
          </ContextMenu>
        </>
      ),
      showCheckbox: false,
    },
  ]);
  const [expanded, setExpanded] = useState([]);
  const [selectedOperation, setSelectedOperation] = useState('');

  useEffect(() => {
    (async () => {
      const response = await axios.get('/app/api/files');
      if (response.status === 200) {
        const files = [];
        const swaggerFiles = response.data.data;

        console.log(swaggerFiles);

        // swaggerFiles.forEach((swaggerFile, index) => {
        //   files.push({
        //     value: `schema-${swaggerFile.slug}`,
        //     label: swaggerFile.slug,
        //     showCheckbox: false,
        //     children: [],
        //   });

        //   swaggerFile.translationFiles.forEach((translationFile) => {
        //     files[index].children.push({
        //       value: translationFile,
        //       label: (
        //         <>
        //           <ContextMenuTrigger id={'SIMPLE'}>
        //             right click to see the menu
        //           </ContextMenuTrigger>
        //           <ContextMenu id={'SIMPLE'}>
        //             <MenuItem onClick={handleClick} data={{ item: 'item 1' }}>
        //               Menu Item 1
        //             </MenuItem>
        //             <MenuItem onClick={handleClick} data={{ item: 'item 2' }}>
        //               Menu Item 2
        //             </MenuItem>
        //             <MenuItem divider />
        //             <MenuItem onClick={handleClick} data={{ item: 'item 3' }}>
        //               Menu Item 3
        //             </MenuItem>
        //           </ContextMenu>
        //         </>
        //       ),
        //       showCheckbox: false,
        //     });
        //   });
        // });

        // setNodes(files);
      }
    })();
  }, []);

  const handleClick = (e, data) => {
    console.log(e, data);
  };

  const onExpand = (newExpanded) => {
    setExpanded(newExpanded);
  };

  const onClick = async (targetNode) => {
    const response = await axios.get('/app/api/swagger', {
      params: { slug: targetNode.label },
    });

    onFileChange(JSON.stringify(response.data, null, 2));
  };

  const handleNewSwaggerFile = (swagger, swaggerName) => {
    setNodes(
      nodes.concat({
        label: swaggerName,
        value: swaggerName,
        showCheckbox: false,
      })
    );
  };

  const handleNewTranslationFile = (translationName) => {
    // TODO
  };

  const handleModalOpening = (operation) => {
    setSelectedOperation(operation);
  };

  return (
    <>
      <div className="operation-icons">
        <Popup
          trigger={
            <FaFile
              title="New Translation File"
              style={{ padding: '5px' }}
              values="New Translation File"
            />
          }
          modal
          closeOnDocumentClick
          onOpen={() => handleModalOpening('New Translation File')}
        >
          {(close) => (
            <AddFilePopup
              selected={selectedOperation}
              newSwaggerFile={handleNewSwaggerFile}
              newTranslationFile={handleNewTranslationFile}
              close={close}
            />
          )}
        </Popup>

        <Popup
          trigger={
            <FaFolder
              onClick={() => console.log('fdsfsd')}
              title="New Folder"
              style={{ padding: '5px' }}
            />
          }
          modal
          closeOnDocumentClick
        />
        <Popup
          trigger={
            <FaUpload title="Upload Swagger File" style={{ padding: '5px' }} />
          }
          modal
          closeOnDocumentClick
          onOpen={() => handleModalOpening('Upload Swagger File')}
        >
          {(close) => (
            <AddFilePopup
              selected={selectedOperation}
              newSwaggerFile={handleNewSwaggerFile}
              newTranslationFile={handleNewTranslationFile}
              close={close}
            />
          )}
        </Popup>

        <FaPencilAlt
          onClick={() => console.log('fdsfsd')}
          title="Rename"
          style={{ padding: '5px' }}
        />
        <FaTrashAlt
          onClick={() => console.log('fdsfsd')}
          title="Delete"
          style={{ padding: '5px' }}
        />
      </div>

      {nodes.length ? (
        <div className="file-checkbox-tree">
          <CheckboxTree
            expanded={expanded}
            nodes={nodes}
            onExpand={onExpand}
            onClick={onClick}
          />
        </div>
      ) : (
        'No files present. Please add a new file'
      )}
    </>
  );
}
