import {
  Button,
  CardContent,
  Card,
  Modal,
  SxProps,
  ModalProps,
  Box,
  CardActions,
} from "@mui/material";
import QrCodeScanner from "./QrCodeScanner";
import { useCallback, useEffect, useRef, useState } from "react";
import { CameraDevice } from "html5-qrcode";
import { QrCodeInfo } from "@/app/api/qrcode";

const modalSx: SxProps = {
  position: "absolute",
  top: "50%",
  left: "50%",
  transform: "translate(-50%, -50%)",
  width: { xs: "calc(100% - 2rem)", sm: "90%" },
  maxHeight: "90%",
  maxWidth: 1400,
};

type QrCodeScannerModalProps = {
  cameras: CameraDevice[];
  title?: string;
  contents?: string[];
  isOpen: boolean;
  onClose: () => void;
  onScanSuccess: (qrCodeInfo: QrCodeInfo) => void;
  onScanError?: (error: string) => void;
};

const QrCodeScannerModal: React.FC<QrCodeScannerModalProps> = ({
  cameras,
  title,
  contents,
  isOpen,
  onClose,
  onScanSuccess,
  onScanError,
}) => {
  const [modalOpen, setModalOpen] = useState(isOpen); // pass to qr code scanner
  useEffect(() => {
    setModalOpen(isOpen);
  }, [isOpen]);

  const onModalClose = useCallback<NonNullable<ModalProps["onClose"]>>(
    (_, reason) => {
      if (reason !== "backdropClick") {
        setModalOpen(false);
      }
    },
    [],
  );

  return (
    <Modal open={isOpen} onClose={onModalClose}>
      <Card sx={modalSx}>
        <CardContent sx={{ overflow: "auto", maxHeight: "90vh" }}>
          <Box
            sx={
              {
                // marginInline: -1,
                // marginBlock: 1,
              }
            }
          >
            <QrCodeScanner
              cameras={cameras}
              title={title}
              contents={contents}
              onScanSuccess={onScanSuccess}
              onScanError={onScanError}
              isOpen={modalOpen}
              onClose={onClose}
            />
          </Box>
        </CardContent>
      </Card>
    </Modal>
  );
};

export default QrCodeScannerModal;
