//@ts-nocheck
import {
  CommonActions,
  StackActions,
  useNavigation,
} from '@react-navigation/native';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useState } from 'react';
import { Alert, SafeAreaView, TouchableOpacity, View } from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import Pdf from 'react-native-pdf';
import { CheckBox, CheckBoxActive, IconBack } from '../../assets/icons';
import Loading from '../../components/Loading';
import { MText } from '../../components/MText';
import { ScreenNames } from '../../navigation';
import { color } from '../../theme';
import { commonStyles } from '../CommonStyles';
import SignTimaStore from './store';
import MHeader from '../../components/MHeader';
import { Api } from '../../services/api';

export const ViewContract = observer(function ViewContract(props: any) {
  const navigation = useNavigation();
  const [source, setSource] = useState({});
  const [check, setCheck] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    SignTimaStore.getContract(props.route.params.loan.id, (data) => {
      setSource({ uri: 'data:application/pdf;base64,' + data });
    });
  }, []);

  const sign = async () => {
    try {
      setIsLoading(true);
      const response = await Api.getInstance().sign_viettel_for_borrower_cimb({
        loanBriefId: props.route.params.loan.id,
        isTermesEtConditions: true,
      });
      if (response.kind === 'ok' && response.data?.meta?.errorCode === 200) {
        navigation.push(ScreenNames.MySignViettel, {
          url: response?.data?.data,
          id: props.route.params.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);
      setIsLoading(false);
    } finally {
      setIsLoading(false);
    }
  };
  return (
    <View style={{ flex: 1, backgroundColor: '#FFFFFF' }}>
      <MHeader
        title="Hợp đồng dịch vụ"
        onBack={() => {
          navigation.dispatch(
            CommonActions.reset({
              index: 1,
              routes: [{ name: ScreenNames.Main }],
            })
          );
        }}
      />
      <SafeAreaView style={{ flex: 1 }}>
        <View style={{ flex: 1 }}>
          <Pdf
            source={source}
            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={{
            backgroundColor: 'white',
            marginVertical: 16,
            paddingHorizontal: 16,
          }}
        >
          <View style={{ flexDirection: 'row' }}>
            <TouchableOpacity
              style={{ marginLeft: 8 }}
              onPress={() => setCheck(!check)}
            >
              {check ? <CheckBoxActive /> : <CheckBox />}
            </TouchableOpacity>
            <MText style={{ color: '#333333', paddingLeft: 10 }}>
              Tôi đồng ý với tất cả những điều kiện trong{'\n'} hợp đồng.
            </MText>
          </View>

          <TouchableOpacity
            onPress={() => {
              sign();
            }}
            disabled={!check || isLoading}
            style={{
              marginTop: 32,
              marginBottom: 16,
            }}
          >
            <LinearGradient
              colors={check ? ['#FF7A00', '#EF4123'] : ['#BDBDBD', '#BDBDBD']}
              style={{
                alignItems: 'center',
                borderRadius: 30,
                height: 40,
                justifyContent: 'center',
              }}
            >
              <MText
                style={[
                  commonStyles.textNormalBold,
                  { color: check ? 'white' : '#333333' },
                ]}
              >
                Ký hợp đồng
              </MText>
            </LinearGradient>
          </TouchableOpacity>
        </View>
      </SafeAreaView>
      <Loading isLoading={isLoading} />
    </View>
  );
});
