//@ts-nocheck
import React, { useEffect, useRef, useState } from 'react';
import { observer, Observer } from 'mobx-react-lite';
import {
  View,
  NativeModules,
  TouchableOpacity,
  SafeAreaView,
  TextStyle,
  ViewStyle,
  ImageStyle,
  Image,
  ActivityIndicator,
  Dimensions,
  StyleSheet,
  Alert,
  Platform,
} from 'react-native';
import { MText } from '../../components/MText';
import { load, OCR_V1, save } from '../../utils/storage';
import {
  request,
  PERMISSIONS,
  RESULTS,
  openSettings,
} from 'react-native-permissions';
import {
  Camera as VisionCamera,
  useCameraDevice,
  useCameraFormat,
} from 'react-native-vision-camera';
import Modal from 'react-native-modal';
import LinearGradient from 'react-native-linear-gradient';
import {
  Cam2Svg,
  ChipSvg,
  CloseIcon,
  IconBackWhite,
  TakePhotoSvg,
  TimaSmall,
} from '../../assets/icons';
import MButton from '../../components/MButton';
import { commonStyles } from '../CommonStyles';
import {
  StackActions,
  useNavigation,
  useIsFocused,
} from '@react-navigation/native';
import TextRecognition from '@react-native-ml-kit/text-recognition';
import { ScreenNames } from '../../navigation';
import { Api } from '../../services/api';
import Loading from '../../components/Loading';
import DeviceInfo from 'react-native-device-info';
import { IconUpload } from '../../assets/svgs';
import ImagePicker from 'react-native-image-crop-picker';
import { launchImageLibrary } from 'react-native-image-picker';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

const { NFCReader } = NativeModules;

export const OCR = observer(function OCR(props: any) {
  const insets = useSafeAreaInsets();
  const isFocused = useIsFocused();
  const [isLoading, setIsLoading] = useState(false);
  const navigation = useNavigation();
  const [showModal, setShowModal] = useState(false);
  const [type, setType] = useState('passport');
  const [taking, setTaking] = useState(false);
  const [passPermission, setPassPermission] = useState(false);
  const [shouldRenderCamera, setShouldRenderCamera] = useState(false);
  const myCamera = 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(() => {
    let timeout: NodeJS.Timeout;
    if (isFocused) {
      // Delay mounting camera to give Android time to release the previous one
      timeout = setTimeout(() => {
        setShouldRenderCamera(true);
      }, 500); // thử 300ms–500ms nếu cần
    } else {
      setShouldRenderCamera(false);
    }

    return () => clearTimeout(timeout);
  }, [isFocused]);

  const loadIntro = async () => {
    const intro = await load(OCR_V1);
    if (!intro) {
      setShowModal(true);
    }
  };

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

  const saveDataNfc = async (body) => {
    try {
      const response = await Api.getInstance().saveNfcInfo({
        ...body,
        loanBriefId: props?.route?.params?.loan?.id,
      });
      if (response.kind === 'ok') {
        if (response.data?.meta?.errorCode === 200) {
          setTimeout(() => {
            navigation.push(ScreenNames.TTSSelfie, {
              loan: props?.route?.params?.loan,
            });
          }, 500);
        } else {
          Alert.alert('Thông báo', response?.data?.meta?.errorMessage);
        }
      } else {
        Alert.alert('Thông báo', 'Có lỗi xảy ra. Vui lòng thử lại sau');
      }
    } catch (error) {
      console.log(error);
    }
  };

  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) {
      try {
        NFCReader.readNFCCard(
          documentNumber,
          convertToDate(birthDate, false),
          convertToDate(expirationDate, true),
          (error, response) => {
            try {
              const convertData = JSON.parse(response);
              saveDataNfc(convertData);
            } catch (e) {
              console.log(e);
            }
          }
        );
      } catch (e) {
        console.log(e);
      }
    }
  };

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

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

  const takePhoto = async () => {
    if (myCamera.current == null || taking) return;
    setTaking(true);
    const data = await myCamera.current.takePhoto({
      qualityPrioritization: 'quality',
    });
    const uri = 'file://' + data.path;
    setTaking(false);
    if (props?.route?.params?.front && !props.route?.params?.callback) {
      navigation.push(ScreenNames.TTSNationalIDFront, {
        uri,
        loan: props?.route?.params?.loan,
      });
    } else if (!props?.route?.params?.front && !props.route?.params?.callback) {
      navigation.push(ScreenNames.TTSNationalIDBack, {
        uri,
        loan: props?.route?.params?.loan,
      });
    } else {
      navigation.goBack();
      props.route?.params?.callback(uri);
    }
  };

  const pickImageFromGallery = async () => {
    if (Platform.OS === 'android') {
      const result = await launchImageLibrary({
        mediaType: 'photo',
      });
      if (result.assets) {
        if (props?.route?.params?.front && !props.route?.params?.callback) {
          navigation.push(ScreenNames.TTSNationalIDFront, {
            uri: result.assets[0]?.uri,
            loan: props?.route?.params?.loan,
          });
        } else if (
          !props?.route?.params?.front &&
          !props.route?.params?.callback
        ) {
          navigation.push(ScreenNames.TTSNationalIDBack, {
            uri: result.assets[0]?.uri,
            loan: props?.route?.params?.loan,
          });
        } else {
          navigation.goBack();
          props.route?.params?.callback(result.assets[0]?.uri);
        }
      }
    } else {
      ImagePicker.openPicker({}).then((image) => {
        if (props?.route?.params?.front && !props.route?.params?.callback) {
          navigation.push(ScreenNames.TTSNationalIDFront, {
            uri:
              Platform.OS === 'android' ? image?.path : 'file://' + image?.path,
            loan: props?.route?.params?.loan,
          });
        } else if (
          !props?.route?.params?.front &&
          !props.route?.params?.callback
        ) {
          navigation.push(ScreenNames.TTSNationalIDBack, {
            uri:
              Platform.OS === 'android' ? image?.path : 'file://' + image?.path,
            loan: props?.route?.params?.loan,
          });
        } else {
          navigation.goBack();
          props.route?.params?.callback(
            Platform.OS === 'android' ? image?.path : 'file://' + image?.path
          );
        }
      });
    }
  };

  return (
    <View
      style={{ flex: 1, backgroundColor: 'black' }}
      pointerEvents={'box-none'}
    >
      <View
        style={{
          alignItems: 'center',
          position: 'absolute',
          top: insets.top + 16,
          left: 0,
          right: 0,
          zIndex: 100,
        }}
      >
        <TouchableOpacity
          onPress={() => {
            navigation.navigate(ScreenNames.Main);
          }}
          style={{
            position: 'absolute',
            left: 10,
            top: 4,
            width: 24,
            height: 24,
            alignItems: 'center',
            justifyContent: 'center',
          }}
        >
          <IconBackWhite />
        </TouchableOpacity>
        <View
          style={{
            flexDirection: 'row',
            padding: 2,
            borderRadius: 4,
            alignItems: 'center',
            backgroundColor: 'transparent',
          }}
        >
          {/* <TouchableOpacity
            style={{}}
            onPress={() => {
              setType('passport');
            }}
          >
            <LinearGradient
              colors={
                type === 'passport'
                  ? ['#FF8E4F', '#EF592E']
                  : ['black', 'black']
              }
              style={{
                height: 28,
                paddingHorizontal: 8,
                borderRadius: 4,
                width: 100,
                flexDirection: 'row',
                alignItems: 'center',
              }}
            >
              <Cam2Svg />
              <MText
                style={{
                  color: 'white',
                  fontSize: 12,
                  fontWeight: 'bold',
                  marginLeft: 5,
                }}
              >
                Chụp 2 mặt
              </MText>
            </LinearGradient>
          </TouchableOpacity> */}
          {/* <View
            style={{
              backgroundColor: 'white',
              width: 1,
              borderRadius: 10,
              height: 20,
              marginHorizontal: 8,
            }}
          ></View> */}
          {/* <TouchableOpacity
            style={{}}
            onPress={() => {
              setType('nfc');
            }}
          >
            <LinearGradient
              colors={
                type === 'nfc' ? ['#FF8E4F', '#EF592E'] : ['black', 'black']
              }
              style={{
                height: 28,
                paddingHorizontal: 8,
                borderRadius: 4,
                width: 100,
                flexDirection: 'row',
                alignItems: 'center',
              }}
            >
              <ChipSvg />
              <MText
                style={{
                  color: 'white',
                  fontSize: 12,
                  fontWeight: 'bold',
                  marginLeft: 5,
                }}
              >
                NFC
              </MText>
            </LinearGradient>
          </TouchableOpacity> */}
        </View>
        <MText
          style={{
            color: 'white',
            fontSize: 16,
            textAlign: 'center',
            padding: 16,
            marginTop: 10,
          }}
        >
          {type === 'passport' && props?.route?.params?.front
            ? 'Chụp CMND/ CCCD mặt trước'
            : type === 'passport'
            ? 'Chụp CMND/ CCCD mặt sau'
            : 'Dùng camera để quét chuỗi ký tự mặt sau thẻ CCCD gắn chíp ở phía dưới'}
        </MText>
      </View>

      {passPermission && type === 'passport' && shouldRenderCamera ? (
        <View
          style={[
            commonStyles.alignCenter,
            commonStyles.fill,
            commonStyles.justifyCenter,
            {
              position: 'absolute',
              width: Dimensions.get('window').width,
              height: Dimensions.get('window').height,
            },
          ]}
        >
          {device ? (
            <VisionCamera
              ref={myCamera}
              style={{
                width: Dimensions.get('window').width,
                height: 260,
                overflow: 'hidden',
              }}
              device={device}
              isActive={true}
              photo={true}
              format={format}
            />
          ) : (
            <ActivityIndicator />
          )}
          <TouchableOpacity
            onPress={() => {
              pickImageFromGallery();
            }}
            style={{
              flexDirection: 'row',
              alignItems: 'center',
              gap: 8,
              marginTop: 16,
            }}
          >
            <IconUpload />
            <MText
              style={{
                color: 'white',
                fontSize: 12,
              }}
            >
              Tải ảnh từ thư viện
            </MText>
          </TouchableOpacity>

          <View style={[styles.buttonContainer, { bottom: insets.bottom }]}>
            <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>
            <MButton
              onPress={() => {
                takePhoto();
              }}
            >
              <TakePhotoSvg />
            </MButton>
          </View>
        </View>
      ) : passPermission && type === 'nfc' && shouldRenderCamera ? (
        <>
          {device ? (
            <VisionCamera
              ref={myCamera}
              style={styles.camera}
              device={device}
              isActive={true}
              photo={true}
              format={format}
            />
          ) : null}
          <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={styles.buttonContainer}>
            <MText
              style={{
                color: 'white',
                fontSize: 14,
                textAlign: 'center',
                padding: 16,
              }}
            >
              Vui lòng đặt chuỗi kí tự nằm vừa khung hình chữ nhật, chụp đủ ánh
              sáng và rõ nét.
            </MText>
            <TouchableOpacity
              onPress={() => {
                scanNfc();
              }}
            >
              <TakePhotoSvg />
            </TouchableOpacity>
          </View>
        </>
      ) : (
        <></>
      )}

      <Modal
        isVisible={showModal}
        style={$modal}
        backdropTransitionInTiming={0}
        nimationOutTiming={200}
        animationInTiming={200}
        animationIn={'slideInUp'}
        animationOut={'fadeOutDown'}
        useNativeDriverForBackdrop={true}
        useNativeDriver={true}
      >
        <LinearGradient colors={['#FF8E4F', '#EF592E']} style={$container}>
          <View style={$paddingV}>
            <TouchableOpacity
              onPress={() => {
                setShowModal(false);
                setTimeout(() => {
                  navigation.goBack();
                }, 100);
              }}
              style={{
                width: 24,
                height: 24,
                position: 'absolute',
                left: 16,
                top: 24,
                alignItems: 'center',
                zIndex: 10000,
              }}
            >
              <CloseIcon />
            </TouchableOpacity>
            <MText style={$title}>NHẬN DIỆN GIẤY TỜ TÙY THÂN</MText>
            <MText style={$description}>
              Chụp ảnh 2 mặt hoặc NFC CCCD/ CMND
            </MText>

            <Image
              source={require('../../assets/tts/vehicleStep.png')}
              style={$step}
            />

            <View style={$bg}>
              <View
                style={{
                  flexDirection: 'column',
                  alignItems: 'center',
                }}
              >
                <Image
                  source={require('../../assets/tts/Frame1000011946.png')}
                  style={{
                    width: '60%',
                    height: 70,
                    resizeMode: 'contain',
                    marginVertical: 16,
                  }}
                />
              </View>
              <View style={{ marginTop: 10, paddingHorizontal: 24 }}>
                <MText style={[$title2, { textAlign: 'left' }]}>
                  Cách 1: NFC (Áp dụng cho CCCD gắn chip)
                </MText>
                <View style={$row}>
                  <TimaSmall />
                  <MText style={$txt}>
                    Đặt phần chip đồng gần lại với phần phía trên của{'\n'}mặt
                    lưng điện thoại
                  </MText>
                </View>
                <View style={$row}>
                  <TimaSmall />
                  <MText style={$txt}>
                    Giữ nguyên cho đến khi đọc xong thông tin thẻ
                  </MText>
                </View>
                <Image
                  source={require('../../assets/tts/Frame1000011953.png')}
                  style={{
                    width: '100%',
                    height: 70,
                    resizeMode: 'contain',
                    marginTop: 16,
                  }}
                />
              </View>
              <View style={{ marginTop: 10, paddingHorizontal: 24 }}>
                <MText style={[$title2, { textAlign: 'left' }]}>
                  Cách 2: Chụp 2 mặt
                </MText>
                <View style={$row}>
                  <TimaSmall />
                  <MText style={$txt}>
                    Nên đặt CCCD/ CMND lên mặt phẳng để chụp
                  </MText>
                </View>
                <View style={$row}>
                  <TimaSmall />
                  <MText style={$txt}>
                    Đặt CCCD/ CMND nằm gọn trong khung hình (Không {'\n'} quá
                    nhỏ hay quá to làm mất chi tiết)
                  </MText>
                </View>
                <View style={$row}>
                  <TimaSmall />
                  <MText style={$txt}>
                    Chọn nơi ánh sáng tốt, tránh lóa/ chói hình chụp
                  </MText>
                </View>
                <Image
                  source={require('../../assets/tts/Frame1000011947.png')}
                  style={{
                    width: '100%',
                    height: 80,
                    resizeMode: 'contain',
                    marginTop: 10,
                  }}
                />
              </View>

              <View
                style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  margin: 16,
                }}
              >
                <TouchableOpacity
                  onPress={() => {
                    setType('passport');
                    setShowModal(false);
                    save(OCR_V1, true);
                  }}
                  style={{
                    flex: 1,
                    borderWidth: 1,
                    borderColor: '#EF592E',
                    height: 40,
                    alignItems: 'center',
                    justifyContent: 'center',
                    borderRadius: 40,
                    // marginRight: 16,
                  }}
                >
                  <MText
                    style={{
                      color: '#EF592E',
                      fontSize: 16,
                    }}
                  >
                    Chụp 2 mặt
                  </MText>
                </TouchableOpacity>
                {/* <MButton
                  style={{
                    flex: 1,
                  }}
                  onPress={() => {
                    setType('nfc');
                    setShowModal(false);
                    save(OCR_V1, true);
                  }}
                >
                  <LinearGradient
                    start={{ x: 1, y: 0 }}
                    end={{ x: 0, y: 1 }}
                    style={{
                      height: 40,
                      marginVertical: 16,
                      borderRadius: 30,
                      alignItems: 'center',
                      justifyContent: 'center',
                    }}
                    colors={['#FF7A00', '#EF4123']}
                  >
                    <MText
                      style={{
                        fontSize: 16,
                        color: 'white',
                      }}
                    >
                      NFC
                    </MText>
                  </LinearGradient>
                </MButton> */}
              </View>
              <View style={{ height: 24 }}></View>
            </View>
          </View>
        </LinearGradient>
      </Modal>

      <Loading isLoading={isLoading} />
    </View>
  );
});
const $row: ViewStyle = {
  flexDirection: 'row',
  alignItems: 'center',
  marginTop: 5,
};
const $txt: TextStyle = {
  fontSize: 12,
  marginLeft: 5,
};
const $bg: ViewStyle = {
  backgroundColor: 'white',
  borderTopRightRadius: 26,
  borderTopLeftRadius: 26,
};

const $step: ImageStyle = {
  height: 40,
  width: '100%',
  resizeMode: 'contain',
  marginTop: 10,
  marginBottom: 10,
};

const $paddingV: ViewStyle = {
  paddingTop: 16,
};

const $title: TextStyle = {
  fontSize: 16,
  color: 'white',
  fontWeight: 'bold',
  textAlign: 'center',
};

const $title2: TextStyle = {
  fontSize: 16,
  color: '#333333',
  fontWeight: 'bold',
  textAlign: 'center',
};

const $description: TextStyle = {
  fontSize: 12,
  color: 'white',
  textAlign: 'center',
};

const $flex: ViewStyle = {
  flex: 1,
};

const $modal: ViewStyle = {
  justifyContent: 'flex-end',
  margin: 0,
};

const $container: ViewStyle = {
  borderTopRightRadius: 26,
  borderTopLeftRadius: 26,
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  camera: {
    flex: 1,
  },
  buttonContainer: {
    flex: 0,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
    position: 'absolute',
    left: 0,
    right: 0,
    zIndex: 1000,
  },
  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: 'black',
    width: '100%',
  },
  overlayCenter: {
    flexDirection: 'row',
  },
  overlayLeft: {
    flex: 1,
    backgroundColor: 'black',
  },
  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: 'black',
  },
  overlayBottom: {
    flex: 1,
    backgroundColor: 'black',
    width: '100%',
  },
  mrzContainer: {
    padding: 10,
  },
  mrzText: {
    fontSize: 16,
  },
});
