import React, {FC, useEffect, useCallback} from 'react';
import {useIsFocused} from '@react-navigation/native';
import {ImageBackground, StyleSheet} from 'react-native';
import {
  Camera,
  useCameraDevices,
  useFrameProcessor,
} from 'react-native-vision-camera';
import {useNavigation} from '@react-navigation/native';
import {scanBarcodes, BarcodeFormat, Barcode} from 'vision-camera-code-scanner';
import BarcodeMask from 'react-native-barcode-mask';
import jwt_decode from 'jwt-decode';
import {runOnJS} from 'react-native-reanimated';
import useUser from '@contexts/user';
import {HOME} from '@constants/navigation/app-bottom-tab';
import QRCodeScannerIcon from '@assets/svg/QrCodeScannerCrossIcon';
import {
  Container,
  CrossIcon,
  CameraContainer,
  CameraView,
} from '@styles/screens/qr-code-scanner';

const QRCodeScanner: FC<{active: boolean}> = () => {
  const isFocused = useIsFocused();
  const navigation: any = useNavigation();
  const [hasPermission, setHasPermission] = React.useState<boolean>(false);
  const {setCredentialRequests} = useUser();

  const devices = useCameraDevices();
  const device = devices.back;

  const onQRCodeDetected = useCallback(
    (qrCode: string) => {
      const decoded: any = jwt_decode(qrCode);

      setCredentialRequests({
        ...JSON.parse(JSON.stringify(decoded?.interactionToken)),
        scan: true,
      });
      navigation.navigate(HOME.SCREEN);
    },
    [navigation, setCredentialRequests],
  );

  const frameProcessor = useFrameProcessor(frame => {
    'worklet';
    const detectedBarcodes: Barcode[] = scanBarcodes(
      frame,
      [BarcodeFormat.QR_CODE],
      {
        checkInverted: true,
      },
    );

    if (detectedBarcodes?.length > 0 && detectedBarcodes[0]?.displayValue) {
      runOnJS(onQRCodeDetected)(detectedBarcodes[0]?.displayValue);
    }
  }, []);

  useEffect(() => {
    (async () => {
      const cameraPermission = await Camera.getCameraPermissionStatus();
      if (cameraPermission !== 'authorized') {
        const status = await Camera.requestCameraPermission();
        setHasPermission(status === 'authorized');
      } else {
        setHasPermission(cameraPermission === 'authorized');
      }
    })();
  }, []);

  return (
    <Container>
      <ImageBackground
        source={require('@assets/images/scan/scan-bg.png')}
        style={StyleSheet.absoluteFill}>
        {!!device && hasPermission && (
          <CameraContainer>
            <CameraView
              device={device}
              isActive={isFocused}
              frameProcessor={frameProcessor}
              frameProcessorFps={5}
            />

            <BarcodeMask
              outerMaskOpacity={0 - 1}
              edgeColor="#46D0F2"
              animatedLineColor="#46D0F2"
              height={260}
              width={260}
              edgeHeight={50}
              edgeWidth={50}
              edgeRadius={15}
              showAnimatedLine={true}
            />
          </CameraContainer>
        )}
        <CrossIcon onPress={() => navigation.navigate(HOME.SCREEN)}>
          <QRCodeScannerIcon />
        </CrossIcon>
      </ImageBackground>
    </Container>
  );
};

export default QRCodeScanner;
