import { FC, useEffect, useState } from "react";
import QRCodeInternal from "react-qr-code";
import { Box } from "@mui/material";
import { colors } from "../styles/theme";

type QRCodeProps = {
  name: string;
  label: string;
  token: string;
  verified: boolean;
  helperText?: string;
  getValue?: (id: string) => Promise<string>;
  refreshInterval?: number;
};

export const QRCode: FC<QRCodeProps> = ({
  name,
  label,
  token,
  verified,
  helperText,
  getValue,
  refreshInterval,
}) => {
  const [value, setValue] = useState("");
  const { white } = colors;

  useEffect(() => {
    if (!verified && getValue && refreshInterval) {
      const interval = setInterval(async () => {
        const result = await getValue(token);
        setValue(result);
      }, refreshInterval * 1000);
      return () => clearInterval(interval);
    }
  }, [getValue, refreshInterval]);

  return !verified ? (
    <Box sx={{ backgroundColor: white, m: 2 }}>
      <QRCodeInternal value={value} />
      <Box>{helperText}</Box>
    </Box>
  ) : null;
};
