// @ts-nocheck
import React, { useEffect, useRef, useState } from 'react';
import {
  ActivityIndicator,
  Dimensions,
  Image,
  ImageStyle,
  Platform,
  TextStyle,
  TouchableOpacity,
  View,
  ViewStyle,
  Alert,
} from 'react-native';
import { useNavigation, useIsFocused } from '@react-navigation/native';
import {
  request,
  PERMISSIONS,
  RESULTS,
  openSettings,
} from 'react-native-permissions';
import {
  Camera as VisionCamera,
  useCameraDevice,
  useCameraFormat,
} from 'react-native-vision-camera';
import Modal from 'react-native-modal';
import { MText } from '../../components/MText';
import LinearGradient from 'react-native-linear-gradient';
import { CloseIcon, TakePhotoSvg, TimaSmall } from '../../assets/icons';
import MButton from '../../components/MButton';
import { commonStyles } from '../CommonStyles';
import { load, OCR_V3, save } from '../../utils/storage';
import { ScreenNames } from '../../navigation';
import DeviceInfo from 'react-native-device-info';
import ImagePicker from 'react-native-image-crop-picker';
import { IconUpload } from '../../assets/svgs';
import { launchImageLibrary } from 'react-native-image-picker';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

export default function RegisterCamera(props: any) {
  const insets = useSafeAreaInsets();
  const isFocused = useIsFocused();
  const [shouldRenderCamera, setShouldRenderCamera] = useState(false);
  const navigation = useNavigation();
  const [showModal, setShowModal] = useState(false);
  const [taking, setTaking] = useState(false);
  const [passPermission, setPassPermission] = useState(false);

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

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

  const loadIntro = async () => {
    const intro = await load(OCR_V3);
    if (!intro) {
      setShowModal(true);
    }
  };

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

  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);
    if (props?.route?.params?.front) {
      navigation.push(ScreenNames.VehicleRegistration, {
        uri,
        loan: props?.route?.params?.loan,
      });
    } else if (props.route?.params?.callback) {
      navigation.goBack();
      props.route?.params?.callback(uri);
    } else {
      navigation.push(ScreenNames.RegisterBack, {
        uri,
        loan: props?.route?.params?.loan,
      });
    }
  };

  const pickImageFromGallery = async () => {
    if (Platform.OS === 'android') {
      const result = await launchImageLibrary({
        mediaType: 'photo',
      });
      if (result.assets) {
        if (props?.route?.params?.front) {
          navigation.push(ScreenNames.VehicleRegistration, {
            uri: result.assets[0]?.uri,
            loan: props?.route?.params?.loan,
          });
        } else if (props.route?.params?.callback) {
          navigation.goBack();
          props.route?.params?.callback(result.assets[0]?.uri);
        } else {
          navigation.push(ScreenNames.RegisterBack, {
            uri: result.assets[0]?.uri,
            loan: props?.route?.params?.loan,
          });
        }
      }
    } else {
      ImagePicker.openPicker({}).then((image) => {
        if (props?.route?.params?.front) {
          navigation.push(ScreenNames.VehicleRegistration, {
            uri:
              Platform.OS === 'android' ? image?.path : 'file://' + image?.path,
            loan: props?.route?.params?.loan,
          });
        } else if (props.route?.params?.callback) {
          navigation.goBack();
          props.route?.params?.callback(
            Platform.OS === 'android' ? image?.path : 'file://' + image?.path
          );
        } else {
          navigation.push(ScreenNames.RegisterBack, {
            uri:
              Platform.OS === 'android' ? image?.path : 'file://' + image?.path,
            loan: props?.route?.params?.loan,
          });
        }
      });
    }
  };
  return (
    <View
      style={[commonStyles.fill, { backgroundColor: 'black' }]}
      pointerEvents={'box-none'}
    >
      {passPermission && shouldRenderCamera ? (
        <View
          style={[
            commonStyles.fill,
            {
              width: Dimensions.get('window').width,
              height: Dimensions.get('window').height,
              // alignItems: 'center',
              zIndex: 1000,
            },
          ]}
        >
          <View
            style={{
              marginVertical: 16,
              marginTop: insets.top + 16,
            }}
          >
            <TouchableOpacity
              onPress={() => {
                navigation.goBack();
              }}
              style={{
                position: 'absolute',
                left: 16,
                zIndex: 100000,
              }}
            >
              <MText
                style={{
                  color: 'white',
                }}
              >
                Trở về
              </MText>
            </TouchableOpacity>
            <MText
              style={{
                color: 'white',
                fontWeight: 'bold',
                textAlign: 'center',
              }}
            >
              {!props?.route?.params?.front
                ? 'Mặt sau Đăng kiểm xe'
                : 'Mặt trước Đăng kiểm xe'}
            </MText>
          </View>
          {device ? (
            <VisionCamera
              ref={myCamera}
              style={{
                width: Dimensions.get('window').width,
                height: (Dimensions.get('window').width * 4) / 3.1,
              }}
              device={device}
              isActive={true}
              photo={true}
              format={format}
            />
          ) : (
            <ActivityIndicator />
          )}
          <View
            style={{
              position: 'absolute',
              bottom: insets.bottom,
              left: 0,
              right: 0,
            }}
          >
            {!taking && (
              <>
                <View style={{ alignItems: 'center', marginBottom: 8 }}>
                  <TouchableOpacity
                    onPress={() => {
                      pickImageFromGallery();
                    }}
                    style={{
                      flexDirection: 'row',
                      alignItems: 'center',
                      gap: 8,
                    }}
                  >
                    <IconUpload />
                    <MText
                      style={{
                        color: 'white',
                        fontSize: 12,
                      }}
                    >
                      Tải ảnh từ thư viện
                    </MText>
                  </TouchableOpacity>
                </View>
                <MText
                  style={{
                    color: 'white',
                    textAlign: 'center',
                    fontSize: 14,
                  }}
                >
                  Xoay ngang màn hình và đặt chứng từ trên{'\n'}mặt phẳng, đảm
                  bảo hình chụp không bị mờ,{'\n'}tối hoặc chói sáng
                </MText>
                <View
                  style={{
                    alignItems: 'center',
                    marginVertical: DeviceInfo.hasNotch() ? 24 : 16,
                  }}
                >
                  <MButton
                    onPress={() => {
                      takePhoto();
                    }}
                  >
                    <TakePhotoSvg />
                  </MButton>
                </View>
              </>
            )}
          </View>
        </View>
      ) : (
        <></>
      )}

      <Modal
        isVisible={showModal}
        style={$modal}
        backdropTransitionInTiming={0}
        animationOutTiming={200}
        animationInTiming={200}
        animationIn={'slideInUp'}
        animationOut={'fadeOutDown'}
        useNativeDriverForBackdrop={true}
        useNativeDriver={true}
      >
        <LinearGradient colors={['#FF8E4F', '#EF592E']} style={$container}>
          <View style={$paddingV}>
            <TouchableOpacity
              onPress={() => {
                setShowModal(false);
                setTimeout(() => {
                  navigation.goBack();
                }, 100);
              }}
              style={{
                width: 24,
                height: 24,
                position: 'absolute',
                left: 16,
                top: 24,
                alignItems: 'center',
                zIndex: 10000,
              }}
            >
              <CloseIcon />
            </TouchableOpacity>
            <MText style={$title}>ĐĂNG KIỂM XE</MText>
            <MText style={$description}>Chụp ảnh đăng kiểm xe</MText>

            <Image
              source={require('../../assets/tts/vehicleStep.png')}
              style={$step}
            />

            <View style={$bg}>
              <View
                style={{
                  flexDirection: 'column',
                  alignItems: 'center',
                }}
              >
                <Image
                  source={require('../../assets/tts/1000011964.png')}
                  style={{
                    width: '60%',
                    height: 120,
                    resizeMode: 'contain',
                    marginVertical: 16,
                  }}
                />
                <MText style={$title2}>
                  Bạn vui lòng chụp ảnh{'\n'}
                  Đăng kiểm xe theo hướng dẫn:
                </MText>
              </View>
              <View style={{ marginTop: 10, paddingHorizontal: 24 }}>
                <View style={$row}>
                  <TimaSmall />
                  <MText style={$txt}>
                    Xoay ngang màn hình điện thoại của bạn như trên
                  </MText>
                </View>
                <View style={$row}>
                  <TimaSmall />
                  <MText style={$txt}>
                    Nên đặt Đăng kiểm xe lên mặt phẳng trắng/ trơn
                  </MText>
                </View>
                <View style={$row}>
                  <TimaSmall />
                  <MText style={$txt}>
                    Đặt Đăng kiểm xe nằm gọn trong khung hình (Không {'\n'} quá
                    nhỏ hay quá to làm mất chi tiết)
                  </MText>
                </View>
                <View style={$row}>
                  <TimaSmall />
                  <MText style={$txt}>
                    Chọn nơi ánh sáng tốt, tránh lóa/ chói hình chụp
                  </MText>
                </View>
                <Image
                  source={require('../../assets/tts/1000009864.png')}
                  style={{
                    width: '100%',
                    height: 100,
                    resizeMode: 'contain',
                    marginTop: 10,
                  }}
                />
              </View>

              <MButton
                onPress={() => {
                  setShowModal(false);
                  save(OCR_V3, true);
                }}
                style={{
                  margin: 16,
                }}
              >
                <LinearGradient
                  start={{ x: 1, y: 0 }}
                  end={{ x: 0, y: 1 }}
                  style={{
                    height: 40,
                    marginVertical: 16,
                    borderRadius: 30,
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}
                  colors={['#FF7A00', '#EF4123']}
                >
                  <MText style={$title}>Tiếp tục</MText>
                </LinearGradient>
              </MButton>
            </View>
          </View>
        </LinearGradient>
      </Modal>
    </View>
  );
}
const $row: ViewStyle = {
  flexDirection: 'row',
  alignItems: 'center',
  marginTop: 5,
};
const $txt: TextStyle = {
  fontSize: 12,
  marginLeft: 5,
};
const $bg: ViewStyle = {
  backgroundColor: 'white',
  borderTopRightRadius: 26,
  borderTopLeftRadius: 26,
};

const $step: ImageStyle = {
  height: 40,
  width: '100%',
  resizeMode: 'contain',
  marginTop: 10,
  marginBottom: 10,
};

const $paddingV: ViewStyle = {
  paddingTop: 16,
};

const $title: TextStyle = {
  fontSize: 16,
  color: 'white',
  fontWeight: 'bold',
  textAlign: 'center',
};

const $title2: TextStyle = {
  fontSize: 16,
  color: '#333333',
  fontWeight: 'bold',
  textAlign: 'center',
};

const $description: TextStyle = {
  fontSize: 12,
  color: 'white',
  textAlign: 'center',
};

const $flex: ViewStyle = {
  flex: 1,
};

const $modal: ViewStyle = {
  justifyContent: 'flex-end',
  margin: 0,
};

const $container: ViewStyle = {
  borderTopRightRadius: 26,
  borderTopLeftRadius: 26,
};
