import { StoreContext } from '../utils/store';
import React, { useContext, useEffect, useState } from 'react';
import { MenuItemService } from '../services/MenuItemService';
import StyledButton from "./core/StyledButton";
import appDebug from "../utils/appDebug";
import { AppConfig } from "../config/AppConfig";

const SaveBar = () => {

  const store = useContext(StoreContext);
  const [isSaved, setIsSaved] = useState(false);
  const [showMessage, setShowMessage] = useState(false)
  //const [hideMessage, setHideMessage] = useState(false);
  const [message, setMessage] = useState(null);
  const [enableMessageTimeout, setEnableMessageTimeout] = useState(false);

  // useEffect(() => {
    
  //   if (hideMessage) {
  //     const timer = setTimeout(() => {
  //       setShowMessage(false);
  //       setIsSaved(false);
  //     }, 2500);
      
  //     return () => {
  //       setShowMessage(false);
  //       setIsSaved(false);
  //       clearTimeout(timer);
  //     }
  //   }
    
  // }, [hideMessage]);

  useEffect(() => {

    if (store.isAnyItemChanged) {
      setMessage('You have unsaved changes');
      setIsSaved(false);
      setShowMessage(true);
    }
    else {
      setIsSaved(true);

      const timeout = ( enableMessageTimeout ) ? 2500 : 0;

      setTimeout(
        () => {
          setShowMessage(false);
          setEnableMessageTimeout(false);
        },
        timeout
      );
     
    }
    
  }, [store.isAnyItemChanged]);


  const performSave = async (event) => { // eslint-disable-line no-unused-vars

    try {

      const maxBatches = 1000;
      const updatedItems = [];

      let continueBatch = true;
      let batchCount = 1;
      let lastItemId = null;
      let saveResult = {};

      store.setIsSaving(true);
      setMessage('Preparing to Save...');
      setShowMessage(true);

      const revisionResult = await MenuItemService.prepareRevisionForSave(store.menuID, store.menuItems);
      
      setMessage("Processing Deletions...");

      const deletionResult = await MenuItemService.processDeletions(store.menuID, revisionResult.revision_id);
      
      setMessage("Saving...");

      //
      // If the save process takes too long, it will return with a lastItemID so
      // it can be continued in batches. Most saves should only take one batch but
      // this stops the server from timing out and canceling the process
      //
      while (continueBatch) {

        saveResult = await MenuItemService.saveItemRevision(store.menuID, deletionResult.revision_id, lastItemId);
        
        if (saveResult.items) {
          let batchItems = saveResult.items.map(
            (item) => {
              return {...item, isNewAddition: false, showEditor: false};
            }
          );

          updatedItems.push(...batchItems);

        }

        batchCount++;

        if (batchCount >= maxBatches) {
          throw new Error('Too many batches processed; Stopping Save');
        }

        if (saveResult.last_item_id) {
          lastItemId = saveResult.last_item_id;
          setMessage(`Saving Batch ${batchCount}...`);
        }
        else {
          continueBatch = false;
        }
      }

      appDebug(AppConfig.debugCategoryDefault, 'Save result', saveResult);
      
      
      // const updatedItems = result.items.map(
      //   (item) => {
      //     return {...item, isNewAddition: false, showEditor: false};
      //   }
      // );

      setMessage("Performing After-Save Operations...");
      
      await MenuItemService.postSaveActions(store.menuID);
      
      setEnableMessageTimeout(true);
      store.clearChangedItems();
      store.setMenuItems(updatedItems, {skipCheckForChanged: true});  
      setMessage("Menu Items Saved");
      
      store.setIsSaving(false);
      setIsSaved(true);

      // setTimeout(
      //   () => {
      //     setHideMessage(true);
      //   },
      //   1000
      // );
    }
    catch(e) {
      setMessage(e.message);
    }
    finally {
      store.setIsSaving(false);
    }
  }

  return (
    <div className={"mmu-save-bar " + ((store.isAnyItemChanged || showMessage) ? "mmu-save-bar--active" : "")}>
      {showMessage ? <div className="mmu-save-bar-message">{message}</div> : ""}
      {store.isAnyItemChanged || showMessage ?
      <> 
        { !isSaved ?
        <StyledButton onClick={performSave} name="save">
          { store.isSaving ? <span className="dashicons dashicons-update mmu-icon-button--item-loading"></span>: "Save" }
        </StyledButton>
        : "" } 
      </>
      : ""}
    </div>
  );
}

export default SaveBar;