// @ts-nocheck
import React, { useEffect, useRef, useState } from 'react';
import {
  ActivityIndicator,
  Alert,
  Dimensions,
  Platform,
  StyleSheet,
  TouchableOpacity,
  View,
} from 'react-native';
import {
  Camera as VisionCamera,
  useCameraDevice,
  useCameraFormat,
} from 'react-native-vision-camera';
import { IconBackWhite, TakePhotoSvg } from '../../assets/icons';
import { MText } from '../../components/MText';
import { useNavigation, useIsFocused } from '@react-navigation/native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { commonStyles } from '../CommonStyles';
import {
  request,
  PERMISSIONS,
  RESULTS,
  openSettings,
} from 'react-native-permissions';

export default function CCCDCameraScreen(props) {
  const insets = useSafeAreaInsets();
  const navigation = useNavigation();
  const isFocused = useIsFocused();
  const myCamera = useRef(null);
  const [passPermission, setPassPermission] = useState(false);
  const [shouldRenderCamera, setShouldRenderCamera] = useState(false);
  const device = useCameraDevice('back');
  const format = useCameraFormat(device, [
    { photoResolution: { width: 1280, height: 720 } },
  ]);

  const takePicture = async () => {
    if (myCamera.current == null) return;
    try {
      const data = await myCamera.current.takePhoto({
        qualityPrioritization: 'quality',
      });
      navigation.goBack();
      if (props.route?.params?.callback) {
        props.route.params.callback('file://' + data.path);
      }
    } catch (err) {
      console.error(err);
    }
  };

  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();
  }, []);

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

  if (!passPermission && !shouldRenderCamera) {
    return (
      <View style={commonStyles.fill}>
        <ActivityIndicator size="large" color="#0000ff" />
      </View>
    );
  }

  return (
    <View
      style={{ flex: 1, 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,
          },
        ]}
      >
        {device ? (
          <View style={$cameraFrame}>
            <VisionCamera
              ref={myCamera}
              style={StyleSheet.absoluteFill}
              device={device}
              isActive={true}
              photo={true}
              format={format}
            />
          </View>
        ) : (
          <ActivityIndicator />
        )}
      </View>

      <View style={[$back, { top: insets.top + 16 }]}>
        <TouchableOpacity
          onPress={() => {
            navigation.goBack();
          }}
          style={{
            position: 'absolute',
            left: 0,
            width: 48,
            height: 48,
            zIndex: 1000,
            alignItems: 'center',
          }}
        >
          <IconBackWhite />
        </TouchableOpacity>
        <MText
          style={{
            textAlign: 'center',
            zIndex: 10,
            color: '#FFFFFF',
            fontSize: 16,
          }}
        >
          {props?.route?.params?.front
            ? 'Chụp CMND/ CCCD mặt trước'
            : 'Chụp CMND/ CCCD mặt sau'}
        </MText>
      </View>
      <View
        style={{
          position: 'absolute',
          bottom: insets.bottom,
          alignSelf: 'center',
          flexDirection: 'column',
          alignItems: 'center',
        }}
      >
        <MText
          style={{
            color: '#fff',
            marginBottom: 16,
            textAlign: 'center',
            paddingHorizontal: 24,
          }}
        >
          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}>
          <TakePhotoSvg />
        </TouchableOpacity>
      </View>
    </View>
  );
}

const overlayColor = 'rgba(22, 22, 22, 0.7)';
const $back: ViewStyle = {
  position: 'absolute',
  left: 0,
  right: 0,
};

const $cameraFrame: ViewStyle = {
  width: Dimensions.get('window').width,
  height: 260,
  overflow: 'hidden',
  backgroundColor: 'black',
};

const $overlay: ViewStyle = {
  ...StyleSheet.absoluteFillObject,
  justifyContent: 'center',
  alignItems: 'center',
};

const $container: ViewStyle = {
  flex: 1,
  backgroundColor: '#000',
};

const $row: ViewStyle = {
  flexDirection: 'row',
  alignItems: 'center',
};

const $darkOverlayTop: ViewStyle = {
  width: '100%',
  backgroundColor: overlayColor,
};

const $darkOverlayBottom: ViewStyle = {
  width: '100%',
  backgroundColor: overlayColor,
};
const $darkOverlaySide: ViewStyle = {
  backgroundColor: overlayColor,
};
const $frameBorder: ViewStyle = {
  // borderColor: '#FDFDFD',
  // borderWidth: 2,
};
