//@ts-nocheck
import React, { useState, Fragment } from 'react';
import {
  ActivityIndicator,
  Alert,
  Dimensions,
  Image,
  ImageStyle,
  Platform,
  SafeAreaView,
  ScrollView,
  TextStyle,
  View,
  ViewStyle,
} from 'react-native';
import {
  CommonActions,
  useNavigation,
  StackActions,
} 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 { MText } from '../../components/MText';
import {
  CIMBBank,
  IconBack,
  IconBackWhite,
  IconCamera,
  TimaSmallWhite,
} from '../../assets/icons';
import { ScreenNames } from '../../navigation';
import appStore from '../../AppStore';
import selfieStore from './SelfieStore';
import nationalIDStore from '../nationalID/Store';
import Loading from '../../components/Loading';
import LinearGradient from 'react-native-linear-gradient';
import livenessStore from '../liveness/LivenessStore';
import MHeader from '../../components/MHeader';

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

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

  const nextStep = (values) => {
    const form = new FormData();
    setIsLoading(true);
    form.append('images', {
      uri: photo,
      type: 'image/jpg',
      name: 'image.jpg',
    });
    form.append('loanbriefId', loan.id);
    form.append('TypeDocumentId', 125);
    form.append('UploadFrom', 3);
    const formSelfie = new FormData();
    formSelfie.append('NationalCard', {
      uri: nationalIDStore.photo,
      type: 'image/jpg',
      name: 'national-card.jpg',
    });
    formSelfie.append('Selfie', {
      uri: photo,
      type: 'image/jpg',
      name: 'selfie.jpg',
    });

    selfieStore.checkSelfieImage(
      formSelfie,
      loan.id,
      () => {
        selfieStore.uploadImage(
          form,
          () => {
            setIsLoading(false);
            livenessStore.getConfigLiveness((data) => {
              if (data === 1) {
                navigation.dispatch(
                  StackActions.push(ScreenNames.LiveNess, { loan })
                );
              } else {
                navigation.dispatch(
                  StackActions.push(ScreenNames.LivenessV2, { loan })
                );
              }
            });
          },
          () => {
            setIsLoading(false);
          }
        );
      },
      () => {
        setIsLoading(false);
      }
    );
  };

  const takePhoto = () => {
    //@ts-ignore
    navigation.push(ScreenNames.Camera, {
      front: true,
      selfie: true,
      callback: (photo) => {
        selfieStore.photo = photo;
        setPhoto(photo);
      },
      base64: (data) => {
        setBase64(data);
        selfieStore.photoBase64 = 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={{ paddingHorizontal: 16, paddingVertical: 16 }}>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                marginTop: 16,
              }}
            >
              <TimaSmallWhite />
              <MText
                style={[
                  commonStyles.textNormalBold,
                  { fontSize: 16, color: '#FFFFFF', marginLeft: 8 },
                ]}
              >
                Ảnh chụp khuôn mặt
              </MText>
            </View>
            <Image
              source={
                photo ? { uri: photo } : require('../../assets/img/selfie.png')
              }
              style={{
                width: Dimensions.get('window').width - 32,
                height: ((Dimensions.get('window').width - 32) * 534) / 564,
                borderWidth: 8,
                borderRadius: 6,
                borderColor: '#FFFFFF',
                marginTop: 16,
              }}
            />
          </View>
        </ScrollView>
        <View
          style={{
            flexDirection: 'row',
            paddingHorizontal: 16,
            marginBottom: 30,
          }}
        >
          <MButton
            //@ts-ignore
            onPress={() => {
              takePhoto();
            }}
            disabled={appStore.isLoading || selfieStore.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,
                    },
                  ]}
                >
                  {isLoading ? (
                    <ActivityIndicator color={'white'} size="small" />
                  ) : (
                    <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>
  );
});
