//@ts-nocheck
import React, { useEffect, useState } from 'react';
import {
  ActivityIndicator,
  Alert,
  Dimensions,
  Image,
  ImageStyle,
  SafeAreaView,
  ScrollView,
  View,
  ViewStyle,
} from 'react-native';
import { MText } from '../../components/MText';
import MHeader from '../../components/MHeader';
import {
  CommonActions,
  StackActions,
  useNavigation,
} from '@react-navigation/native';
import { commonStyles } from '../CommonStyles';
import { TimaSmall, TimaSmallWhite } from '../../assets/icons';
import MButton from '../../components/MButton';
import LinearGradient from 'react-native-linear-gradient';
import { ScreenNames } from '../../navigation';
import { Api } from '../../services/api';
import Loading from '../../components/Loading';

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

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

export default function VehicleRegistrationBack(props: any) {
  const navigation = useNavigation();
  const [photo, setPhoto] = useState(null);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    if (props?.route?.params?.uri) {
      setPhoto(props?.route?.params?.uri);
    }
  }, []);

  const takePhoto = () => {
    navigation.push(ScreenNames.VehicleCamera, {
      loan: props?.route?.params?.loan,
      callback: (photo) => {
        setPhoto(photo);
      },
    });
  };

  const nextStep = async () => {
    try {
      setIsLoading(true);
      const formData = new FormData();
      formData.append('LoanBriefId', props?.route?.params?.loan?.id);
      formData.append('TypeDocumentId', 314); // Đăng ký xe
      formData.append('SubTypeId', 2); // Đăng ký xe mat sau
      formData.append('image', {
        uri: photo,
        type: 'image/jpg',
        name: 'image.jpg',
      });

      const response = await Api.getInstance().uploadImageAutoDE(formData);
      setIsLoading(false);
      if (response.kind === 'ok') {
        if (response.data?.meta?.errorCode === 200) {
          // navigation.push(ScreenNames.RegisterCamera, {
          //   loan: props?.route?.params?.loan,
          //   front: true,
          // });
          if (props?.route?.params?.loan?.typeLoan === 8) {
            navigation.dispatch(
              CommonActions.reset({
                index: 1,
                routes: [
                  {
                    name: ScreenNames.ReviewLoanMotobike,
                    params: {
                      loan: props?.route?.params?.loan,
                    },
                  },
                ],
              })
            );
          } else {
            navigation.dispatch(
              CommonActions.reset({
                index: 1,
                routes: [
                  {
                    name: ScreenNames.AssetInformation,
                    params: {
                      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');
      }
    } catch (error) {
      console.log(error);
      Alert.alert('Thông báo', 'Có lỗi xảy ra. Vui lòng thử lại sau');
      setIsLoading(false);
    }
  };

  return (
    <View style={$flex}>
      <Image source={require('../../assets/img/EKYC.png')} style={logoView} />
      <MHeader
        title="ĐĂNG KÝ XE"
        onBack={() => {
          navigation.goBack();
        }}
      />
      <SafeAreaView style={commonStyles.fill}>
        <ScrollView style={commonStyles.fill}>
          <View style={{ paddingHorizontal: 16, paddingBottom: 16 }}>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                marginTop: 16,
              }}
            >
              <TimaSmallWhite />
              <MText
                style={[
                  commonStyles.textNormalBold,
                  { fontSize: 16, color: '#FFFFFF', marginLeft: 8 },
                ]}
              >
                Chụp đăng ký xe mặt sau
              </MText>
            </View>
            <Image
              source={
                photo ? { uri: photo } : require('../../assets/tts/back.png')
              }
              style={{
                width: Dimensions.get('window').width - 32,
                height: ((Dimensions.get('window').width - 32) * 250) / 360,
                borderWidth: 8,
                borderRadius: 6,
                borderColor: '#FFFFFF',
                marginTop: 16,
              }}
            />
            <View style={{ marginTop: 24 }}>
              <MText style={[commonStyles.textNormalBold, { fontSize: 16 }]}>
                Lưu ý chụp đăng ký xe
              </MText>
              <View
                style={{
                  flexDirection: 'row',
                  marginTop: 16,
                  alignItems: 'center',
                }}
              >
                <TimaSmall />
                <MText
                  style={{ color: '#333333', marginLeft: 8, fontSize: 12 }}
                >
                  Nên đặt đăng ký xe 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 đăng ký xe 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>
        </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>

          <MButton
            disabled={!photo || isLoading}
            style={{ flex: 1 }}
            onPress={() => {
              nextStep();
            }}
          >
            <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>
        </View>
      </SafeAreaView>
      <Loading isLoading={isLoading} />
    </View>
  );
}
