//@ts-nocheck
import React, { useState } from 'react';
import {
  ActivityIndicator,
  Alert,
  Dimensions,
  Image,
  ImageStyle,
  SafeAreaView,
  ScrollView,
  TouchableOpacity,
  View,
} from 'react-native';
import { StackActions, useNavigation } from '@react-navigation/native';
import { observer, Observer } from 'mobx-react-lite';
import { commonStyles } from '../CommonStyles';
import KeyboardSpacer from '../../components/keyboardspace';
import MButton from '../../components/MButton';
import { color } from '../../theme';
import { ScreenNames } from '../../navigation';
import { MText } from '../../components/MText';
import {
  CIMBBank,
  IconBackWhite,
  TimaSmall,
  TimaSmallWhite,
} from '../../assets/icons';
import appStore from '../../AppStore';
import nationalIDStore from './Store';
import Loading from '../../components/Loading';
import LinearGradient from 'react-native-linear-gradient';
import MHeader from '../../components/MHeader';
import livenessStore from '../liveness/LivenessStore';

const logoView: ImageStyle = {
  position: 'absolute',
  width: '100%',
  height: '100%',
  resizeMode: 'cover',
};

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

export const NationalIDBack = observer(function NationalIDBack(props: any) {
  const navigation = useNavigation();
  const [photo, setPhoto] = useState(null);
  const loan = props.route.params?.loan;
  const [base64, setBase64] = useState(null);
  const [isLoading, setIsLoading] = useState(false);

  const nextStep = (values) => {
    setIsLoading(true);
    const form2 = new FormData();
    form2.append('image', {
      uri: photo,
      type: 'image/jpg',
      name: 'image.jpg',
    });
    form2.append('loanbriefId', loan.id);
    form2.append('TypeDocumentId', 311);
    form2.append('UploadFrom', 3);
    form2.append('SubTypeId', 2);
    nationalIDStore.uploadImage(
      form2,
      () => {
        setIsLoading(false);
        navigation.dispatch(StackActions.push(ScreenNames.Selfie, { loan }));
      },
      () => {
        setIsLoading(false);
      }
    );
  };

  const takePhoto = () => {
    livenessStore.getConfigOcr(
      (data) => {
        if (data === 1) {
          navigation.push(ScreenNames.CCCDCameraScreen, {
            front: false,
            callback: (photo) => {
              setPhoto(photo);
            },
          });
        } else {
          navigation.push(ScreenNames.Camera, {
            front: false,
            callback: (photo) => {
              setPhoto(photo);
            },
            base64: (data) => {
              setBase64(data);
            },
          });
        }
      },
      () => {
        navigation.push(ScreenNames.Camera, {
          front: false,
          callback: (photo) => {
            setPhoto(photo);
          },
          base64: (data) => {
            setBase64(data);
          },
        });
      }
    );
  };

  return (
    <View style={{ flex: 1 }}>
      <Image source={require('../../assets/img/EKYC.png')} style={logoView} />
      <MHeader
        title="Xác thực khách hàng"
        onBack={() => {
          navigation.goBack();
        }}
      />
      <SafeAreaView style={commonStyles.fill}>
        <ScrollView style={commonStyles.fill}>
          <View style={{}}>
            <View style={{ paddingHorizontal: 16, paddingVertical: 16 }}>
              <View
                style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  marginTop: 16,
                }}
              >
                <TimaSmallWhite />
                <MText
                  style={[
                    commonStyles.textNormalBold,
                    { fontSize: 16, color: '#FFFFFF', marginLeft: 8 },
                  ]}
                >
                  Chụp CMND/ CCCD mặt sau
                </MText>
              </View>
              <View
                style={{
                  width: '100%',
                  aspectRatio: frameAspectRatio,
                  borderWidth: 8,
                  borderRadius: 6,
                  borderColor: '#FFFFFF',
                  marginTop: 16,
                }}
              >
                <Image
                  source={
                    photo
                      ? { uri: photo }
                      : require('../../assets/img/national_id_back.png')
                  }
                  style={{
                    width: '100%',
                    height: '100%',
                    resizeMode: 'cover',
                  }}
                />
              </View>
              <View style={{ marginTop: 24 }}>
                <MText style={[commonStyles.textNormalBold, { fontSize: 16 }]}>
                  Lưu ý chụp CMND/ CCCD
                </MText>
                <View
                  style={{
                    flexDirection: 'row',
                    marginTop: 16,
                    alignItems: 'center',
                  }}
                >
                  <TimaSmall />
                  <MText
                    style={{ color: '#333333', marginLeft: 8, fontSize: 12 }}
                  >
                    Nên đặt CCCD/ CMND lên mặt phẳng để chụp
                  </MText>
                </View>
                <View style={{ flexDirection: 'row', marginTop: 8 }}>
                  <TimaSmall style={{ marginTop: 5 }} />
                  <MText
                    style={{ color: '#333333', marginLeft: 8, fontSize: 12 }}
                  >
                    Đặt CCCD/ CMND nằm gọn trong khung hình{'\n'}(Không quá nhỏ
                    hay quá to làm mất chi tiết)
                  </MText>
                </View>
                <View
                  style={{
                    flexDirection: 'row',
                    marginTop: 8,
                    alignItems: 'center',
                  }}
                >
                  <TimaSmall />
                  <MText
                    style={{ color: '#333333', marginLeft: 8, fontSize: 12 }}
                  >
                    Chọn nơi ánh sáng tốt, tránh lóa/ chói hình chụp
                  </MText>
                </View>
              </View>
            </View>
          </View>
        </ScrollView>
        <View
          style={{
            flexDirection: 'row',
            paddingHorizontal: 16,
            marginBottom: 30,
          }}
        >
          <MButton
            onPress={() => {
              takePhoto();
            }}
            disabled={isLoading}
            style={[
              commonStyles.row,
              commonStyles.alignCenter,
              commonStyles.justifyCenter,
              {
                backgroundColor: '#FFFFFF',
                height: 40,
                borderRadius: 30,
                flex: 1,
                marginRight: 8,
                borderWidth: 1,
                borderColor: '#EF4123',
              },
            ]}
          >
            <MText style={[commonStyles.textNormal, { color: '#F05123' }]}>
              Chụp ảnh
            </MText>
          </MButton>

          <Observer>
            {() => (
              <MButton
                disabled={!photo || isLoading}
                onPress={nextStep}
                style={{ flex: 1 }}
              >
                <LinearGradient
                  colors={['#FF7A00', '#EF4123']}
                  style={[
                    commonStyles.alignCenter,
                    commonStyles.justifyCenter,
                    {
                      height: 40,
                      borderRadius: 30,
                      marginLeft: 8,
                    },
                  ]}
                >
                  <MText style={[commonStyles.textNormal, { color: 'white' }]}>
                    Tiếp tục
                  </MText>
                </LinearGradient>
              </MButton>
            )}
          </Observer>
        </View>
        {loan?.isPipelineCIMB && (
          <View
            style={{
              marginBottom: 24,
              marginTop: 8,
              flexDirection: 'row',
              justifyContent: 'center',
            }}
          >
            <MText style={{ fontSize: 12, color: '#333333' }}>
              Cung cấp bởi{' '}
            </MText>
            <CIMBBank />
          </View>
        )}
        <KeyboardSpacer />
      </SafeAreaView>
      <Loading isLoading={isLoading} />
    </View>
  );
});
