import React from 'react';
import QrScanner from 'react-qr-scanner';
import { Box } from '@mui/material';
import styled from 'styled-components';
import Modal from '../components/Modal';

const ScannerContainer = styled(Box)`
    position: relative;
    width: 100%;
    height: 100%;
`;

const ScannerFrame = styled.div`
    position: absolute;
    top: 50%;
    left: 50%;
    width: 60%;
    height: 60%;
    transform: translate(-50%, -50%);
    border: 3px solid green;
    box-sizing: border-box;
    z-index: 2;
`;

const BlurOverlay = styled.div`
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;

    &::before,
    &::after {
        content: '';
        background: rgba(255, 255, 255, 0.7);
        backdrop-filter: blur(10px);
        position: absolute;
        pointer-events: none;
    }

    &::before {
        top: 0;
        left: 0;
        right: 0;
        height: calc(50% - 30%);
    }

    &::after {
        bottom: 0;
        left: 0;
        right: 0;
        height: calc(50% - 30%);
    }

    div {
        position: absolute;
        top: calc(50% - 30%);
        bottom: calc(50% - 30%);
        width: calc(50% - 30%);
        backdrop-filter: blur(10px);
        background: rgba(255, 255, 255, 0.7);
        pointer-events: none;
    }

    div:first-child {
        left: 0;
    }

    div:last-child {
        right: 0;
    }
`;

interface ScannerModalProps {
    open: boolean;
    onClose: () => void;
    onScan: (data: string | null) => void;
    slotQRCodes: string[]; // Required prop
}

const ScannerModal: React.FC<ScannerModalProps> = ({ open, onClose, onScan }) => {
    const handleScan = (data: string | null) => {
        if (data) {
            onScan(data);
        }
    };

    const handleError = (err: any) => {
        console.error(err);
    };

    const constraints = {
        video: { facingMode: "environment" }, // Switch to "environment" for the rear-facing camera
    };


    return (
        <Modal open={open} onClose={onClose} title="Scan QR Code">
            <ScannerContainer>
                <QrScanner
                    delay={300}
                    onError={handleError}
                    onScan={handleScan}
                    style={{ width: '100%' }}
                    constraints={constraints}
                />
                <BlurOverlay>
                    <div />
                    <div />
                </BlurOverlay>
                <ScannerFrame />
            </ScannerContainer>
        </Modal>
    );
}

export default ScannerModal;