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

const { width: screenWidth } = Dimensions.get('window');
const frameWidth = screenWidth * 0.85;
const frameHeight = frameWidth * 0.63; // tỷ lệ giống CCCD

export default function VehicleCamera(props: any) {
  const insets = useSafeAreaInsets();
  const isFocused = useIsFocused();
  const [cameraKey, setCameraKey] = useState(0);

  useEffect(() => {
    if (isFocused) {
      setCameraKey((prev) => prev + 1);
    }
  }, [isFocused]);
  const [shouldRenderCamera, setShouldRenderCamera] = useState(false);
  const navigation = useNavigation();
  const [showModal, setShowModal] = useState(false);
  const [title, setTitle] = useState(
    props?.route?.params?.front
      ? 'Chụp đăng ký xe mặt trước'
      : 'Chụp đăng ký xe mặt sau'
  );
  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 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.VehicleRegistrationFront, {
        uri,
        loan: props?.route?.params?.loan,
      });
    } else if (props.route?.params?.callback) {
      navigation.goBack();
      props.route?.params?.callback(uri);
    } else {
      navigation.push(ScreenNames.VehicleRegistrationBack, {
        uri,
        loan: props?.route?.params?.loan,
      });
    }
  };

  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_V2);
    if (!intro) {
      setShowModal(true);
    } else {
      setShowModal(false);
    }
  };

  useEffect(() => {
    requestPermissions();
    loadIntro();
  }, []);

  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 pickImageFromGallery = async () => {
    if (Platform.OS === 'android') {
      const result = await launchImageLibrary({
        mediaType: 'photo',
      });
      if (result.assets) {
        if (props?.route?.params?.front) {
          navigation.push(ScreenNames.VehicleRegistrationFront, {
            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.VehicleRegistrationBack, {
            uri: result.assets[0]?.uri,
            loan: props?.route?.params?.loan,
          });
        }
      }
    } else {
      ImagePicker.openPicker({}).then((image) => {
        if (props?.route?.params?.front) {
          navigation.push(ScreenNames.VehicleRegistrationFront, {
            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.VehicleRegistrationBack, {
            uri:
              Platform.OS === 'android' ? image?.path : 'file://' + image?.path,
            loan: props?.route?.params?.loan,
          });
        }
      });
    }
  };

  return (
    <View
      style={[$flex, { backgroundColor: '#000' }]}
      pointerEvents={'box-none'}
    >
      {passPermission && shouldRenderCamera ? (
        <View style={{ flex: 1 }}>
          {device ? (
            <VisionCamera
              key={cameraKey}
              ref={myCamera}
              style={{
                flex: 1,
              }}
              device={device}
              isActive={true}
              photo={true}
              format={format}
            />
          ) : null}
          <View style={$overlay}>
            <View style={$darkOverlayTop} />
            <View style={$overlayRow}>
              <View style={$darkOverlaySide} />
              <View style={$frameBorder}>
                <Corner
                  style={{
                    top: 0,
                    left: 0,
                    borderTopWidth: CORNER_WIDTH,
                    borderLeftWidth: CORNER_WIDTH,
                    borderColor: BORDER_COLOR,
                  }}
                />

                <Corner
                  style={{
                    top: 0,
                    right: 0,
                    borderTopWidth: CORNER_WIDTH,
                    borderRightWidth: CORNER_WIDTH,
                    borderColor: BORDER_COLOR,
                  }}
                />

                <Corner
                  style={{
                    bottom: 0,
                    left: 0,
                    borderBottomWidth: CORNER_WIDTH,
                    borderLeftWidth: CORNER_WIDTH,
                    borderColor: BORDER_COLOR,
                  }}
                />

                <Corner
                  style={{
                    bottom: 0,
                    right: 0,
                    borderBottomWidth: CORNER_WIDTH,
                    borderRightWidth: CORNER_WIDTH,
                    borderColor: BORDER_COLOR,
                  }}
                />
              </View>
              <View style={$darkOverlaySide} />
            </View>
            <View style={$darkOverlayBottom} />
          </View>

          <View
            style={{
              position: 'absolute',
              bottom: 20,
              left: 0,
              right: 0,
              zIndex: 1000,
            }}
          >
            {/* <TouchableOpacity
              onPress={() => {
                pickImageFromGallery();
              }}
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'center',
                gap: 8,
                marginBottom: 50,
              }}
            >
              <IconUpload />
              <MText
                style={{
                  color: 'white',
                  fontSize: 12,
                }}
              >
                Tải ảnh từ thư viện
              </MText>
            </TouchableOpacity> */}
            {!taking && (
              <>
                <MText
                  style={{
                    color: 'white',
                    textAlign: 'center',
                    fontSize: 14,
                  }}
                >
                  Vui lòng đặt giấy tờ nằm vừa khung hình chữ nhật,{'\n'}chụp đủ
                  ánh sáng và rõ nét.
                </MText>
                <View
                  style={{
                    alignItems: 'center',
                    marginVertical: 24,
                  }}
                >
                  <MButton
                    onPress={() => {
                      takePhoto();
                    }}
                  >
                    <TakePhotoSvg />
                  </MButton>
                </View>
              </>
            )}
          </View>
          <View
            style={[
              commonStyles.fill,
              { position: 'absolute', width: '100%', height: '100%' },
            ]}
          >
            <View
              style={[
                commonStyles.row,
                commonStyles.alignCenter,
                { paddingVertical: 16, marginTop: insets.top },
              ]}
            >
              <MButton
                onPress={() => {
                  navigation.goBack();
                }}
                style={[
                  {
                    width: 48,
                    height: 48,
                    zIndex: 1000,
                    position: 'absolute',
                    left: 16,
                    top: 16,
                  },
                ]}
              >
                <IconBackWhite />
              </MButton>
              <View style={{ flex: 1, alignItems: 'center' }}>
                <MText style={$title}>ĐĂNG KÝ XE</MText>
              </View>
            </View>
            <MText
              style={{
                color: 'white',
                textAlign: 'center',
              }}
            >
              {title}
            </MText>
          </View>
        </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 KÝ XE</MText>
            <MText style={$description}>Chụp ảnh 2 mặt đăng ký 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/vehicleRegistration.png')}
                  style={{
                    width: '60%',
                    height: 120,
                    resizeMode: 'contain',
                    marginVertical: 16,
                  }}
                />
                <MText style={$title2}>
                  Bạn vui lòng chụp ảnh{'\n'}
                  Đăng ký xe theo hướng dẫn:
                </MText>
              </View>
              <View style={{ marginTop: 10, paddingHorizontal: 24 }}>
                <View style={$row}>
                  <TimaSmall />
                  <MText style={$txt}>
                    Nên đặt đăng ký xe lên mặt phẳng để chụp
                  </MText>
                </View>
                <View style={$row}>
                  <TimaSmall />
                  <MText style={$txt}>
                    Đặt Đăng ký 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/1000009872.png')}
                  style={{
                    width: '100%',
                    height: 100,
                    resizeMode: 'contain',
                    marginTop: 10,
                  }}
                />
              </View>

              <MButton
                onPress={() => {
                  setShowModal(false);
                  save(OCR_V2, 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 CORNER_SIZE = 20;
const CORNER_WIDTH = 2;
const BORDER_COLOR = '#FDFDFD';

const Corner = ({ style }: { style: ViewStyle }) => (
  <View
    style={[
      style,
      {
        position: 'absolute',
        width: CORNER_SIZE,
        height: CORNER_SIZE,
      },
    ]}
  />
);

const overlayColor = 'rgba(22, 22, 22, 0.7)';

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

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

const $darkOverlayBottom: ViewStyle = {
  width: '100%',
  flex: 1,
  backgroundColor: overlayColor,
};
const $darkOverlaySide: ViewStyle = {
  flex: 1,
  height: frameHeight,
  backgroundColor: overlayColor,
};
const $frameBorder: ViewStyle = {
  width: frameWidth,
  height: frameHeight,
};

const $overlayRow: ViewStyle = {
  width: '100%',
  height: frameHeight,
  flexDirection: 'row',
  alignItems: 'center',
};

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