//@ts-nocheck
import React, { useCallback, useEffect, useRef, useState } from 'react';
import {
  Alert,
  Dimensions,
  ScrollView,
  TextInput,
  TextStyle,
  TouchableOpacity,
  View,
  ViewStyle,
} from 'react-native';
import MHeader from '../../components/MHeader';
import { commonStyles } from '../CommonStyles';
import { CommonActions, useNavigation } from '@react-navigation/native';
import StepIndicator from '../../components/StepIndicator';
import { IconBack } from '../../assets/svgs';
import { MText } from '../../components/MText';
import { Formik } from 'formik';
import { CheckBox, CheckBoxActive, DropDown2, Tick2 } from '../../assets/icons';
import { color } from '../../theme';
import {
  EnumTypeAsset,
  EnumTypeCar,
  formatDDMMYYY,
  formatMoney,
} from '../../utils';
import appStore from '../../AppStore';
import { ScreenNames } from '../../navigation';
import KeyboardSpacer from '../../components/keyboardspace';
import MButton from '../../components/MButton';
import LinearGradient from 'react-native-linear-gradient';
import { Api } from '../../services/api';
import Loading from '../../components/Loading';
import { debounce } from 'lodash';
import moment from 'moment';
import ttsStore from './store';
import * as yup from 'yup';

export default function ReviewLoan(props: any) {
  const navigation = useNavigation();
  const formRef = useRef(null);
  const [isLoading, setIsLoading] = useState(false);

  const onSubmit = async (values) => {
    try {
      setIsLoading(true);
      const body = {
        loanBriefId: props.route?.params?.loan?.id,
        loanAmount: Number(values.loanAmount),
        rateTypeId: values.rateTypeId,
        loanTime: values.loanTime,
        firstPaymentDate: moment(values.firstPaymentDate, 'DD/MM/YYYY').format(
          'YYYY-MM-DD'
        ),
        buyInsurenceCustomer: values?.buyInsurenceCustomer,
        buyInsuranceProperty: values?.buyInsuranceProperty,
        timeInsurenceCustomer: values?.timeInsurenceCustomer?.id ?? 0,
        timeInsuranceProperty: values?.timeInsuranceProperty?.id ?? 0,
        moneyInsurenceCustomer: values.moneyInsurenceCustomer,
        moneyInsuranceProperty: values.moneyInsuranceProperty,
      };

      const response = await Api.getInstance().updateInfoLoanV2(body);
      setIsLoading(false);
      if (response.kind === 'ok') {
        if (response.data?.meta?.errorCode === 200) {
          navigation.push(ScreenNames.OCR, {
            loan: props.route?.params?.loan,
            front: true,
          });
        } 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) {
      setIsLoading(false);
      console.log(error);
    }
  };

  const getData = async () => {
    try {
      setIsLoading(true);
      const response = await Api.getInstance().getInfoLoanAutoDEV2(
        props.route?.params?.loan?.id
      );
      setIsLoading(false);
      if (response.kind === 'ok') {
        if (response.data?.meta.errorCode === 200) {
          formRef.current.setFieldValue(
            'loanAmount',
            response?.data?.data?.loanAmount ?? 0
          );
          formRef.current.setFieldValue(
            'firstPaymentDate',
            formatDDMMYYY(response?.data?.data?.firstPaymentDate) ?? ''
          );
          formRef.current.setFieldValue(
            'rateTypeId',
            response?.data?.data?.rateTypeId ?? null
          );

          if (response?.data?.data?.rateTypeId) {
            appStore.getLoanTimeByType(
              response?.data?.data?.rateTypeId,
              props.route?.params?.loan?.typeLoan ?? 0
            );
          }
          formRef.current.setFieldValue(
            'loanTime',
            response?.data?.data?.loanTime ?? null
          );
          formRef.current.setFieldValue(
            'moneyInsuranceProperty',
            response?.data?.data?.moneyInsuranceProperty ?? null
          );
          formRef.current.setFieldValue(
            'moneyInsurenceCustomer',
            response?.data?.data?.moneyInsurenceCustomer ?? null
          );
          formRef.current.setFieldValue(
            'buyInsuranceProperty',
            response?.data?.data?.buyInsuranceProperty
              ? response?.data?.data?.buyInsuranceProperty
              : false
          );
          formRef.current.setFieldValue(
            'buyInsurenceCustomer',
            response?.data?.data?.buyInsurenceCustomer
              ? response?.data?.data?.buyInsurenceCustomer
              : false
          );

          const timeInsurenceCustomer = appStore.listInsurenceTimeAll.find(
            (x) => x.id === response.data.data?.timeInsurenceCustomer
          );
          formRef.current?.setFieldValue(
            'timeInsurenceCustomer',
            timeInsurenceCustomer
          );
          const timeInsuranceProperty = appStore.listInsurenceTimeAll.find(
            (x) => x.id === response.data.data?.timeInsuranceProperty
          );
          formRef.current?.setFieldValue(
            'timeInsuranceProperty',
            timeInsuranceProperty
          );
        } else {
        }
      }
    } catch (error) {
      setIsLoading(false);
      console.log(error);
    }
  };

  useEffect(() => {
    getData();
    ttsStore.getFirstPayment(props.route?.params?.loan?.id);
    appStore.getRateTypeAll();
  }, []);

  const getInfoInsurence = async (
    loanAmount,
    loanTime,
    rateTypeId,
    timeInsurenceCustomer,
    timeInsuranceProperty
  ) => {
    try {
      setIsLoading(true);
      const response = await Api.getInstance().getInfoInsurence2(
        props.route.params?.loan?.id,
        loanAmount,
        loanTime,
        rateTypeId,
        timeInsurenceCustomer,
        timeInsuranceProperty
      );
      setIsLoading(false);

      if (response.kind === 'ok') {
        if (response.data?.meta?.errorCode === 200) {
          formRef.current?.setFieldValue(
            'moneyInsurenceCustomer',
            response.data.data?.moneyInsurenceCustomer
          );
          formRef.current?.setFieldValue(
            'moneyInsuranceProperty',
            response.data.data?.moneyInsuranceProperty
          );
          formRef.current?.setFieldValue(
            'moneyInsurranceHospitalization',
            response.data.data?.moneyInsurranceHospitalization
          );
        } else {
          Alert.alert('Thông báo', response.data?.meta?.errorMessage);
        }
      } else {
        Alert.alert('Thông báo', 'Có lỗi xảy ra trong quá trình lấy dữ liệu');
      }
    } catch (error) {
      setIsLoading(false);
    }
  };

  const debounceCall = useCallback(
    debounce((textParam) => {
      getInfoInsurence(
        Number(textParam.replace(/\D/g, '')),
        formRef.current.values.loanTime,
        formRef.current.values?.rateTypeId,
        formRef.current.values.timeInsurenceCustomer?.id ?? 0,
        formRef.current.values.timeInsuranceProperty?.id ?? 0
      );
    }, 2000),
    []
  );

  return (
    <View style={{ flex: 1 }}>
      <MHeader title="Vay Online 24/7" />
      <View style={commonStyles.fill}>
        <View style={$h} />
        <View style={$bg}>
          <View
            style={{
              paddingVertical: 10,
              flexDirection: 'row',
              alignItems: 'center',
              paddingHorizontal: 16,
            }}
          >
            <TouchableOpacity
              style={{
                zIndex: 1000,
              }}
              onPress={() => {
                navigation.navigate(ScreenNames.Main);
              }}
            >
              <IconBack />
            </TouchableOpacity>
            <MText style={$title}>Thông tin chi tiết</MText>
          </View>
          {/* <StepIndicator steps={3} currentStep={1} /> */}
          <Formik
            validateOnBlur={false}
            validateOnChange={false}
            innerRef={formRef}
            onSubmit={onSubmit}
            initialValues={{
              loanAmount: '',
              rateTypeId: null,
              loanTime: null,
              firstPaymentDate: '',
              buyInsurenceCustomer: false,
              buyInsuranceProperty: false,
              timeInsurenceCustomer: null,
              timeInsuranceProperty: null,
              moneyInsurenceCustomer: null,
              moneyInsuranceProperty: null,
            }}
            validationSchema={yup.object().shape({
              loanAmount: yup.string().required('Số tiền là bắt buộc'),
              rateTypeId: yup.number().required('HTTT là bắt buộc').nullable(),
              loanTime: yup
                .number()
                .required('Thời gian vay là bắt buộc')
                .nullable(),
              firstPaymentDate: yup
                .string()
                .required('Ngày thanh toán đầu kỳ là bắt buộc'),
            })}
          >
            {({
              values,
              setFieldValue,
              errors,
              handleSubmit,
              handleChange,
            }) => (
              <ScrollView
                style={[commonStyles.fill, { paddingHorizontal: 16 }]}
              >
                <MText style={$title2}>Thông tin đề nghị khoản vay</MText>
                <View style={$row}>
                  <View style={{ flex: 1 }}>
                    <MText style={$label}>Số tiền đề nghị vay</MText>
                    <TextInput
                      numberOfLines={1}
                      style={[
                        $textInput,
                        {
                          color: '#EF592E',
                          fontWeight: '500',
                          fontFamily: 'BeVietnamPro-Medium',
                        },
                      ]}
                      value={formatMoney(values.loanAmount)}
                      onChangeText={(text) => {
                        setFieldValue('loanAmount', text.replaceAll(',', ''));
                        debounceCall(text);
                      }}
                    />
                    {errors && errors.loanAmount && (
                      <MText style={$error}>{errors.loanAmount}</MText>
                    )}
                  </View>
                  <View style={{ flex: 1 }}>
                    <MText style={$label}>Hình thức thanh toán</MText>
                    <TouchableOpacity
                      style={$select}
                      onPress={() => {
                        navigation.push(ScreenNames.MSelect, {
                          title: 'Chọn hình thức thanh toán',
                          data: appStore.listRateType,
                          callback: (value) => {
                            setFieldValue('rateTypeId', value?.id);
                            appStore.getLoanTimeByType(
                              value?.id,
                              props?.route?.params?.loan?.typeLoan ?? 0
                            );
                            setFieldValue('loanTime', null);
                          },
                        });
                      }}
                    >
                      <MText
                        numberOfLines={1}
                        style={{
                          color: '#333333',

                          fontWeight: '500',
                          flex: 1,
                          fontFamily: 'BeVietnamPro-Medium',
                        }}
                      >
                        {
                          appStore.listRateType?.find(
                            (x) => x?.id === values.rateTypeId
                          )?.name
                        }
                      </MText>
                      <DropDown2 />
                    </TouchableOpacity>
                    {errors && errors.rateTypeId && (
                      <MText style={$error}>{errors.rateTypeId}</MText>
                    )}
                  </View>
                </View>

                <MText style={$label}>Thời gian vay</MText>
                <TouchableOpacity
                  style={$select}
                  onPress={() => {
                    navigation.push(ScreenNames.MSelect, {
                      title: 'Chọn thời gian vay',
                      data: appStore.listLoanTimeByType,
                      callback: (value) => {
                        setFieldValue('loanTime', value?.id);
                        getInfoInsurence(
                          values.loanAmount,
                          value?.id,
                          values?.rateTypeId,
                          values.timeInsurenceCustomer?.id ?? 0,
                          values.timeInsuranceProperty?.id ?? 0
                        );
                      },
                    });
                  }}
                >
                  <MText
                    numberOfLines={1}
                    style={{
                      color: '#333333',

                      fontWeight: '500',
                      flex: 1,
                      fontFamily: 'BeVietnamPro-Medium',
                    }}
                  >
                    {values?.loanTime ? `${values?.loanTime} tháng` : ''}
                  </MText>
                  <DropDown2 />
                </TouchableOpacity>
                {errors && errors.loanTime && (
                  <MText style={$error}>{errors.loanTime}</MText>
                )}

                <MText style={[$label, { marginTop: 16 }]}>
                  Ngày thanh toán kỳ đầu
                </MText>
                <TouchableOpacity
                  style={$select}
                  onPress={() => {
                    navigation.push(ScreenNames.MSelect, {
                      title: 'Ngày thanh toán kỳ đầu',
                      data: ttsStore.listFirstPayment,
                      callback: (value) => {
                        setFieldValue('firstPaymentDate', value?.name);
                      },
                    });
                  }}
                >
                  <MText
                    numberOfLines={1}
                    style={{
                      color: '#333333',

                      fontWeight: '500',
                      flex: 1,
                      fontFamily: 'BeVietnamPro-Medium',
                    }}
                  >
                    {values?.firstPaymentDate}
                  </MText>
                  <DropDown2 />
                </TouchableOpacity>
                {errors && errors.firstPaymentDate && (
                  <MText style={$error}>{errors.firstPaymentDate}</MText>
                )}

                <View
                  style={{
                    backgroundColor: '#FFF8F2',
                    borderLeftWidth: 1,
                    borderRadius: 8,
                    padding: 16,
                    borderColor: color.primary,
                    marginTop: 10,
                  }}
                >
                  <MText
                    style={{
                      color: color.primary,
                      fontWeight: 'bold',
                    }}
                  >
                    Bảo hiểm
                  </MText>
                  <View
                    style={{
                      flexDirection: 'row',
                      alignItems: 'center',
                      gap: 10,
                      marginTop: 10,
                    }}
                  >
                    <TouchableOpacity
                      onPress={() => {
                        setFieldValue(
                          'buyInsurenceCustomer',
                          !values.buyInsurenceCustomer
                        );
                      }}
                    >
                      {values.buyInsurenceCustomer === true ? (
                        <CheckBoxActive />
                      ) : (
                        <CheckBox />
                      )}
                    </TouchableOpacity>
                    <View style={{ flex: 1 }}>
                      <MText
                        style={{
                          color: '#333333',
                          fontSize: 12,
                          fontWeight: 'bold',
                        }}
                      >
                        BH sức khoẻ người vay
                      </MText>
                      <MText
                        style={{
                          color: '#828282',
                          fontSize: 12,
                          marginTop: 5,
                        }}
                      >
                        Số tiền{' '}
                        <MText
                          style={{
                            fontSize: 12,
                            color: '#333333',
                          }}
                        >
                          {formatMoney(values.moneyInsurenceCustomer)} đ
                        </MText>
                      </MText>
                    </View>
                    <TouchableOpacity
                      onPress={() => {
                        navigation.push(ScreenNames.MSelect, {
                          title: 'Chọn thời gian',
                          data: appStore.listInsurenceTimeAll,
                          callback: (value) => {
                            setFieldValue('timeInsurenceCustomer', value);
                            getInfoInsurence(
                              values.loanAmount,
                              values.loanTime,
                              values?.rateTypeId,
                              value?.id,
                              values.timeInsuranceProperty?.id ?? 0
                            );
                          },
                        });
                      }}
                      style={{
                        backgroundColor: '#FFFFFF',
                        height: 40,
                        borderRadius: 6,
                        alignItems: 'center',
                        justifyContent: 'space-between',
                        flexDirection: 'row',
                        paddingHorizontal: 10,
                        borderWidth: 1,
                        borderColor: '#F5F5F5',
                        width: Dimensions.get('window').width / 3,
                      }}
                    >
                      <MText style={{ fontSize: 12, color: '#333333' }}>
                        {values.timeInsurenceCustomer?.name ?? 'Chọn thời gian'}
                      </MText>
                      <DropDown2 />
                    </TouchableOpacity>
                  </View>
                  <View
                    style={{
                      height: 1,
                      backgroundColor: '#EFEFEF',
                      marginVertical: 8,
                    }}
                  />
                  <View
                    style={{
                      flexDirection: 'row',
                      alignItems: 'center',
                      gap: 10,
                      marginTop: 10,
                    }}
                  >
                    <TouchableOpacity
                      onPress={() => {
                        setFieldValue(
                          'buyInsuranceProperty',
                          !values.buyInsuranceProperty
                        );
                      }}
                    >
                      {values.buyInsuranceProperty === true ? (
                        <CheckBoxActive />
                      ) : (
                        <CheckBox />
                      )}
                    </TouchableOpacity>
                    <View style={{ flex: 1 }}>
                      <MText
                        style={{
                          color: '#333333',
                          fontSize: 12,
                          fontWeight: 'bold',
                        }}
                      >
                        BH vật chất
                      </MText>
                      <MText
                        style={{
                          color: '#828282',
                          fontSize: 12,
                          marginTop: 5,
                        }}
                      >
                        Số tiền{' '}
                        <MText
                          style={{
                            fontSize: 12,
                            color: '#333333',
                          }}
                        >
                          {formatMoney(values.moneyInsuranceProperty)} đ
                        </MText>
                      </MText>
                    </View>
                    <TouchableOpacity
                      onPress={() => {
                        navigation.push(ScreenNames.MSelect, {
                          title: 'Chọn thời gian',
                          data: appStore.listInsurenceTimeAll,
                          callback: (value) => {
                            setFieldValue('timeInsuranceProperty', value);
                            getInfoInsurence(
                              values.loanAmount,
                              values.loanTime,
                              values?.rateTypeId,
                              values?.timeInsurenceCustomer?.id ?? 0,
                              value?.id
                            );
                          },
                        });
                      }}
                      style={{
                        backgroundColor: '#FFFFFF',
                        height: 40,
                        borderRadius: 6,
                        alignItems: 'center',
                        justifyContent: 'space-between',
                        flexDirection: 'row',
                        paddingHorizontal: 10,
                        borderWidth: 1,
                        borderColor: '#F5F5F5',
                        width: Dimensions.get('window').width / 3,
                      }}
                    >
                      <MText style={{ fontSize: 12, color: '#333333' }}>
                        {values.timeInsuranceProperty?.name ?? 'Chọn thời gian'}
                      </MText>
                      <DropDown2 />
                    </TouchableOpacity>
                  </View>
                  <View
                    style={{
                      height: 1,
                      backgroundColor: '#BDBDBD',
                      marginVertical: 8,
                    }}
                  />
                  <View style={{ flexDirection: 'row', gap: 5 }}>
                    <Tick2 />
                    <MText
                      style={{
                        fontSize: 10,
                        color: '#828282',
                      }}
                    >
                      Quyền lợi bảo hiểm sức khoẻ lên tới 100% từ Bảo Minh
                      {'\n'}
                      (Tai nạn, thương tật,...)
                    </MText>
                  </View>
                  <View style={{ marginTop: 8, flexDirection: 'row', gap: 5 }}>
                    <Tick2 />
                    <MText
                      style={{
                        fontSize: 10,
                        color: '#828282',
                      }}
                    >
                      Quyền lợi bảo hiểm vật chất 100% từ Bảo Minh
                    </MText>
                  </View>
                </View>
              </ScrollView>
            )}
          </Formik>
          <MButton
            onPress={() => {
              formRef.current?.handleSubmit();
            }}
            style={{
              marginVertical: 24,
              marginHorizontal: 16,
            }}
          >
            <LinearGradient
              start={{ x: 1, y: 0 }}
              end={{ x: 0, y: 1 }}
              style={{
                height: 40,
                marginVertical: 16,
                borderRadius: 30,
                alignItems: 'center',
                justifyContent: 'center',
              }}
              colors={['#FF7A00', '#EF4123']}
            >
              <MText
                style={{
                  color: 'white',
                  fontSize: 16,
                }}
              >
                Tiếp tục
              </MText>
            </LinearGradient>
          </MButton>
          <KeyboardSpacer />
        </View>
      </View>
      <Loading isLoading={isLoading} />
    </View>
  );
}

const $select: ViewStyle = {
  flexDirection: 'row',
  height: 40,
  alignItems: 'center',
  paddingHorizontal: 8,
  borderWidth: 1,
  borderRadius: 4,
  borderColor: '#E0E0E0',
};

const $row: ViewStyle = {
  flexDirection: 'row',
  // alignItems: 'center',
  marginBottom: 16,
  gap: 16,
};

const $textInput: ViewStyle = {
  borderWidth: 1,
  borderRadius: 4,
  borderColor: '#E0E0E0',
  height: 40,
  paddingHorizontal: 8,
  fontFamily: 'BeVietnamPro-Medium',
};

const $label: TextStyle = {
  fontSize: 14,
  color: '#333333',
  paddingBottom: 5,
};

const $title2: TextStyle = {
  fontSize: 16,
  fontWeight: 'bold',
  color: '#333333',
  paddingBottom: 10,
  marginTop: 6,
};
const $title: TextStyle = {
  fontSize: 16,
  fontWeight: 'bold',
  color: '#333333',
  position: 'absolute',
  left: 0,
  right: 0,
  textAlign: 'center',
};
const $h: ViewStyle = {
  backgroundColor: '#EF592E',
  position: 'absolute',
  height: 30,
  width: '100%',
};

const $bg: ViewStyle = {
  borderTopLeftRadius: 30,
  borderTopRightRadius: 30,
  backgroundColor: 'white',
  flex: 1,
};

const $error: TextStyle = {
  color: '#EB5757',
  fontSize: 14,
  fontStyle: 'italic',
  fontFamily: 'BeVietnamPro-Thin',
  fontWeight: '300',
  marginTop: 5,
};
