// @ts-nocheck
import React, { useEffect, useRef, useState } from 'react';
import { CommonActions, useNavigation } from '@react-navigation/native';
import { Observer, observer } from 'mobx-react-lite';
import {
  ActivityIndicator,
  Alert,
  Dimensions,
  Image,
  Modal,
  Platform,
  StyleSheet,
  TouchableOpacity,
  View,
} from 'react-native';
import CircularProgress from 'react-native-circular-progress-indicator';
import RNFS from 'react-native-fs';
import {
  PERMISSIONS,
  RESULTS,
  openSettings,
  request,
} from 'react-native-permissions';
import { IconBackWhite, IconEkyc } from '../../assets/icons';
import { MText } from '../../components/MText';
import {
  Camera as VisionCamera,
  useCameraDevice,
} from 'react-native-vision-camera';
import livenessStore from '../liveness/LivenessStore';
import { commonStyles } from '../CommonStyles';
import { ScreenNames } from '../../navigation';
import { color } from '../../theme';
import { createThumbnail } from 'react-native-create-thumbnail';
import appStore from '../../AppStore';
import { logEvent, logEventFb } from '../../utils';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

const { width: windowWidth } = Dimensions.get('window');

const PREVIEW_SIZE = 320;
const PREVIEW_RECT = {
  minX: (windowWidth - PREVIEW_SIZE) / 2,
  minY: 240,
  width: PREVIEW_SIZE,
  height: PREVIEW_SIZE,
};
export const LivenessV2 = observer(function LivenessV2(props: any) {
  const loan = props.route.params?.loan;
  const insets = useSafeAreaInsets();
  const navigation = useNavigation();
  const cameraRef = useRef<any>(null);
  const interval = useRef<any>(null);
  const [passPermission, setPassPermission] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const device = useCameraDevice('front');

  const renderHint = (key: string) => {
    switch (key) {
      case 'blink':
        return 'Nhắm mắt trong 3 giây';
      case 'right':
        return 'Quay sang phải 3 giây';
      case 'left':
        return 'Quay sang trái 3 giây';
      case 'up':
        return 'Nhìn lên trên 3 giây';
      case 'down':
        return 'Nhìn xuống dưới 3 giây';
      case 'mouth':
        return 'Há miệng trong 3 giây';
      default:
        return '';
    }
  };
  const renderImg = (key: string) => {
    switch (key) {
      case 'blink':
        return (
          <Image
            source={require('../../assets/img/blink.png')}
            style={{
              height: 24,
              width: 50,
              resizeMode: 'contain',
              marginTop: 40,
            }}
          />
        );
      case 'right':
        return (
          <Image
            source={require('../../assets/img/right.png')}
            style={{
              height: 24,
              width: 50,
              resizeMode: 'contain',
              marginTop: 40,
            }}
          />
        );
      case 'left':
        return (
          <Image
            source={require('../../assets/img/left.png')}
            style={{
              height: 24,
              width: 50,
              resizeMode: 'contain',
              marginTop: 40,
            }}
          />
        );
      case 'up':
        return (
          <Image
            source={require('../../assets/img/up.png')}
            style={{
              height: 24,
              width: 50,
              resizeMode: 'contain',
              marginTop: 40,
            }}
          />
        );
      case 'down':
        return (
          <Image
            source={require('../../assets/img/down.png')}
            style={{
              height: 24,
              width: 50,
              resizeMode: 'contain',
              marginTop: 40,
            }}
          />
        );
      case 'mouth':
        return (
          <Image
            source={require('../../assets/img/mouth.png')}
            style={{
              height: 24,
              width: 50,
              resizeMode: 'contain',
              marginTop: 40,
            }}
          />
        );
      default:
        return <></>;
    }
  };

  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.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;
      }
    });
  };

  let second = 3;

  const start = () => {
    requestPermissions();
    livenessStore.getListAction(() => {
      if (passPermission) {
        interval.current = setInterval(() => {
          second--;
          if (second === 0) {
            clearInterval(interval.current);
            startLiveness();
          }
        }, 1000);
      }
    });
  };

  const extractFramesFromVideo = async (videoPath: string) => {
    try {
      const thumbnails: string[] = [];
      const numFrames = 3;
      for (let i = 0; i < numFrames; i++) {
        const time = i * 300;
        const result = await createThumbnail({
          url: videoPath,
          timeStamp: time,
        });
        console.log(`Thumbnail at ${time}ms: `, result.path);
        const base64 = await RNFS.readFile(result.path, 'base64');
        thumbnails.push(base64);
      }
      return thumbnails;
    } catch (error) {
      setIsLoading(false);
      console.log(error, 'LỖI');
      Alert.alert('Thông báo', 'Quá trình xử lý hình ảnh thất bại', [
        {
          text: 'Thử lại',
          onPress: () => {
            startLiveness();
          },
        },
      ]);
    }
  };

  useEffect(() => {
    start();
  }, [passPermission]);

  const uploadLiveness = async (template: any) => {
    setIsLoading(true);
    try {
      if (
        loan?.typeLoan === 5 ||
        loan?.typeLoan === 6 ||
        loan?.typeLoan === 4
      ) {
        await livenessStore.verifyLiveness2(
          loan?.id,
          template,
          () => {
            setTimeout(() => {
              startLiveness();
            }, 2000);
            setIsLoading(false);
          },
          () => {
            setTimeout(() => {
              startLiveness();
            }, 2000);
            setIsLoading(false);
          }
        );
      } else {
        await livenessStore.verifyLiveness(
          loan?.id,
          template,
          () => {
            setTimeout(() => {
              startLiveness();
            }, 2000);
            setIsLoading(false);
          },
          () => {
            setTimeout(() => {
              startLiveness();
            }, 2000);
            setIsLoading(false);
          }
        );
      }
    } catch (error) {
      setIsLoading(false);
      console.log(error);
    }
  };

  const startLiveness = async () => {
    livenessStore.ekycSuccess = false;
    if (livenessStore.listAction.length === 0) {
      livenessStore.ekycSuccess = true;
      livenessStore.saveLiveness(loan.id);
      return;
    }
    if (cameraRef.current) {
      const data = await new Promise((resolve, reject) => {
        let stopped = false;
        const timeout = setTimeout(() => {
          if (!stopped) {
            stopped = true;
            cameraRef.current?.stopRecording();
          }
        }, 3500);
        cameraRef.current.startRecording({
          fileType: 'mp4',
          videoCodec: Platform.OS === 'ios' ? 'h264' : undefined,
          onRecordingFinished: (video) => {
            clearTimeout(timeout);
            resolve(video);
          },
          onRecordingError: (error) => {
            clearTimeout(timeout);
            reject(error);
          },
        });
      });
      if (data.path) {
        setIsLoading(true);
        const thump = await extractFramesFromVideo(
          Platform.OS === 'ios' ? data.path : 'file://' + data.path
        );
        if (thump.length > 0) {
          uploadLiveness(thump);
        }
      } else {
        Alert.alert('Thông báo', 'Quá trình xác thực thất bại', [
          {
            text: 'Thử lại',
            onPress: () => {
              startLiveness();
            },
          },
        ]);
      }
    }
  };

  useEffect(() => {
    const trackingEvent = async () => {
      await logEvent('ekyc_started', {
        event: 'ekyc_started',
        createdAt: new Date(),
        deviceId: appStore.deviceId,
        loanId: String(loan?.id),
        utmSource: loan?.utmSource,
      });
      logEventFb('ekyc_started');
    };
    trackingEvent();
  }, []);

  return (
    <View style={styles.container}>
      <TouchableOpacity
        onPress={() => {
          navigation.goBack();
        }}
        style={{
          position: 'absolute',
          left: 16,
          top: insets.top + 16,
          width: 40,
          height: 40,
          zIndex: 1000,
        }}
      >
        <IconBackWhite />
      </TouchableOpacity>
      <View style={[{ top: insets.top + 16 }, styles.topOverlay]}>
        <MText
          style={{
            color: 'white',
            fontWeight: '600',
            fontSize: 16,
          }}
        >
          Xác thực khuôn mặt
        </MText>
        <Observer>
          {() => (
            <>
              {isLoading ? (
                <View style={{ marginTop: 24 }}>
                  <MText
                    style={{
                      textAlign: 'center',
                      fontSize: 16,
                      color: 'white',
                    }}
                  >
                    Đang xác thực
                  </MText>
                  <ActivityIndicator
                    size={'large'}
                    color={'white'}
                    style={{ marginTop: 8 }}
                  />
                </View>
              ) : (
                <></>
              )}
            </>
          )}
        </Observer>
      </View>

      <View style={styles.preview}>
        {passPermission && device ? (
          <VisionCamera
            ref={cameraRef}
            style={StyleSheet.absoluteFill}
            device={device}
            isActive={true}
            video={true}
            audio={false}
          />
        ) : null}
        <View
          style={{
            height: '100%',
            width: '100%',
            justifyContent: 'center',
            alignItems: 'center',
          }}
        >
          {renderImg(livenessStore.hintAction)}
          <MText
            style={{
              color: 'white',
              fontSize: 16,
              marginTop: 8,
              fontWeight: '400',
            }}
          >
            {renderHint(livenessStore.hintAction)}
          </MText>
        </View>
      </View>

      <View style={styles.circularProgress}>
        <CircularProgress
          value={
            livenessStore.listAction.length === 3
              ? 0
              : livenessStore.listAction.length === 2
              ? 100 / 3
              : livenessStore.listAction.length === 1
              ? (2 / 3) * 100
              : 100
          }
          radius={PREVIEW_SIZE / 2}
          inActiveStrokeOpacity={0.5}
          activeStrokeWidth={13}
          inActiveStrokeWidth={13}
          showProgressValue={false}
          activeStrokeColor="#F05123"
          inActiveStrokeColor="#F05123"
          duration={800}
        />
      </View>
      <Observer>
        {() => (
          <View style={styles.bottomOverlay}>
            <MText style={styles.instructionText}>
              Vui lòng điều chỉnh khuôn mặt nằm gọn trong vòng tròn ở trên
            </MText>
          </View>
        )}
      </Observer>

      <Modal
        visible={livenessStore.ekycSuccess}
        animationType={'fade'}
        transparent
      >
        <View
          style={[
            commonStyles.alignCenter,
            commonStyles.justifyCenter,
            { backgroundColor: 'transparent', height: '100%' },
          ]}
        >
          <View
            style={[
              commonStyles.alignCenter,
              commonStyles.justifyCenter,
              {
                backgroundColor: 'white',
                borderRadius: 8,
                padding: 16,
                marginHorizontal: 16,
              },
            ]}
          >
            <IconEkyc />
            <MText
              style={[
                commonStyles.textNormalBold,
                { marginTop: 16, textAlign: 'center' },
              ]}
            >
              Chúc mừng bạn đã thực hiện xác thực khách hàng{'\n'}thành công.
            </MText>
            <TouchableOpacity
              style={{
                marginTop: 16,
                backgroundColor: color.primary,
                height: 40,
                alignItems: 'center',
                borderRadius: 30,
                width: 150,
                justifyContent: 'center',
              }}
              onPress={async () => {
                await logEvent('ekyc_completed', {
                  event: 'ekyc_completed',
                  createdAt: new Date(),
                  deviceId: appStore.deviceId,
                  loanId: String(loan?.id),
                  utmSource: loan?.utmSource,
                });
                logEventFb('ekyc_completed');
                livenessStore.ekycSuccess = false;
                if (loan?.typeLoan === 5 || loan?.typeLoan === 6) {
                  navigation.dispatch(
                    CommonActions.reset({
                      index: 1,
                      routes: [
                        { name: ScreenNames.TTSSignLoan, params: { loan } },
                      ],
                    })
                  );
                } else {
                  navigation.dispatch(
                    CommonActions.reset({
                      index: 1,
                      routes: [{ name: ScreenNames.Main }],
                    })
                  );
                }
              }}
            >
              <MText style={[commonStyles.textNormalBold, { color: 'white' }]}>
                Đồng ý
              </MText>
            </TouchableOpacity>
          </View>
        </View>
      </Modal>
    </View>
  );
});

const styles = StyleSheet.create({
  instructionText: {
    color: 'white',
    fontSize: 12,
    textAlign: 'center',
    paddingHorizontal: 50,
    marginTop: 16,
  },
  bottomOverlay: {
    marginTop: 24,
  },
  maskedView: {
    flex: 1,
    flexDirection: 'row',
    height: '100%',
  },
  maskWrapper: {
    backgroundColor: 'transparent',
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  mask: {
    borderRadius: PREVIEW_SIZE / 2,
    height: PREVIEW_SIZE - 10,
    width: PREVIEW_SIZE - 10,
    marginTop: PREVIEW_RECT.minY,
    alignSelf: 'center',
  },
  container: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: '#333333',
  },
  topOverlay: {
    position: 'absolute',

    right: 0,
    left: 0,
    justifyContent: 'center',
    alignItems: 'center',
  },
  captureFrame: {
    height: Dimensions.get('window').width - 50,
    marginHorizontal: 16,
    marginTop: '50%',
    borderRadius: 50,
  },
  preview: {
    width: PREVIEW_SIZE - 29,
    height: PREVIEW_SIZE - 28,
    marginTop: PREVIEW_RECT.minY + 14,
    marginLeft: PREVIEW_RECT.minX + 14,
    borderRadius: PREVIEW_SIZE / 2,
    overflow: 'hidden',
  },
  circularProgress: {
    width: PREVIEW_SIZE,
    height: PREVIEW_SIZE,
    marginTop: PREVIEW_RECT.minY,
    marginLeft: PREVIEW_RECT.minX,
    zIndex: 100,
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
  },
});
