"use client";

import { QrCodeInfo } from "@/app/api/qrcode";
import { Box, Button, Modal, ModalProps } from "@mui/material";
import { useCallback, useEffect, useMemo, useState } from "react";
import BarcodeScanner, { BarcodeStringFormat } from "react-qr-barcode-scanner";
import { BarcodeFormat, Result } from "@zxing/library";

interface Props {
  scannerConfig: ScannerConfig;
}

// interface Props extends Omit<ModalProps, "children"> {
//   scannerConfig: ScannerConfig;
// }

const style = {
  position: "absolute",
  top: "50%",
  left: "50%",
  transform: "translate(-50%, -50%)",
  bgcolor: "background.paper",
  pt: 5,
  px: 5,
  pb: 10,
  width: { xs: "80%", sm: "80%", md: "80%" },
};

export var defaultScannerConfig: ScannerConfig = {
  onUpdate: (err, result) => {
    if (result) {
      const data = JSON.parse(result.getText());
      console.log(data);
    } else return;
  },
  width: 500,
  height: 500,
  facingMode: "environment",
  // torch: false
};

export interface ScannerConfig {
  onUpdate: (arg0: unknown, arg1?: Result) => void;
  onError?: (arg0: string | DOMException) => void;
  width?: number | string;
  height?: number | string;
  facingMode?: "environment" | "user"; // default environment
  delay?: number; // Delay between scans in milliseconds. Default is 500ms.
  videoConstraints?: MediaTrackConstraints; // Video constraints to pass to the webcam. If not provided, the default constraints will be used.
  formats?: BarcodeFormat[] | BarcodeStringFormat[]; // Array of barcode formats to decode. If not provided, all formats will be used. A smaller list may improve the speed of the scan.
  stopStream?: boolean;
}

const ReactQrCodeScanner: React.FC<Props> = ({ scannerConfig }) => {
  const [stopStream, setStopStream] = useState(
    scannerConfig.stopStream || defaultScannerConfig.stopStream || false
  );
  const [torchEnabled, setTorchEnabled] = useState<boolean>(false);
  // const _scannerConfig = useMemo(() => ({
  //   ...defaultScannerConfig,
  //   ...scannerConfig,
  // }),[])
  const [_scannerConfig, setScannerConfig] = useState<ScannerConfig>({
    ...defaultScannerConfig
  });
  useEffect(() => {
    setScannerConfig({
      ...defaultScannerConfig,
      ...scannerConfig,
    });
  }, []);
  const SwitchOnOffScanner = useCallback(() => {
    // Stop the QR Reader stream (fixes issue where the browser freezes when closing the modal) and then dismiss the modal one tick later
    setStopStream((prev) => !prev);
  }, []);

  const SwitchOnOffTorch = useCallback(() => {
    setTorchEnabled((prev) => !prev);
  }, []);

  return (
    <>
      {!stopStream ? (
        <BarcodeScanner
          stopStream={stopStream}
          torch={torchEnabled}
          {..._scannerConfig}
        />
      ) : undefined}
      <Button onClick={SwitchOnOffTorch}>{torchEnabled ? "off" : "on"}</Button>
      <Button onClick={SwitchOnOffScanner}>
        {stopStream ? "start" : "stop"}
      </Button>
    </>
  );
};
export default ReactQrCodeScanner;
