//@ts-nocheck
import React, { useEffect } from 'react';
import {
  Alert,
  SafeAreaView,
  ScrollView,
  TouchableOpacity,
  View,
} from 'react-native';
import { MText } from '../../components/MText';
import { CheckBox, CheckBoxActive, IconBack } from '../../assets/icons';
import LinearGradient from 'react-native-linear-gradient';
import { CommonActions, useNavigation } from '@react-navigation/native';
import { ScreenNames } from '../../navigation';
import Pdf from 'react-native-pdf';
import { Api } from '../../services/api';
import { is, set } from 'ramda';
import Loading from '../../components/Loading';
import { logEvent, logEventFb } from '../../utils';
import ttsStore from './store';

export default function TTSSignLoan(props) {
  const loan = props?.route?.params?.loan;
  const [isLoading, setIsLoading] = React.useState(false);
  const [contract, setContract] = React.useState(null);
  const [step, setStep] = React.useState(1);
  const [isAgree, setIsAgree] = React.useState(false);
  const navigation = useNavigation();

  const getContract = async () => {
    try {
      setIsLoading(true);
      const response = await Api.getInstance().previewContract(loan?.id);
      setIsLoading(false);
      if (response.kind === 'ok') {
        if (response.data?.meta?.errorCode === 200) {
          setContract(response.data?.data);
        } else {
          Alert.alert(
            'Thông báo',
            response.data?.meta?.errorMessage ||
              'Có lỗi xảy ra. Vui lòng thử lại sau.',
            [
              {
                text: 'Đồng ý',
                onPress: () => {
                  navigation.dispatch(
                    CommonActions.reset({
                      index: 1,
                      routes: [{ name: ScreenNames.Main }],
                    })
                  );
                },
              },
            ]
          );
        }
      } else {
        Alert.alert('Thông báo', 'Có lỗi xảy ra. Vui lòng thử lại sau.');
      }
    } catch (error) {
      setIsLoading(false);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    if (loan) {
      getContract();
      const trackEvent = async () => {
        await logEvent('kyhopdong_started', {
          event: 'kyhopdong_started',
          createdAt: new Date(),
          deviceId: appStore.deviceId,
          loanId: String(props?.route?.params?.loan?.id),
          utmSource: props?.route?.params?.loan?.utmSource,
        });
        logEventFb('kyhopdong_started', {
          event: 'kyhopdong_started',
          createdAt: new Date(),
          deviceId: appStore.deviceId,
          loanId: props?.route?.params?.loan?.id,
          utmSource: props?.route?.params?.loan?.utmSource,
        });
      };
      trackEvent();
    }
  }, []);

  const signLoan = async () => {
    if (!isAgree) {
      Alert.alert(
        'Thông báo',
        'Bạn cần đồng ý với tất cả những điều kiện trong hợp đồng trước khi ký.'
      );
      return;
    }
    if (contract === null) {
      Alert.alert('Thông báo', 'Không tạo được hợp đồng');
      return;
    }

    if (
      !contract?.base64_hopdongdichvu ||
      contract?.base64_hopdongdichvu === null
    ) {
      Alert.alert(
        'Thông báo',
        'Hợp đồng dịch vụ chưa tồn tại. Không thể ký hợp đồng'
      );
      return;
    }
    if (!contract?.base64_giaoket_1 || contract?.base64_giaoket_1 === null) {
      Alert.alert(
        'Thông báo',
        'Giao kết cho vay chưa tồn tại. Không thể ký hợp đồng'
      );
      return;
    }
    try {
      setIsLoading(true);
      const response = await Api.getInstance().sign_viettel_for_borrower({
        loanBriefId: loan?.id,
      });
      if (response.kind === 'ok' && response.data.meta.errorCode === 200) {
        navigation.push(ScreenNames.MySignViettel, {
          url: response?.data?.data,
          id: loan?.id,
        });
      } else {
        Alert.alert(
          'Thông báo',
          response.data?.meta?.errorMessage ||
            'Có lỗi xảy ra. Vui lòng thử lại sau.',
          [
            {
              text: 'OK',
              onPress: () => {
                navigation.dispatch(
                  CommonActions.reset({
                    index: 1,
                    routes: [{ name: ScreenNames.Main }],
                  })
                );
              },
            },
          ]
        );
      }
    } catch (error) {
      console.log(error);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <View
      style={{
        backgroundColor: '#ffffff',
        flex: 1,
      }}
    >
      <SafeAreaView
        style={{
          backgroundColor: '#ffffff',
          flex: 1,
        }}
      >
        <View
          style={{
            paddingVertical: 16,
            borderBottomWidth: 1,
            borderBottomColor: '#F2F2F2',
          }}
        >
          <TouchableOpacity
            onPress={() => {
              if (step === 1) {
                navigation.dispatch(
                  CommonActions.reset({
                    index: 1,
                    routes: [{ name: ScreenNames.Main }],
                  })
                );
              } else {
                setStep(1);
              }
            }}
            style={{
              position: 'absolute',
              left: 10,
              top: 16,
              width: 25,
              height: 25,
              zIndex: 1000,
              alignItems: 'center',
            }}
          >
            <IconBack />
          </TouchableOpacity>
          <MText
            style={{
              fontSize: 16,
              color: '#333333',
              fontWeight: 'bold',
              textAlign: 'center',
            }}
          >
            Đề nghị giao kết thoả thuận cho vay
          </MText>
        </View>

        <View style={{ flex: 1 }}>
          {step === 1 ? (
            <Pdf
              source={{
                uri:
                  'data:application/pdf;base64,' +
                  contract?.base64_hopdongdichvu,
              }}
              onLoadComplete={(numberOfPages, filePath) => {
                console.log(`Number of pages: ${numberOfPages}`);
              }}
              onPageChanged={(page, numberOfPages) => {
                console.log(`Current page: ${page}`);
              }}
              onError={(error) => {
                console.log(error);
              }}
              onPressLink={(uri) => {
                console.log(`Link pressed: ${uri}`);
              }}
              style={{
                flex: 1,
              }}
            />
          ) : (
            <Pdf
              source={{
                uri:
                  'data:application/pdf;base64,' + contract?.base64_giaoket_1,
              }}
              onLoadComplete={(numberOfPages, filePath) => {
                console.log(`Number of pages: ${numberOfPages}`);
              }}
              onPageChanged={(page, numberOfPages) => {
                console.log(`Current page: ${page}`);
              }}
              onError={(error) => {
                console.log(error);
              }}
              onPressLink={(uri) => {
                console.log(`Link pressed: ${uri}`);
              }}
              style={{
                flex: 1,
              }}
            />
          )}
        </View>

        <View
          style={{
            borderTopWidth: 1,
            borderTopColor: '#F2F2F2',
            paddingVertical: 16,
          }}
        >
          {step === 2 && (
            <View
              style={{
                flexDirection: 'row',
                gap: 10,
                paddingHorizontal: 16,
              }}
            >
              <TouchableOpacity onPress={() => setIsAgree(!isAgree)}>
                {isAgree ? <CheckBoxActive /> : <CheckBox />}
              </TouchableOpacity>
              <MText
                style={{
                  color: '#333333',
                }}
              >
                Tôi đồng ý với tất cả những điều kiện trong hợp đồng.
              </MText>
            </View>
          )}
          <View
            style={{
              flexDirection: 'row',
              gap: 6,
              marginTop: 16,
              marginHorizontal: 16,
            }}
          >
            <View
              style={{
                height: 4,
                backgroundColor: step === 1 ? '#FF7A00' : '#FFEAD8',
                flex: 1,
                borderRadius: 6,
              }}
            />
            <View
              style={{
                height: 4,
                backgroundColor: step === 2 ? '#FF7A00' : '#F2F2F2',
                flex: 1,
                borderRadius: 6,
              }}
            />
          </View>
          {step === 1 ? (
            <TouchableOpacity
              onPress={() => setStep(2)}
              style={{
                height: 40,
                alignItems: 'center',
                justifyContent: 'center',
                borderWidth: 1,
                borderColor: '#FF7A00',
                marginHorizontal: 16,
                borderRadius: 6,
                marginTop: 10,
              }}
            >
              <MText
                style={{
                  color: '#FF7A00',
                  fontSize: 16,
                }}
              >
                Tiếp tục
              </MText>
            </TouchableOpacity>
          ) : (
            <TouchableOpacity
              onPress={() => {
                signLoan();
              }}
              style={{
                marginTop: 10,
                marginHorizontal: 16,
              }}
            >
              <LinearGradient
                start={{ x: 1, y: 0 }}
                end={{ x: 0, y: 1 }}
                style={{
                  height: 40,
                  borderRadius: 6,
                  alignItems: 'center',
                  justifyContent: 'center',
                }}
                colors={['#FF7A00', '#EF4123']}
              >
                <MText
                  style={{
                    color: 'white',
                    fontSize: 16,
                  }}
                >
                  Xác nhận ký
                </MText>
              </LinearGradient>
            </TouchableOpacity>
          )}
        </View>
      </SafeAreaView>
      <Loading isLoading={isLoading} />
    </View>
  );
}
