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 TQRCode({
  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]);

  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 qrcode = new window.QRCode(qrcodeRef.current, {
        text: isBillingProductVisible
          ? text
          : `${text}&entryMenu=${encodeEntryMenu}&nowMenu=${encodedNowMenu}&idx=${idx}`,
        width: scaleW(width),
        height: scaleH(height),
        correctLevel: window.QRCode.CorrectLevel.L,
      });
    }
  }, [text, deviceInfo, entryMenu, nowMenu, width, height]);
  return <div aria-label={ariaLabel} ref={qrcodeRef} />;
}
