//@ts-nocheck
import React, { useEffect, useState } from 'react';
import {
  View,
  StatusBar,
  SafeAreaView,
  Image,
  Dimensions,
  ScrollView,
  ActivityIndicator,
  Platform,
  Alert,
  TouchableOpacity,
} from 'react-native';
import { CommonActions, useNavigation } from '@react-navigation/native';
import { observer, Observer } from 'mobx-react-lite';
import WebView from 'react-native-webview';
import LinearGradient from 'react-native-linear-gradient';
import { commonStyles } from '../CommonStyles';
import MButton from '../../components/MButton';
import { MText, MTextInput } from '../../components/MText';
import { color } from '../../theme';
import { IconBack } from '../../assets/icons';
import { Formik } from 'formik';
import { myLog } from '../../utils/log';
import * as yup from 'yup';
import eSignStore from './Store';
import ImageView from 'react-native-image-viewing';
import { ScreenNames } from '../../navigation';
import Slack from 'react-native-slack-webhook';
import homeStore from '../home/Store';
import appStore from '../../AppStore';
import Pdf from 'react-native-pdf';
import Modal from 'react-native-modal';
import KeyboardSpacer from '../../components/keyboardspace';
import Loading from '../../components/Loading';
import MHeader from '../../components/MHeader';
import { Api } from '../../services/api';

const webHookURL =
  'https://hooks.slack.com/services/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';

export const ESign = observer(function ESign(props: any) {
  const navigation = useNavigation();
  const loan = props.route.params?.loan;
  const [loading, setLoading] = useState(true);
  const [contract, setContract] = useState<any>();
  const [showModal, setShowModal] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [currentTime, setCurrentTime] = useState(300);
  const timerRef = React.useRef(currentTime);

  const countDown = () => {
    const timerId = setInterval(() => {
      timerRef.current -= 1;
      if (timerRef.current < 0) {
        clearInterval(timerId);
      } else {
        setCurrentTime(timerRef.current);
      }
    }, 1000);
    return () => {
      clearInterval(timerId);
    };
  };

  const verify = (OTP) => {
    if (!eSignStore.isLoading) {
      eSignStore.confirmSignContractForBorrower(
        {
          loanBriefId: loan.id,
          otp: OTP,
        },
        () => {
          try {
            new Slack(webHookURL).post(
              JSON.stringify({
                loanID: loan.id,
                eSign: 'Success',
              }),
              '#timacare'
            );
          } catch (e) {}
          setShowModal(false);
          setTimeout(() => {
            Alert.alert('Thông báo', 'Ký hợp đồng thành công', [
              {
                text: 'Đồng ý',
                onPress: () => {
                  navigation.dispatch(
                    CommonActions.reset({
                      index: 1,
                      routes: [
                        {
                          name: ScreenNames.Main,
                        },
                      ],
                    })
                  );
                },
              },
            ]);
          }, 300);
        }
      );
    }
  };

  const signContract = async () => {
    // setIsLoading(true);
    // eSignStore.signContractForBorrower(
    //   {
    //     loanBriefId: loan.id,
    //   },
    //   () => {
    //     setIsLoading(false);
    //     setShowModal(true);
    //     countDown();
    //   },
    //   () => {
    //     navigation.goBack();
    //     setIsLoading(false);
    //   }
    // );
    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);
    }
  };

  const back = () => {
    navigation.goBack();
  };

  const reSendOTP = () => {
    eSignStore.reSendOTP(
      {
        customerId: loan.id,
      },
      () => {
        setCurrentTime(300);
        timerRef.current = 300;
        countDown();
      }
    );
  };

  useEffect(() => {
    eSignStore.getPreviewContract(
      loan?.id,
      (res) => {
        setContract(res);
        setLoading(false);
      },
      () => {
        setLoading(false);
      },
      () => {
        navigation.goBack();
      }
    );
  }, []);

  return (
    <View style={{ flex: 1, backgroundColor: 'white' }}>
      <MHeader
        title="Ký hợp đồng"
        onBack={() => {
          back();
        }}
      />
      <SafeAreaView style={{ flex: 1 }}>
        <View style={{ flex: 1 }}>
          <View style={{ flex: 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,
              }}
            />
          </View>
          <View style={{ paddingHorizontal: 24 }}>
            {contract?.base64_giaoket_1 && (
              <TouchableOpacity
                style={{ marginTop: 10 }}
                onPress={() => {
                  navigation.push(ScreenNames.PreviewContract, {
                    uri:
                      'data:application/pdf;base64,' +
                      contract?.base64_giaoket_1,
                  });
                }}
              >
                <MText
                  style={{ color: 'blue', textDecorationLine: 'underline' }}
                >
                  Đề nghị giao kết thoả thuận cho vay 1
                </MText>
              </TouchableOpacity>
            )}
            {contract?.base64_giaoket_2 && (
              <TouchableOpacity
                style={{ marginTop: 10 }}
                onPress={() => {
                  navigation.push(ScreenNames.PreviewContract, {
                    uri:
                      'data:application/pdf;base64,' +
                      contract?.base64_giaoket_2,
                  });
                }}
              >
                <MText
                  style={{ color: 'blue', textDecorationLine: 'underline' }}
                >
                  Đề nghị giao kết thoả thuận cho vay 2
                </MText>
              </TouchableOpacity>
            )}
            {contract?.base64_phulucsuadoithoathuanchovay && (
              <TouchableOpacity
                style={{ marginTop: 10 }}
                onPress={() => {
                  navigation.push(ScreenNames.PreviewContract, {
                    uri:
                      'data:application/pdf;base64,' +
                      contract?.base64_phulucsuadoithoathuanchovay,
                  });
                }}
              >
                <MText
                  style={{ color: 'blue', textDecorationLine: 'underline' }}
                >
                  Phụ lục sửa đổi thoả thuận cho vay
                </MText>
              </TouchableOpacity>
            )}
            <MButton
              disabled={isLoading}
              onPress={() => {
                signContract();
              }}
            >
              <LinearGradient
                style={{
                  height: 40,
                  marginVertical: 16,
                  borderRadius: 30,
                  alignItems: 'center',
                  justifyContent: 'center',
                }}
                colors={['#FF7A00', '#EF4123']}
              >
                <MText
                  style={[
                    commonStyles.textNormalBold,
                    {
                      color: 'white',
                      textAlign: 'center',
                    },
                  ]}
                >
                  Ký hợp đồng
                </MText>
              </LinearGradient>
            </MButton>
          </View>
        </View>
      </SafeAreaView>
      <Modal isVisible={showModal}>
        <View style={{ backgroundColor: 'white', padding: 16 }}>
          <MText
            style={{
              fontSize: 12,
              color: color.textHeader,
              marginBottom: 10,
            }}
          >{`Nhập mã OTP`}</MText>
          <Formik
            initialValues={{
              otp: __DEV__ ? '1234' : '',
            }}
            onSubmit={(values, setFieldValue) => {}}
            validationSchema={yup.object().shape({
              otp: yup.string().required('Yêu cầu mã OTP.'),
            })}
          >
            {({ values, setFieldValue, setFieldTouched }) => (
              <View>
                <View style={[commonStyles.row, commonStyles.alignCenter]}>
                  <MTextInput
                    placeholderTextColor={'#939598'}
                    placeholder={'••••••'}
                    style={[
                      commonStyles.textNormal,
                      commonStyles.fill,
                      {
                        textAlign: 'center',
                        fontSize: 16,
                        borderRadius: 4,
                        borderWidth: 1,
                        borderColor: color.border,
                        paddingVertical: Platform.OS === 'android' ? 8 : 14,
                        paddingHorizontal: 16,
                      },
                    ]}
                    onChangeText={(text) => {
                      setFieldValue('otp', text);
                      if (text.length === 6 && eSignStore.currentTime !== 0) {
                        verify(text);
                      }
                    }}
                    maxLength={6}
                    onBlur={() => setFieldTouched('otp')}
                    returnKeyType={'done'}
                    value={values.otp}
                    autoFocus={true}
                    textContentType={'oneTimeCode'}
                    keyboardType={'numeric'}
                  />
                </View>

                <MText
                  style={{
                    fontSize: 12,
                    color: '#AAAAAA',
                    marginTop: 8,
                    fontStyle: 'italic',
                  }}
                >{`Tin nhắn SMS sẽ được gửi tới số điện thoại của bạn có hạn là 5 phút`}</MText>

                <Observer>
                  {() => (
                    <View style={{ alignItems: 'center' }}>
                      {currentTime === 0 ? (
                        <MButton
                          onPress={reSendOTP}
                          style={[
                            commonStyles.alignCenter,
                            commonStyles.justifyCenter,
                            {
                              marginTop: 12,
                              backgroundColor: color.primary,
                              height: 50,
                              borderRadius: 4,
                              paddingHorizontal: 20,
                              marginLeft: 16,
                            },
                          ]}
                        >
                          {eSignStore.reSendOTPLoading ? (
                            <ActivityIndicator color={'white'} size={'small'} />
                          ) : (
                            <MText
                              style={[
                                commonStyles.textNormalBold,
                                { color: 'white' },
                              ]}
                            >
                              Lấy OTP
                            </MText>
                          )}
                        </MButton>
                      ) : (
                        <Observer>
                          {() => (
                            <MText
                              style={[
                                commonStyles.textNormalBold,
                                {
                                  marginTop: 12,
                                  paddingHorizontal: 16,
                                  color: color.primary,
                                },
                              ]}
                            >
                              {currentTime}s
                            </MText>
                          )}
                        </Observer>
                      )}
                    </View>
                  )}
                </Observer>
              </View>
            )}
          </Formik>
        </View>
      </Modal>

      <Loading isLoading={loading || isLoading} />
    </View>
  );
});
