//@ts-nocheck
import React, { useState, Fragment, useEffect, useRef } from 'react';
import {
  ActivityIndicator,
  Alert,
  Dimensions,
  Image,
  ImageStyle,
  Linking,
  Platform,
  SafeAreaView,
  ScrollView,
  TextStyle,
  TouchableOpacity,
  View,
  ViewStyle,
} from 'react-native';
import {
  CommonActions,
  useNavigation,
  useIsFocused,
} 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,
  useCameraFormat,
} from 'react-native-vision-camera';
import {
  CIMBBank,
  IconBackFill,
  IconBackWhite,
  IconFlash,
  IconSwitchCamera,
  IconUnFlash,
  Selfie,
  TakePhotoSvg,
  TimaNormal,
  TimaSmall,
} from '../../assets/icons';
import { Svg, Circle, Defs, ClipPath, Rect } from 'react-native-svg';
import Store from './Store';
import { MText } from '../../components/MText';
import Modal from 'react-native-modal';
import LinearGradient from 'react-native-linear-gradient';
import RNFS from 'react-native-fs';

const cameraStore = new Store();
export const Camera = observer(function Camera(props: any) {
  const navigation = useNavigation();
  const isFocused = useIsFocused();
  const [shouldRenderCamera, setShouldRenderCamera] = useState(false);
  const [passPermission, setPassPermission] = useState(false);
  const [flash, setFlash] = useState(false);
  const [front, setFront] = useState(props.route.params.front);
  const [selfie] = useState(props.route.params.selfie);
  const [taking, setTaking] = useState(false);
  const [showModal, setShowModal] = useState(false);

  const myCamera = useRef(null);
  const device = useCameraDevice(front ? 'front' : 'back');
  const format = useCameraFormat(device, [
    { photoResolution: { width: 1280, height: 720 } },
  ]);

  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);
    //  eslint-disable-next-line
    navigation.goBack();
    if (props.route.params.callback) {
      props.route.params.callback(uri);
    }
    if (props.route.params.base64) {
      const base64 = await RNFS.readFile(data.path, 'base64');
      props.route.params.base64(base64);
    }
  };

  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();
    if (selfie) {
      cameraStore.interval = setInterval(() => {
        if (new Date().getTime() - cameraStore.lastFace > 1000) {
          cameraStore.isFace = false;
        }
      }, 1000);
    }
    return () => {
      clearInterval(cameraStore.interval);
    };
  }, []);

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

  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]);

  return (
    <View
      style={[commonStyles.fill, { backgroundColor: 'black' }]}
      pointerEvents={'box-none'}
    >
      {passPermission && 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: '100%',
              }}
              device={device}
              isActive={true}
              photo={true}
              format={format}
              torch={flash && device.hasTorch ? 'on' : 'off'}
            />
          ) : (
            <ActivityIndicator />
          )}
        </View>
      )}

      <SafeAreaView
        style={[
          commonStyles.fill,
          { position: 'absolute', width: '100%', height: '100%' },
        ]}
      >
        <View
          style={[
            commonStyles.row,
            commonStyles.alignCenter,
            { paddingHorizontal: 16, marginTop: 16 },
          ]}
        >
          <MButton
            //@ts-ignore
            onPress={() => {
              navigation.goBack();
            }}
            style={[{ width: 48, height: 48, zIndex: 1000 }]}
          >
            <IconBackWhite />
          </MButton>
          <View style={{ flex: 1 }} />
        </View>
        <View
          style={{
            flex: 0,
            justifyContent: 'center',
            position: 'absolute',
            bottom: 0,
            width: '100%',
          }}
        >
          {!props.route.params.front && (
            <MText
              style={[
                commonStyles.textNormal,
                {
                  color: 'white',
                  textAlign: 'center',
                  backgroundColor: '#00000099',
                  paddingVertical: 12,
                },
              ]}
            >
              Vui lòng đặt giấy tờ nằm vừa khung hình,{'\n'}
              chụp đủ ánh sáng và rõ nét.
            </MText>
          )}
          {props.route.params.selfie && (
            <MText
              style={[
                commonStyles.textNormal,
                {
                  color: 'white',
                  textAlign: 'center',
                  backgroundColor: '#00000099',
                  paddingVertical: 12,
                },
              ]}
            >
              Xin vui lòng nhìn thẳng, khuôn mặt ở trong{'\n'}khung hình, ánh
              sáng đủ rõ nét khuôn mặt
            </MText>
          )}
          {/* {(Platform.OS === 'ios' ? false : !cameraStore.isFace) && selfie && (
            <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>
          )} */}
          {taking ? (
            <View
              style={[
                commonStyles.alignCenter,
                commonStyles.justifyCenter,
                { width: 64, height: 64, alignSelf: 'center' },
              ]}
            >
              <ActivityIndicator color={'white'} size="large" />
            </View>
          ) : (
            <MButton
              onPress={() => takePhoto()}
              style={[
                commonStyles.alignCenter,
                commonStyles.justifyCenter,
                {
                  margin: 24,
                },
              ]}
            >
              <TakePhotoSvg />
            </MButton>
          )}
        </View>
      </SafeAreaView>
      <Modal isVisible={showModal}>
        <SafeAreaView style={{ backgroundColor: '#FFFFFF', borderRadius: 4 }}>
          <View>
            <MText
              style={[
                {
                  marginTop: 16,
                  color: '#F05123',
                  fontSize: 16,
                  textAlign: 'center',
                  fontWeight: 'bold',
                },
              ]}
              center
            >
              B2: XÁC THỰC KHUÔN MẶT
            </MText>
            <View style={{ alignItems: 'center', marginTop: 16 }}>
              <Selfie />
            </View>
            <MText
              style={{
                color: '#333333',
                textAlign: 'center',
                fontSize: 16,
                fontWeight: '600',
                marginTop: 16,
              }}
            >
              Bạn vui lòng chụp ảnh{'\n'}
              khuôn mặt theo hướng dẫn:
            </MText>
            <View
              style={{
                flexDirection: 'row',
                marginTop: 16,
                alignItems: 'center',
                paddingHorizontal: 16,
              }}
            >
              <TimaNormal width={12} />
              <MText style={{ color: '#333333', marginLeft: 8, fontSize: 12 }}>
                Giữ điện thoại ổn định, thẳng mặt
              </MText>
            </View>
            <View
              style={{
                flexDirection: 'row',
                paddingHorizontal: 16,
                alignItems: 'center',
              }}
            >
              <TimaNormal width={12} />
              <MText style={{ color: '#333333', marginLeft: 8, fontSize: 12 }}>
                Điều chỉnh khuôn mặt nằm gọn trong vòng tròn
              </MText>
            </View>
            <View
              style={{
                flexDirection: 'row',
                paddingHorizontal: 16,
              }}
            >
              <TimaNormal width={12} />
              <MText style={{ color: '#333333', marginLeft: 8, fontSize: 12 }}>
                Thực hiện quay trái, phải theo hướng dẫn để{'\n'} hoàn thành xác
                thực khuôn mặt
              </MText>
            </View>
            <View style={{ marginTop: 24, paddingHorizontal: 50 }}>
              <TouchableOpacity onPress={() => setShowModal(false)}>
                <LinearGradient
                  colors={['#FF7A00', '#EF4123']}
                  style={{
                    alignItems: 'center',
                    borderRadius: 30,
                    alignContent: 'center',
                    paddingVertical: 12,
                  }}
                >
                  <MText
                    style={[commonStyles.textNormalBold, { color: '#ffffff' }]}
                  >
                    Tiếp tục
                  </MText>
                </LinearGradient>
              </TouchableOpacity>
            </View>
            <View
              style={{
                marginBottom: 24,
                marginTop: 8,
                flexDirection: 'row',
                justifyContent: 'center',
              }}
            >
              <MText style={{ fontSize: 12, color: '#333333' }}>
                Cung cấp bởi{' '}
              </MText>
              <CIMBBank />
            </View>
          </View>
        </SafeAreaView>
      </Modal>
    </View>
  );
});
