// @ts-nocheck
import React, { useEffect, useRef, useState } from 'react';
import { Alert, Dimensions, Platform, View } from 'react-native';
import { useNavigation, useIsFocused } from '@react-navigation/native';
import {
  request,
  PERMISSIONS,
  RESULTS,
  openSettings,
} from 'react-native-permissions';
import { MText } from '../../components/MText';
import MButton from '../../components/MButton';
import { commonStyles } from '../CommonStyles';
import { IconBackWhite, TakePhotoSvg } from '../../assets/icons';
import Loading from '../../components/Loading';
import { Api } from '../../services/api';
import { ScreenNames } from '../../navigation';
import appStore from '../../AppStore';
import { logEvent, logEventFb } from '../../utils';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import {
  Camera,
  useCameraDevice,
  useCameraFormat,
} from 'react-native-vision-camera';

export default function TTSSelfie(props: any) {
  const insets = useSafeAreaInsets();
  const isFocused = useIsFocused();
  const [shouldRenderCamera, setShouldRenderCamera] = useState(false);
  const navigation = useNavigation();
  const [taking, setTaking] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [passPermission, setPassPermission] = useState(false);
  const device = useCameraDevice('front');
  const myCamera = useRef(null);

  const format = useCameraFormat(device, [
    { photoResolution: { width: 1280, height: 1280 } },
  ]);

  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();
    const trackEvent = async () => {
      await logEvent('cccd_completed', {
        event: 'cccd_completed',
        createdAt: new Date(),
        deviceId: appStore.deviceId,
        loanId: String(props?.route?.params?.loan?.id),
        utmSource: props?.route?.params?.loan?.utmSource,
      });
      logEventFb('cccd_completed');
    };
    trackEvent();
  }, []);

  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 takePhoto = async () => {
    if (myCamera.current == null || taking) return;
    setTaking(true);
    const data = await myCamera.current.takePhoto({
      qualityPrioritization: 'speed',
    });
    setTaking(false);
    if (data) {
      setIsLoading(true);
      const formData = new FormData();
      formData.append('LoanBriefId', props?.route?.params?.loan?.id);
      formData.append('TypeDocumentId', 125); // Anh selfie
      formData.append('image', {
        uri: 'file://' + data.path,
        type: 'image/jpg',
        name: 'selfie.jpg',
      });
      const response = await Api.getInstance().uploadImageAutoDE(formData);
      setIsLoading(false);
      if (response.kind === 'ok') {
        if (response.data?.meta.errorCode === 200) {
          if (
            props?.route?.params?.loan?.typeLoan === 6 ||
            props?.route?.params?.loan?.typeLoan === 4
          ) {
            navigation.push(ScreenNames.TopupLoanInfo, {
              loan: props?.route?.params?.loan,
            });
          } else if (props?.route?.params?.loan?.typeLoan === 8) {
            navigation.push(ScreenNames.InfoLoanMotobike, {
              loan: props?.route?.params?.loan,
            });
          } else {
            navigation.push(ScreenNames.ReviewInformation, {
              loan: props?.route?.params?.loan,
            });
          }
        } 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');
      }
    }
  };

  return (
    <View
      style={{ flex: 1, backgroundColor: 'black' }}
      pointerEvents={'box-none'}
    >
      {passPermission && shouldRenderCamera ? (
        <View
          style={[
            commonStyles.fill,
            {
              width: Dimensions.get('window').width,
              height: Dimensions.get('window').height,
            },
          ]}
        >
          <View
            style={{
              marginVertical: 24,
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'center',
              marginTop: insets.top + 16,
            }}
          >
            <MButton
              onPress={() => {
                navigation.goBack();
              }}
              style={{
                position: 'absolute',
                left: 16,
              }}
            >
              <IconBackWhite />
            </MButton>
            <MText
              style={{
                color: 'white',
                fontWeight: 'bold',
                textAlgin: 'center',
              }}
            >
              Xác thực khuôn mặt
            </MText>
          </View>

          <Camera
            style={{
              width: Dimensions.get('window').width,
              height: (Dimensions.get('window').width * 4) / 3.1,
            }}
            ref={myCamera}
            device={device}
            isActive={true}
            photo={true}
            format={format}
          />

          <View
            style={{
              position: 'absolute',
              bottom: 20,
              left: 0,
              right: 0,
            }}
          >
            {!taking && (
              <>
                <MText
                  style={{
                    color: 'white',
                    textAlign: 'center',
                    fontSize: 14,
                    paddingHorizontal: 24,
                  }}
                >
                  Xin vui lòng nhìn thẳng, khuôn mặt ở trong khung hình, ánh
                  sáng đủ rõ nét khuôn mặt
                </MText>
                <View
                  style={{
                    alignItems: 'center',
                    marginVertical: 24,
                  }}
                >
                  <MButton
                    onPress={() => {
                      takePhoto();
                    }}
                  >
                    <TakePhotoSvg />
                  </MButton>
                </View>
              </>
            )}
          </View>
        </View>
      ) : null}

      <Loading isLoading={isLoading} />
    </View>
  );
}
