//@ts-nocheck
import React, { useState, useEffect, useRef } from 'react';
import {
  View,
  Text,
  Button,
  StyleSheet,
  PermissionsAndroid,
  Platform,
  Alert,
  TouchableOpacity,
  NativeModules,
} from 'react-native';
import { StackActions, useNavigation } from '@react-navigation/native';
import {
  Camera as VisionCamera,
  useCameraDevice,
  useCameraFormat,
} from 'react-native-vision-camera';
import TextRecognition from '@react-native-ml-kit/text-recognition';
import {
  openSettings,
  PERMISSIONS,
  request,
  RESULTS,
} from 'react-native-permissions';
import { MText } from '../../components/MText';
import MButton from '../../components/MButton';
import { IconBackWhite } from '../../assets/icons';
import { commonStyles } from '../CommonStyles';
import nfcStore from './store';
import { ScreenNames } from '../../navigation';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

const { NFCReader } = NativeModules;

const MRZScanner = (props: any) => {
  const insets = useSafeAreaInsets();
  const navigation = useNavigation();
  const loan = props?.route?.params?.loan;

  const [hasCameraPermission, setHasCameraPermission] = useState(null);
  const [mrzData, setMrzData] = useState('');
  const [passPermission, setPassPermission] = useState(false);
  const cameraRef = useRef(null);
  const device = useCameraDevice('back');
  const format = useCameraFormat(device, [
    { photoResolution: { width: 1280, height: 720 } },
  ]);

  const requestPermissions = () => {
    request(
      Platform.OS === 'ios'
        ? PERMISSIONS.IOS.CAMERA
        : PERMISSIONS.ANDROID.CAMERA
    ).then((result) => {
      switch (result) {
        case RESULTS.UNAVAILABLE:
          console.log(
            'This feature is not available (on this device / in this context)'
          );
          Alert.alert(
            'Thông báo',
            'Máy ảnh trên thiết bị không tương thích.\nVui lòng kiểm tra lại thiết bị!',
            [{ text: 'Đồng ý' }]
          );
          break;
        case RESULTS.DENIED:
          console.log(
            'The permission has not been requested / is denied but requestable'
          );
          Alert.alert(
            'Thông báo',
            'Bạn đã từ chối quyền máy ảnh. Vui lòng cấp quyền máy ảnh để tiếp tục!',
            [
              {
                text: 'Đồng ý',
                onPress: () => {
                  if (Platform.OS === 'ios') {
                    openSettings();
                  } else {
                    requestPermissions();
                  }
                },
              },
            ]
          );
          break;
        case RESULTS.LIMITED:
          console.log('The permission is limited: some actions are possible');
          Alert.alert(
            'Thông báo',
            'Quyền máy ảnh bị hạn chế. Vui lòng kiểm tra lại để tiếp tục!',
            [
              {
                text: 'Đồng ý',
                onPress: () => {
                  if (Platform.OS === 'ios') {
                    openSettings();
                  } else {
                    requestPermissions();
                  }
                },
              },
            ]
          );
          break;
        case RESULTS.GRANTED:
          console.log('The permission is granted');
          setPassPermission(true);
          break;
        case RESULTS.BLOCKED:
          console.log('The permission is denied and not requestable anymore');
          Alert.alert(
            'Thông báo',
            'Bạn đã từ chối quyền máy ảnh. Vui lòng cấp quyền máy ảnh để tiếp tục!',
            [
              {
                text: 'Đồng ý',
                onPress: () => {
                  if (Platform.OS === 'ios') {
                    openSettings();
                  } else {
                    openSettings();
                  }
                },
              },
            ]
          );
          break;
      }
    });
  };

  useEffect(() => {
    requestPermissions();
  }, []);

  const convertToDate = (input, end) => {
    let yearPrefix = input.substring(0, 2);
    let year = end
      ? '20' + yearPrefix
      : parseInt(yearPrefix) > 20
      ? '19' + yearPrefix
      : '20' + yearPrefix;
    let month = input.substring(2, 4);
    let day = input.substring(4, 6);

    return year + '-' + month + '-' + day;
  };

  const extractMRZInfo = (text) => {
    let documentNumber = '';
    let birthDate = '';
    let expirationDate = '';
    const regex1 = /VNM(\d{9})/;
    const match1 = text.match(regex1);

    // If a match is found, return the 9 digits, otherwise return null
    if (match1) {
      documentNumber = match1[1];
    }

    console.log('documentNumber', documentNumber);

    // Regular expression to match 'VNM' followed by 9 digits, then two 6-digit numbers
    const regex = /(\d{6}).[MF](\d{6})/;

    // Search for the pattern in the text
    const match = text.replace(/ /g, '').match(regex);

    // If a match is found, return the captured groups, otherwise return null
    if (match) {
      console.log({
        documentNumber: documentNumber,
        birthDate: match[1],
        expirationDate: match[2],
      });
      (birthDate = match[1]), (expirationDate = match[2]);
    } else {
      return null;
    }
    if (documentNumber && birthDate && expirationDate) {
      console.log(convertToDate(birthDate, false));
      console.log(convertToDate(expirationDate, true));
      try {
        NFCReader.startNFCReader(
          documentNumber,
          convertToDate(birthDate, false),
          convertToDate(expirationDate, true),
          (error, response) => {
            try {
              const convertData = JSON.parse(response);
              const body = {
                LoanBriefId: loan?.id,
                RawSod: convertData?.sod,
                RawDg1: convertData?.dg1,
                RawDg2: convertData?.dg2,
                RawDg13: convertData?.dg13,
                RawDg14: convertData?.dg14,
                RawDg15: convertData?.dg15,
              };
              nfcStore.addNfcData(body, () => {
                navigation.dispatch(
                  StackActions.push(ScreenNames.FullSubmit, {
                    loan: loan,
                  })
                );
              });
            } catch (e) {
              console.log(e);
              Alert.alert('Lỗi', e);
            }
          }
        ).t;
      } catch (e) {
        console.log(e);
      }
    }
  };

  const handleTextRecognition = async (imagePath) => {
    try {
      const result = await TextRecognition.recognize(imagePath);
      const mrzText = result.text;
      setMrzData(mrzText);
      extractMRZInfo(mrzText);
    } catch (error) {
      console.log(error);
    }
  };

  const takePicture = async () => {
    if (cameraRef.current) {
      const data = await cameraRef.current.takePhoto({
        qualityPrioritization: 'speed',
      });
      await handleTextRecognition('file://' + data.path);
    }
  };

  return (
    <View style={styles.container}>
      {passPermission && device ? (
        <VisionCamera
          ref={cameraRef}
          style={styles.camera}
          device={device}
          isActive={true}
          photo={true}
          format={format}
        />
      ) : (
        <View style={styles.camera} />
      )}
      <View style={styles.overlay}>
        <View style={styles.overlayTop} />
        <View style={styles.overlayCenter}>
          <View style={styles.overlayLeft} />
          <View style={styles.overlayRect}></View>
          <View style={styles.overlayRight} />
        </View>
        <View style={styles.overlayBottom} />
      </View>

      <View
        style={{ position: 'absolute', top: insets.top, left: 0, right: 0 }}
      >
        <View
          style={[
            commonStyles.row,
            commonStyles.alignCenter,
            { height: 56, paddingHorizontal: 16 },
          ]}
        >
          <MButton
            onPress={() => {
              navigation.goBack();
            }}
            style={[{ width: 48, height: 48, justifyContent: 'center' }]}
          >
            <IconBackWhite />
          </MButton>
          <View style={{ flex: 1, paddingRight: 48 }}>
            <MText
              style={{
                color: 'white',
                fontSize: 16,
                textAlign: 'center',
                padding: 16,
                fontWeight: '600',
              }}
            >
              EKYC
            </MText>
          </View>
        </View>
        <MText
          style={{
            color: 'white',
            fontSize: 16,
            textAlign: 'center',
            padding: 16,
          }}
        >
          Dùng camera để quét chuỗi ký tự mặt sau thẻ CCCD gắn chip ở phía dưới
        </MText>
      </View>
      <View style={styles.buttonContainer}>
        <MText
          style={{
            color: 'white',
            fontSize: 14,
            textAlign: 'center',
            padding: 16,
          }}
        >
          Vui lòng đặt giấy tờ nằm vừa khung hình chữ nhật, chụp đủ ánh sáng và
          rõ nét.
        </MText>
        <TouchableOpacity
          onPress={() => takePicture()}
          style={styles.captureButton}
        ></TouchableOpacity>
      </View>
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  camera: {
    flex: 1,
  },
  buttonContainer: {
    flex: 0,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    position: 'absolute',
    bottom: 40,
    left: 0,
    right: 0,
  },
  captureButton: {
    width: 56,
    height: 56,
    borderRadius: 35,
    backgroundColor: 'white',
    justifyContent: 'center',
    alignItems: 'center',
  },
  innerCaptureButton: {
    width: 60,
    height: 60,
    borderRadius: 30,
    backgroundColor: 'red',
  },
  overlay: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    justifyContent: 'center',
    alignItems: 'center',
  },
  overlayTop: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    width: '100%',
  },
  overlayCenter: {
    flexDirection: 'row',
  },
  overlayLeft: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
  },
  overlayRect: {
    width: '90%',
    height: 100,
    borderColor: 'white',
    borderWidth: 2,
    justifyContent: 'center',
    alignItems: 'center',
  },
  instructionText: {
    color: 'white',
    textAlign: 'center',
    paddingHorizontal: 10,
    fontSize: 14,
    position: 'absolute',
    top: -50,
  },
  overlayRight: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
  },
  overlayBottom: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    width: '100%',
  },
  mrzContainer: {
    padding: 10,
  },
  mrzText: {
    fontSize: 16,
  },
});

export default MRZScanner;
