//@ts-nocheck
import { CommonActions, useNavigation } from '@react-navigation/native';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useState } from 'react';
import {
  Image,
  ImageStyle,
  Modal,
  SafeAreaView,
  StatusBar,
  StyleSheet,
  TouchableOpacity,
  View,
} from 'react-native';
import { IconBack, SuccessIcon } from '../../assets/icons';
import { MText } from '../../components/MText';
import { color } from '../../theme';
import { commonStyles } from '../CommonStyles';
import {
  CodeField,
  Cursor,
  useBlurOnFulfill,
  useClearByFocusCell,
} from 'react-native-confirmation-code-field';
import LinearGradient from 'react-native-linear-gradient';
import SignTimaStore from './store';
import { ScreenNames } from '../../navigation';
import Loading from '../../components/Loading';
import appStore from '../../AppStore';
import moment from 'moment';
import MHeader from '../../components/MHeader';

const CELL_COUNT = 4;

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

export const ConfirmContract = observer(function ConfirmContract({
  route,
}: any) {
  const navigation = useNavigation();
  const [showSuccess, setShowSuccess] = useState(false);
  const [value, setValue] = useState('');
  const ref = useBlurOnFulfill({ value, cellCount: CELL_COUNT });
  const [props, getCellOnLayoutHandler] = useClearByFocusCell({
    value,
    setValue,
  });
  const [expire_time, setExpireTime] = useState(300);
  const [open, setOpen] = useState(false);

  useEffect(() => {
    SignTimaStore.getOtpSign(2);
  }, []);

  useEffect(() => {
    let interval = setInterval(() => {
      if (expire_time > 0) {
        setExpireTime(expire_time - 1);
      } else {
        clearInterval(interval);
      }
    }, 1000);
    return () => clearInterval(interval);
  }, [expire_time]);

  const onSubmit = () => {
    const body = {
      LoanBriefId: route.params.loan.id,
      PassCode: value,
    };
    SignTimaStore.confirmContract(body, (data) => {
      setShowSuccess(true);
      setTimeout(() => {
        navigation.dispatch(
          CommonActions.reset({
            index: 1,
            routes: [{ name: ScreenNames.Main }],
          })
        );
      }, 2000);
    });
  };
  return (
    <View style={{ flex: 1, backgroundColor: '#FFFFFF' }}>
      <Image source={require('./Onboarding.png')} style={logoView} />
      <MHeader title="Ký hợp đồng" onBack={() => navigation.goBack()} />
      <SafeAreaView style={{ flex: 1 }}>
        <MText
          style={{
            marginTop: 24,
            padding: 16,
            textAlign: 'center',
            color: '#333333',
            fontWeight: 'bold',
          }}
        >
          Mã xác thực OTP của bạn sẽ được gửi vào số điện{'\n'}thoại{' '}
          {appStore.phone}, vui lòng nhập mã để hoàn thành{'\n'}ký hợp đồng.
        </MText>
        <CodeField
          ref={ref}
          {...props}
          value={value}
          onChangeText={setValue}
          cellCount={CELL_COUNT}
          rootStyle={{
            width: '70%',
            alignSelf: 'center',
            marginBottom: 40,
          }}
          keyboardType="numeric"
          textContentType="jobTitle"
          renderCell={({ index, symbol, isFocused }) => (
            <View
              onLayout={getCellOnLayoutHandler(index)}
              key={index}
              style={{
                width: 54,
                height: 54,
                justifyContent: 'center',
                alignItems: 'center',
                backgroundColor: '#EFEFEF',
                marginHorizontal: 4,
                borderRadius: 8,
              }}
            >
              <MText
                style={{
                  color: '#000',
                  fontSize: 24,
                  textAlign: 'center',
                  fontWeight: '700',
                }}
              >
                {symbol || (isFocused ? <Cursor /> : null)}
              </MText>
            </View>
          )}
        />
        <View style={{ flexDirection: 'row', justifyContent: 'center' }}>
          <TouchableOpacity
            disabled={value.trim().length === 4 ? false : true}
            onPress={() => onSubmit()}
          >
            <LinearGradient
              colors={
                value.trim().length === 4
                  ? ['#FF7A00', '#EF4123']
                  : ['#BDBDBD', '#BDBDBD']
              }
              style={{
                alignItems: 'center',
                borderRadius: 30,
                height: 40,
                justifyContent: 'center',
                paddingHorizontal: 50,
              }}
            >
              <MText style={{ color: 'white' }}>Xác nhận</MText>
            </LinearGradient>
          </TouchableOpacity>
        </View>
        {expire_time === 0 ? (
          <TouchableOpacity
            style={{ alignItems: 'center', marginTop: 16 }}
            onPress={() => setOpen(true)}
          >
            <MText style={{ color: color.primary }}>Gửi lại mã OTP</MText>
          </TouchableOpacity>
        ) : (
          <MText
            style={{ textAlign: 'center', marginTop: 16, color: '#666666' }}
          >
            Gửi lại mã OTP sau ({moment.utc(expire_time * 1000).format('mm:ss')}
            )
          </MText>
        )}
        <Modal transparent={true} animationType={'none'} visible={showSuccess}>
          <View style={styles.modalBackground}>
            <View style={styles.activityIndicatorWrapper}>
              <SuccessIcon />
              <MText
                style={{
                  color: '#FFFFFF',
                  fontWeight: 'bold',
                  fontSize: 16,
                  marginTop: 16,
                }}
              >
                Ký hợp đồng thành công !
              </MText>
            </View>
          </View>
        </Modal>

        <Modal
          visible={open}
          animationType="slide"
          transparent={true}
          onRequestClose={() => {
            setOpen(!open);
          }}
          onDismiss={() => {
            setOpen(!open);
          }}
        >
          <View
            style={{ flex: 1, justifyContent: 'center', paddingHorizontal: 50 }}
          >
            <View style={styles.modalView}>
              <View
                style={{
                  backgroundColor: '#F36D21',
                  borderTopRightRadius: 4,
                  borderTopLeftRadius: 4,
                  justifyContent: 'center',
                  alignItems: 'center',
                  height: 40,
                }}
              >
                <MText
                  style={{
                    fontSize: 16,
                    color: '#FFFFFF',
                    fontWeight: '600',
                  }}
                >
                  Chọn phương thức gửi lại OTP
                </MText>
              </View>
              <View>
                <TouchableOpacity
                  style={styles.btn}
                  onPress={() => {
                    setOpen(false);
                    SignTimaStore.getOtpSign(2);
                    setExpireTime(300);
                  }}
                >
                  <MText>Nhận qua cuộc gọi thoại</MText>
                </TouchableOpacity>
                <TouchableOpacity
                  style={styles.btn}
                  onPress={() => {
                    setOpen(false);
                    SignTimaStore.getOtpSign(4);
                    setExpireTime(300);
                  }}
                >
                  <MText>Nhận qua Zalo</MText>
                </TouchableOpacity>
              </View>
            </View>
          </View>
        </Modal>
        <Loading isLoading={SignTimaStore.isLoading} />
      </SafeAreaView>
    </View>
  );
});

const styles = StyleSheet.create({
  modalBackground: {
    flex: 1,
    alignItems: 'center',
    flexDirection: 'column',
    justifyContent: 'space-around',
    backgroundColor: '#00000090',
  },
  activityIndicatorWrapper: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-around',
  },
  btn: {
    borderWidth: 1,
    borderColor: '#D9D9D9',
    marginTop: 16,
    justifyContent: 'center',
    height: 40,
    alignItems: 'center',
    borderRadius: 30,
    marginHorizontal: 20,
  },
  modalView: {
    backgroundColor: 'white',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 4,
    elevation: 5,
  },
});
