import { InputNumber, Popover } from "antd";
import { useEffect, useRef, useState } from "react";

const FormInputNUmberCalculator = ({ value: formValue, onChange: formOnChange, ...restProps }) => {
  const [value, setValue] = useState(formValue);
  const [total, setTotal] = useState(0);
  const [history, setHistory] = useState([]);

  const ref = useRef(null);

  const handleKeyDown = (e) => {
    const { key } = e;
    let action;
    switch (key) {
      case "/":
      case "*":
      case "+":
      case "-":
        action = key;
        break;
      case "Enter":
        action = "=";
        break;
      default:
        setValue(e.currentTarget.value);
        return;
    }
    const val = parseFloat(value);
    setValue(null);
    ref.current.blur();
    ref.current.focus();
    if (!isNaN(val)) {
      setHistory([...history, val, action]);
    }
  };

  useEffect(() => {
    if (value !== formValue && formOnChange) formOnChange(value);
  }, [formOnChange, formValue, value]);

  useEffect(() => {
    if (history.length > 2) {
      const subTotal = history.reduce((acc, val, idx) => {
        if (idx === 0) {
          return val;
        }
        switch (val) {
          case "/":
          case "*":
          case "+":
          case "-":
            return acc;

          default:
            //Weve got math on our hands. Find the last operator, and apply it accordingly.
            switch (history[idx - 1]) {
              case "/":
                return acc / val;
              case "*":
                return acc * val;
              case "+":
                return acc + val;
              case "-":
                return acc - val;
              default:
                return acc;
            }
        }
      }, 0);
      setTotal(subTotal);
      if (history[history.length - 1] === "=") {
        setValue(subTotal);
        ref.current.blur();
        ref.current.focus();
        setHistory([]);
      }
    }
  }, [history]);

  const popContent = (
    <div style={{ display: "flex", flexDirection: "column" }}>
      History
      {history.map((h, idx) => (
        <div style={{ marginLeft: "auto" }} key={idx}>
          {h}
        </div>
      ))}
      <div>{total}</div>
    </div>
  );

  return (
    <div>
      <Popover content={popContent} open={history.length > 0}>
        <InputNumber
          ref={ref}
          value={value}
          defaultValue={value}
          onKeyDown={handleKeyDown}
          onBlur={() => setHistory([])}
          {...restProps}
        />
      </Popover>
    </div>
  );
};

export default FormInputNUmberCalculator;
