//@ts-nocheck
import React, { useState, useEffect, useRef } from 'react';
import {
  ActivityIndicator,
  Alert,
  Dimensions,
  Modal,
  Platform,
  SafeAreaView,
  TouchableOpacity,
  View,
} from 'react-native';
import { CommonActions, useNavigation } from '@react-navigation/native';
import { observer } from 'mobx-react-lite';
import { commonStyles } from '../CommonStyles';
import MButton from '../../components/MButton';
import { color } from '../../theme';
import {
  request,
  PERMISSIONS,
  RESULTS,
  openSettings,
} from 'react-native-permissions';
import {
  Camera as VisionCamera,
  useCameraDevice,
} from 'react-native-vision-camera';
import { IconBackFill, IconEkyc } from '../../assets/icons';
import { myLog } from '../../utils/log';
import { MText } from '../../components/MText';
import livenessStore from './LivenessStore';
import RNFS, { CachesDirectoryPath } from 'react-native-fs';
import { ScreenNames } from '../../navigation';
import selfieStore from '../selfie/SelfieStore';
import Slack from 'react-native-slack-webhook';
import Loading from '../../components/Loading';
import { Api } from '../../services/api';
import { createThumbnail } from 'react-native-create-thumbnail';

const webHookURL =
  'https://hooks.slack.com/services/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';

export const LiveNess = observer(function LiveNess(props: any) {
  const navigation = useNavigation();
  const [isLoading, setIsLoading] = useState(false);
  const [ekycSuccess, setEkycSuccess] = useState(false);
  const [recording, setRecording] = useState(false);
  const [hintAction, setHintAction] = useState(
    'Vui lòng bấm bắt đầu và thực hiện\ncác hành động theo yêu cầu'
  );

  const [passPermission, setPassPermission] = useState(false);
  const [flash, setFlash] = useState(false);
  const [front, setFront] = useState(true);
  const myCamera = useRef(null);
  const device = useCameraDevice(front ? 'front' : 'back');
  const loan = props.route.params?.loan;
  const actions = [
    'Ngẩng mặt lên trong 1 giây',
    'Hạ mặt xuống trong 1 giây',
    'Quay mặt sang trái trong 1 giây',
    'Quay mặt sang phải trong 1 giây',
    'Nghiêng mặt sang trái trong 1 giây',
    'Nghiêng mặt sang phải trong 1 giây',
    'Há miệng trong 1 giây',
  ];

  const uploadLiveness = async (template) => {
    try {
      // const listImage = [];
      // const imgSelfie = await RNFS.readFile(selfieStore.photo, 'base64');
      // for (let i = 1; i <= 20; i++) {
      //   const file = 'file://' + template + `_img_${('000' + i).slice(-4)}.jpg`;
      //   const imgBase64 = await RNFS.readFile(file, 'base64');
      //   listImage.push(imgBase64);
      // }

      await livenessStore.uploadLiveness(
        {
          loanBriefId: loan.id,
          files: template,
          selfie: imgSelfie,
        },
        () => {
          setEkycSuccess(true);
          setIsLoading(false);
          try {
            new Slack(webHookURL).post(
              JSON.stringify({
                loanID: loan?.id,
                eKYC: 'Success',
              }),
              '#timacare'
            );
          } catch (e) {}
          // RNFS.unlink(livenessStore.videoFile);
          // for (let i = 1; i <= 20; i++) {
          //   const file =
          //     'file://' + template + `_img_${('000' + i).slice(-4)}.jpg`;
          //   RNFS.unlink(file);
          // }
        },
        (errorMessage) => {
          try {
            new Slack(webHookURL).post(
              JSON.stringify({
                loanID: loan?.id,
                eKYC: 'Fail',
              }),
              '#timacare'
            );
          } catch (e) {}
          setIsLoading(false);
          Alert.alert('Thông báo', errorMessage, [
            {
              text: 'Đồng ý',
              onPress: () => {
                setPassPermission(false);
                setTimeout(() => {
                  setPassPermission(true);
                }, 100);
              },
            },
          ]);
        }
      );
    } catch (e) {
      myLog(e);
      setIsLoading(false);
    }
  };

  const captureFromVideo = async (videoFile) => {
    if (!livenessStore.cancel) {
      setIsLoading(true);
      // const time = new Date().getTime();
      // const template = CachesDirectoryPath + '/' + time;
      // const output = template + '_img_%04d.jpg';
      // FFmpegKit.execute(`-i ${uri} -r 2 ${output}`)
      //   .then(async (result) => {
      //     const returnCode = await result.getReturnCode();
      //     if (ReturnCode.isSuccess(returnCode)) {
      //       uploadLiveness(template);
      //     } else {
      //       setIsLoading(false);
      //       Alert.alert(
      //         'Thông báo',
      //         'Quá trình xử lý hình ảnh bị lỗi. Vui lòng thử lại.',
      //         [{ text: 'Đồng ý' }]
      //       );
      //     }
      //   })
      //   .catch((err) => {
      //     console.log(err);
      //     setIsLoading(false);
      //   });
      const thumbnails: string[] = [];
      const numFrames = 20;
      for (let i = 0; i < numFrames; i++) {
        const time = i * 500;
        const result = await createThumbnail({
          url: videoFile,
          timeStamp: time,
        });
        console.log(`Thumbnail at ${time}ms: `, result.path);
        const base64 = await RNFS.readFile(result.path, 'base64');
        thumbnails.push(base64);
      }
      uploadLiveness(thumbnails);
    }
  };

  const startLiveNess = () => {
    livenessStore.ready = true;
    livenessStore.counter = 0;
    livenessStore.interval = setInterval(() => {
      livenessStore.counter += 1;
      if (livenessStore.counter < 20) {
        if ((livenessStore.counter + 1) % 4 === 0) {
          setHintAction(actions[Math.round(Math.random() * actions.length)]);
          livenessStore.hintAction =
            actions[Math.round(Math.random() * actions.length)];
        }
      } else {
        setHintAction('');
        livenessStore.hintAction = '';
        clearInterval(livenessStore.interval);
      }
      myLog(livenessStore.counter);
    }, 1000);
  };

  const handlerFace = (event) => {
    myLog(event);
    if (event.type === 'face') {
      livenessStore.isFace = true;
      livenessStore.lastFace = new Date().getTime();
    }
  };

  const recordVideo = async () => {
    if (myCamera.current) {
      setRecording(true);
      startLiveNess();
      const data = await new Promise((resolve, reject) => {
        let stopped = false;
        const timeout = setTimeout(() => {
          if (!stopped) {
            stopped = true;
            myCamera.current?.stopRecording();
          }
        }, 13000);
        myCamera.current.startRecording({
          videoCodec: Platform.OS === 'ios' ? 'h264' : undefined,
          onRecordingFinished: (video) => {
            clearTimeout(timeout);
            resolve(video);
          },
          onRecordingError: (error) => {
            clearTimeout(timeout);
            reject(error);
          },
        });
      });
      if (data.path) {
        setRecording(false);
        const newPath =
          CachesDirectoryPath + '/' + new Date().getTime() + '.mp4';
        await RNFS.copyFile(data.path, newPath).then(() => {
          console.log('Copied to:', newPath);
        });
        captureFromVideo(
          Platform.OS === 'android'
            ? 'file://' + data?.path
            : 'file://' + newPath
        );
      } else {
        Alert.alert(
          'Thông báo',
          'Quá trình xác thực thất bại. Vui lòng bắt đầu lại.'
        );
      }
    }
  };

  const requestPermissions = () => {
    request(
      Platform.OS === 'ios'
        ? PERMISSIONS.IOS.CAMERA
        : PERMISSIONS.ANDROID.CAMERA
    ).then((result) => {
      switch (result) {
        case RESULTS.UNAVAILABLE:
          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(() => {
    livenessStore.cancel = false;
    requestPermissions();
    livenessStore.intervalFace = setInterval(() => {
      if (new Date().getTime() - livenessStore.lastFace > 1000) {
        livenessStore.isFace = false;
      }
    }, 1000);
    return () => {
      livenessStore.cancel = true;
      clearInterval(livenessStore.interval);
      clearInterval(livenessStore.intervalFace);
      setIsLoading(false);
    };
  }, []);

  return (
    <View
      style={[commonStyles.fill, { backgroundColor: 'black' }]}
      pointerEvents={'box-none'}
    >
      {
        <View
          style={[
            commonStyles.alignCenter,
            commonStyles.fill,
            commonStyles.justifyCenter,
            {
              position: 'absolute',
              width: Dimensions.get('window').width,
              height: Dimensions.get('window').height,
            },
          ]}
        >
          {passPermission && device ? (
            <VisionCamera
              ref={myCamera}
              style={{
                width: Dimensions.get('window').width,
                height: (Dimensions.get('window').width * 4) / 3,
              }}
              device={device}
              isActive={true}
              video={true}
              audio={false}
              torch={flash && device.hasTorch ? 'on' : 'off'}
            />
          ) : (
            <ActivityIndicator />
          )}
        </View>
      }
      <SafeAreaView
        style={[
          commonStyles.fill,
          { position: 'absolute', width: '100%', height: '100%' },
        ]}
      >
        <View style={[commonStyles.row, commonStyles.alignCenter]}>
          <MButton
            onPress={() => {
              navigation.goBack();
            }}
            style={[
              commonStyles.alignCenter,
              commonStyles.justifyCenter,
              { width: 48, height: 48 },
            ]}
          >
            <IconBackFill width="24" height="24" fill="white" />
          </MButton>

          <MText
            style={[
              commonStyles.textNormalBold,
              commonStyles.fill,
              {
                fontSize: 18,
                textAlign: 'center',
                color: color.textHint,
                paddingRight: 48,
              },
            ]}
          >
            Liveness
          </MText>
        </View>
        <View
          style={{
            flex: 0,
            justifyContent: 'center',
            position: 'absolute',
            bottom: 48,
            width: '100%',
          }}
        >
          {!recording && (
            <MText
              style={[
                commonStyles.textNormal,
                {
                  color: 'white',
                  textAlign: 'center',
                  backgroundColor: '#00000099',
                  paddingVertical: 12,
                },
              ]}
            >
              Vui lòng hướng khuôn mặt vào máy ảnh
            </MText>
          )}
          <MText
            style={{
              lineHeight: 22,
              fontSize: 16,
              textAlign: 'center',
              backgroundColor: '#00000099',
              color: 'white',
              fontWeight: 'bold',
              paddingVertical: 12,
              paddingHorizontal: 16,
            }}
          >
            {hintAction}
          </MText>
          {!recording ? (
            <MButton
              onPress={() => recordVideo()}
              style={[
                commonStyles.alignCenter,
                commonStyles.justifyCenter,
                {
                  flex: 0,
                  borderRadius: 16,
                  backgroundColor: '#00000099',
                  borderWidth: 2,
                  borderColor: color.primary,
                  paddingHorizontal: 20,
                  alignSelf: 'center',
                  marginBottom: 40,
                },
              ]}
            >
              <MText
                style={{
                  color: 'white',
                  fontWeight: 'bold',
                  paddingVertical: 12,
                  paddingHorizontal: 16,
                }}
              >
                Bắt đầu
              </MText>
            </MButton>
          ) : (
            <View />
          )}
        </View>
      </SafeAreaView>
      <Loading isLoading={isLoading} />

      <Modal visible={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 },
            ]}
          >
            <IconEkyc />
            <MText
              style={[
                commonStyles.textNormalBold,
                { marginTop: 16, textAlign: 'center' },
              ]}
            >
              Chúc mừng bạn đã thực hiện xác thực{'\n'}khách hàng thành công.
            </MText>
            <TouchableOpacity
              style={{
                marginTop: 16,
                backgroundColor: color.primary,
                height: 40,
                alignItems: 'center',
                borderRadius: 30,
                width: 150,
                justifyContent: 'center',
              }}
              onPress={() => {
                setEkycSuccess(false);
                if (loan?.typeLoan === 4) {
                  navigation.push(ScreenNames.QuickSubmit, { 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>
  );
});
