import {useDispatch, useSelector} from "react-redux";
import {AppState} from "../../../store/store";
import React, {useCallback, useEffect, useRef, useState} from "react";
import useComponentResizeListener from "../../../hooks/componentResizeListener";

import {CupItem} from "../../../hooks/rustWsServer";
import {IconButton, useTheme} from "@mui/material";
import {AddRounded, RemoveRounded, SettingsRounded} from "@mui/icons-material";
const Cup = ({workerRef, symbol, volume, volumeAsDollars, order, setOrder, settings, setShowSettings}: CupProps) => {

  const [canvasSize, setCanvasSize] = useState<CanvasSize>({height: 0, width: 0});
  const containerRef = useRef<HTMLDivElement|null>(null);
  const canvasRef = useRef<HTMLCanvasElement|null>(null);
  const cupSubscribe = useCallback(async(pair: string, zoom: number) => {
    workerRef.current?.postMessage(JSON.stringify({type: "subscribe", pair, zoom}));
  }, []);

  const cupUnsubscribe = useCallback(async(pair: string) => {
    workerRef.current?.postMessage(JSON.stringify({type: "unsubscribe", pair}));
  }, []);
  const wheelHandler = (e: WheelEvent) => {
    e.preventDefault();
    workerRef.current?.postMessage(JSON.stringify({type: e.deltaY < 0 ? "camera_up" : "camera_down"}));
  };
  useEffect(() => {
    workerRef.current = new Worker(new URL("/workers/cup-builder.ts", import.meta.url));
    canvasRef.current?.addEventListener("wheel", wheelHandler, {passive: false});
    sendSettings();

    return () => {
      workerRef.current?.terminate();
      canvasRef.current?.removeEventListener("wheel", wheelHandler);
    };
  }, []);

  canvasRef.current?.addEventListener("click", (event) => {
    console.log("click");
    
  });

  useEffect(() => {
    if (!workerRef.current) return;
    let animationFrameId: number|null = null;

    workerRef.current.onmessage = (event: MessageEvent<{
      type: string,
      camera: number,
      aggregation: number,
      bestBidPrice: number,
      bestAskPrice: number,
      maxVolume: number,
      pricePrecision: number,
      quantityPrecision: number,
      priceStep: number,
      cup: {[key: number]: CupItem},
      rowsCount: number,
      volumeAsDollars: boolean,
    }>) => {
};
    return () => {
      if (null !== animationFrameId) {
        cancelAnimationFrame(animationFrameId);
      }
    };
  }, [workerRef.current, canvasSize, darkMode, dpiScale, isLoaded]);

  useEffect(() => {
    setDpiScale(Math.ceil(window.devicePixelRatio));
  }, [window.devicePixelRatio]);

  useEffect(() => {
    if (!size) {
      return;
    }

    setCanvasSize({
      width: Math.floor(size.width) * dpiScale,
      height: Math.floor(size.height) * dpiScale,
    });
  }, [dpiScale, size]);

  useEffect(() => {
    cupSubscribe(symbol.toUpperCase(), zoom);

    return () => {
      cupUnsubscribe(symbol.toUpperCase());
    };
  }, [symbol, zoom]);

  return <div ref={containerRef} className={styles.canvasWrapper}>
    <div className={styles.controls}>
      <IconButton onClick={zoomSub} size="small" disabled={!isLoaded}>
        <RemoveRounded />
      </IconButton>
      <span>x{zoom}</span>
      <IconButton onClick={zoomAdd} size="small" disabled={!isLoaded}>
        <AddRounded />
      </IconButton>
      <IconButton onClick={() => setShowSettings(true)} size="small">
        <SettingsRounded
          // @ts-ignore
          fontSize="xx-small"
        />
      </IconButton>
    </div>
    <canvas
      ref={canvasRef}
      className={[styles.canvas, isLoaded ? "" : styles.loading].join(" ")}
      width={canvasSize?.width}
      height={canvasSize?.height}
    />
  </div>;
};

export default Cup;

canvasRef.current?.addEventListener("click", (event) => {
    console.log("click");
      });  // событие клика вешается несколько раз. я кликаю и он срабатывает не один раз, как исправить эту причину?