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

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

export default function VehicleRegistration(props) {
  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 trackStarted = async () => {
      await logEvent('dangky_completed', {
        event: 'dangky_completed',
        createdAt: new Date(),
        deviceId: appStore.deviceId,
        loanId: String(props?.route?.params?.loan?.id),
        utmSource: props?.route?.params?.loan?.utmSource,
      });
      logEventFb('dangky_completed');
      await logEvent('dangkiem_started', {
        event: 'dangkiem_started',
        createdAt: new Date(),
        deviceId: appStore.deviceId,
        loanId: String(props?.route?.params?.loan?.id),
        utmSource: props?.route?.params?.loan?.utmSource,
      });
      logEventFb('dangkiem_started');
    };
    trackStarted();
  }, []);

  const takePhoto = () => {
    navigation.push(ScreenNames.RegisterCamera, {
      front: true,
      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', 508); // Đăng kiem xe
      formData.append('SubType', 1); // Đăng kiem xe
      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,
          });
        } 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 KIỂM XE"
        onBack={() => {
          navigation.goBack();
        }}
      />
      <SafeAreaView style={$flex}>
        <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 kiểm xe mặt trước
              </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>
        </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>
        <Loading isLoading={isLoading} />
      </SafeAreaView>
    </View>
  );
}

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