import React, {
  useEffect,
  useRef,
} from 'react';

import {
  useDispatch,
  useSelector,
} from 'react-redux';

import { getDeviceAdditionInfo } from '../../actions/deviceActions';
import {
  scaleH,
  scaleW,
} from '../../utils/helperMethods';

export default function TQRCodeNew({
  isBillingProductVisible,
  ariaLabel,
  text,
  width = "128",
  height = "128",
}) {
  const qrcodeRef = useRef(null);
  const deviceInfo = useSelector((state) => state.device.deviceInfo);
  const { entryMenu, nowMenu } = useSelector((state) => state.common.menu);
  const dispatch = useDispatch();

  useEffect(() => {
    if (!deviceInfo) {
      dispatch(getDeviceAdditionInfo());
    }
  }, [deviceInfo, dispatch]);

  const applyCircularMask = (scaledWidth, scaledHeight) => {
    if (!qrcodeRef.current) return;

    const canvas = qrcodeRef.current.querySelector('canvas');
    if (!canvas) return;

    const radius = scaledWidth / 2;

    // 원본 canvas 저장
    const tempCanvas = document.createElement('canvas');
    tempCanvas.width = scaledWidth;
    tempCanvas.height = scaledHeight;
    const tempCtx = tempCanvas.getContext('2d');
    tempCtx.drawImage(canvas, 0, 0);

    // 원본 canvas 초기화
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, scaledWidth, scaledHeight);

    // 원형 마스크 적용
    ctx.beginPath();
    ctx.arc(radius, radius, radius, 0, Math.PI * 2);
    ctx.clip();

    // 이미지 다시 그리기
    ctx.drawImage(tempCanvas, 0, 0);
  };

  useEffect(() => {
    if (typeof window === "object" && entryMenu && nowMenu) {
      if (qrcodeRef.current) {
        while (qrcodeRef.current.firstChild) {
          qrcodeRef.current.removeChild(qrcodeRef.current.firstChild);
        }
      }
      // nowMenu 데이터를 Base64로 인코딩
      const encodedNowMenu = encodeURIComponent(nowMenu);
      const encodeEntryMenu = encodeURIComponent(entryMenu);

      let idx;

      if (deviceInfo === null || !deviceInfo) {
        idx = 0;
      } else {
        idx = deviceInfo?.dvcIndex;
      }

      const scaledWidth = scaleW(width);
      const scaledHeight = scaleH(height);

      const qrcode = new window.QRCode(qrcodeRef.current, {
        text: isBillingProductVisible
          ? text
          : `${text}&entryMenu=${encodeEntryMenu}&nowMenu=${encodedNowMenu}&idx=${idx}`,
        width: scaledWidth,
        height: scaledHeight,
        correctLevel: window.QRCode.CorrectLevel.L,
      });

      // QR코드 생성 완료 후 원형 마스킹 적용
      setTimeout(() => {
        applyCircularMask(scaledWidth, scaledHeight);
      }, 100);
    }
  }, [text, deviceInfo, entryMenu, nowMenu, isBillingProductVisible, width, height]);

  return <div aria-label={ariaLabel} ref={qrcodeRef} />;
}
