//@ts-nocheck
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { observer } from 'mobx-react-lite';
import {
  Alert,
  Dimensions,
  SafeAreaView,
  ScrollView,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  View,
} from 'react-native';
import MHeader from '../../components/MHeader';
import { useNavigation, StackActions } from '@react-navigation/native';
import LinearGradient from 'react-native-linear-gradient';
import { MText } from '../../components/MText';
import { Formik } from 'formik';
import { formatDDMMYYY, formatMoney } from '../../utils';
import { commonStyles } from '../CommonStyles';
import {
  CheckBox,
  CheckBoxActive,
  DropDown2,
  Tick2,
  WarningIcon,
} from '../../assets/icons';
import { Api } from '../../services/api';
import Loading from '../../components/Loading';
import { color } from '../../theme';
import appStore from '../../AppStore';
import { ScreenNames } from '../../navigation';
import moment from 'moment';
import { debounce } from 'lodash';
import * as yup from 'yup';

export const UpdateLoan = observer(function UpdateLoan(props: any) {
  const navigation = useNavigation();
  const formRef = useRef(null);
  const [isLoading, setIsLoading] = useState(false);
  const [maximumAmount, setMaximumAmount] = useState(0);

  const getData = async () => {
    setIsLoading(true);
    try {
      const response = await Api.getInstance().getInfoUpdateTopup(
        props.route.params.id
      );
      if (response.kind === 'ok') {
        if (response.data?.meta?.errorCode === 200) {
          setMaximumAmount(response.data.data?.loanAmount);
          formRef.current?.setFieldValue(
            'loanAmount',
            response.data.data?.loanAmount
          );
          formRef.current?.setFieldValue(
            'moneyInsurenceCustomer',
            response.data.data?.moneyInsurenceCustomer
          );
          formRef.current?.setFieldValue(
            'moneyInsuranceProperty',
            response.data.data?.moneyInsuranceProperty
          );
          formRef.current?.setFieldValue(
            'moneyInsurranceHospitalization',
            response.data.data?.moneyInsurranceHospitalization
          );
          formRef.current?.setFieldValue(
            'buyInsurenceCustomer',
            response.data.data?.buyInsurenceCustomer
          );
          formRef.current?.setFieldValue(
            'buyInsuranceProperty',
            response.data.data?.buyInsuranceProperty
          );
          formRef.current?.setFieldValue(
            'buyInsurranceHospitalization',
            response.data.data?.buyInsurranceHospitalization
          );
          const rateTypeId = appStore.listRateType.find(
            (x) => x.id === response.data.data?.rateTypeId
          );
          formRef.current?.setFieldValue('rateTypeId', rateTypeId);
          const loanTime = appStore.listLoanTime.find(
            (x) => x.id === response.data.data?.loanTime
          );
          formRef.current?.setFieldValue('loanTime', loanTime);
          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
          );
          formRef.current?.setFieldValue(
            'firstPaymentDate',
            response.data.data?.firstPaymentDate
              ? moment(response.data.data?.firstPaymentDate).format(
                  'DD-MM-YYYY'
                )
              : null
          );

          appStore.getFirstDayPayment(response.data.data?.loanBriefId, 2);
        } 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) {
      console.error(error);
      Alert.alert('Thông báo', 'Có lỗi xảy ra trong quá trình lấy dữ liệu');
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    if (props.route?.params) {
      getData();
    }
  }, []);

  const getInfoInsurence = async (
    loanAmount,
    loanTime,
    rateTypeId,
    timeInsurenceCustomer,
    timeInsuranceProperty
  ) => {
    try {
      const response = await Api.getInstance().getInfoInsurence(
        props.route.params.id,
        loanAmount,
        loanTime,
        rateTypeId,
        timeInsurenceCustomer,
        timeInsuranceProperty
      );
      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) {}
  };

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

  const onSubmit = async (values) => {
    try {
      const body = {
        loanBriefId: props.route.params.id,
        loanAmount: values?.loanAmount,
        rateTypeId: values.rateTypeId?.id,
        loanTime: values?.loanTime?.id,
        firstPaymentDate: moment(values.firstPaymentDate, 'DD-MM-YYYY').format(
          'YYYY-MM-DD'
        ),
        buyInsurenceCustomer: values.buyInsurenceCustomer,
        buyInsuranceProperty: values.buyInsuranceProperty,
        buyInsurranceHospitalization: values.buyInsurranceHospitalization,
        timeInsurenceCustomer: values.timeInsurenceCustomer?.id,
        timeInsuranceProperty: values.timeInsuranceProperty?.id,
        moneyInsurenceCustomer: values.moneyInsurenceCustomer,
        moneyInsuranceProperty: values.moneyInsuranceProperty,
        moneyInsurranceHospitalization: values.moneyInsurranceHospitalization,
      };
      const response = await Api.getInstance().updateInfoTopup(body);
      if (response.kind === 'ok') {
        if (response.data?.meta?.errorCode === 200) {
          Alert.alert('Thông báo', 'Cập nhật thông tin thành công', [
            {
              text: 'Đồng ý',
              onPress: () => {
                navigation.dispatch(
                  StackActions.replace(
                    ScreenNames.PreviewSchedulePaymentTopup,
                    {
                      id: props.route.params.id,
                      isUpdate: 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 trong quá trình cập nhật');
      }
    } catch (error) {
      console.error(error);
      Alert.alert('Thông báo', 'Có lỗi xảy ra trong quá trình cập nhật');
    }
  };
  return (
    <View style={{ flex: 1, backgroundColor: '#FDFDFD' }}>
      <MHeader
        title={`Cập nhật thông tin`}
        onBack={() => navigation.goBack()}
      />
      <SafeAreaView style={{ flex: 1 }}>
        <ScrollView>
          <Formik
            onSubmit={onSubmit}
            innerRef={formRef}
            initialValues={{
              loanAmount: 0,
              moneyInsurenceCustomer: 0,
              moneyInsuranceProperty: 0,
              moneyInsurranceHospitalization: 0,
              buyInsurenceCustomer: false,
              buyInsuranceProperty: false,
              buyInsurranceHospitalization: false,
              rateTypeId: null,
              loanTime: null,
              firstPaymentDate: null,
              timeInsurenceCustomer: null,
              timeInsuranceProperty: null,
            }}
            validationSchema={yup.object().shape({
              firstPaymentDate: yup
                .string()
                .required('Vui lòng chọn ngày thanh toán')
                .nullable(),
              loanAmount: yup
                .number()
                .required('Vui lòng nhập số tiền')
                .min(1, 'Số tiền không hợp lệ')
                .nullable(),
            })}
          >
            {({ values, handleChange, setFieldValue, errors }) => {
              return (
                <View style={{ padding: 16 }}>
                  <MText style={[commonStyles.textNormal]}>Chọn số tiền</MText>
                  <TextInput
                    style={[styles.input, { color: color.primary }]}
                    value={formatMoney(values.loanAmount)}
                    onChangeText={(text) => {
                      setFieldValue(
                        'loanAmount',
                        Number(text.replace(/\D/g, ''))
                      );
                      debounceCall(text);
                    }}
                    keyboardType="numeric"
                  />
                  {errors && errors.loanAmount && (
                    <MText
                      style={{
                        fontSize: 12,
                        color: 'red',
                        fontStyle: 'italic',
                        marginTop: 5,
                      }}
                    >
                      {errors.loanAmount}
                    </MText>
                  )}
                  <View
                    style={{
                      backgroundColor: '#FFEBEB',
                      marginTop: 8,
                      padding: 8,
                      borderRadius: 4,
                      flexDirection: 'row',
                      alignItems: 'center',
                      gap: 8,
                    }}
                  >
                    <WarningIcon />
                    <MText
                      style={{
                        color: '#333333',
                        fontSize: 12,
                      }}
                    >
                      Số tiền vay tối đa {formatMoney(maximumAmount)}đ
                    </MText>
                  </View>

                  <MText style={[commonStyles.textNormal, { marginTop: 16 }]}>
                    Hình thức thanh toán
                  </MText>
                  <TouchableOpacity
                    onPress={() => {
                      navigation.dispatch(
                        StackActions.push(ScreenNames.CommonSelect, {
                          title: 'Chọn hình thức thanh toán',
                          data: appStore.listRateType,
                          callback: (value) => {
                            setFieldValue('rateTypeId', value);
                            if (value?.id === 14 && values.loanTime?.id > 12) {
                              setFieldValue('loanTime', {
                                id: 12,
                                name: '12 tháng',
                              });
                              getInfoInsurence(
                                values.loanAmount,
                                12,
                                value?.id,
                                values.timeInsurenceCustomer?.id,
                                values.timeInsuranceProperty?.id
                              );
                            } else {
                              getInfoInsurence(
                                values.loanAmount,
                                values.loanTime?.id,
                                value?.id,
                                values.timeInsurenceCustomer?.id,
                                values.timeInsuranceProperty?.id
                              );
                            }
                          },
                        })
                      );
                    }}
                    style={[
                      styles.input,
                      {
                        justifyContent: 'space-between',
                        flexDirection: 'row',
                        alignItems: 'center',
                      },
                    ]}
                  >
                    <MText
                      style={[commonStyles.textNormalBold]}
                      numberOfLines={1}
                    >
                      {values?.rateTypeId?.name}
                    </MText>
                    <DropDown2 />
                  </TouchableOpacity>

                  <MText style={[commonStyles.textNormal, { marginTop: 16 }]}>
                    Thời gian vay
                  </MText>
                  <TouchableOpacity
                    onPress={() => {
                      navigation.dispatch(
                        StackActions.push(ScreenNames.CommonSelect, {
                          title: 'Chọn thời gian vay',
                          data:
                            values.rateTypeId.id === 14
                              ? appStore.listLoanTime.filter((x) => x.id <= 12)
                              : appStore.listLoanTime,
                          callback: (value) => {
                            setFieldValue('loanTime', value);
                            getInfoInsurence(
                              values.loanAmount,
                              value?.id,
                              values?.rateTypeId?.id,
                              values.timeInsurenceCustomer?.id,
                              values.timeInsuranceProperty?.id
                            );
                          },
                        })
                      );
                    }}
                    style={[
                      styles.input,
                      {
                        justifyContent: 'space-between',
                        flexDirection: 'row',
                        alignItems: 'center',
                      },
                    ]}
                  >
                    <MText
                      style={[commonStyles.textNormalBold]}
                      numberOfLines={1}
                    >
                      {values?.loanTime?.name}
                    </MText>
                    <DropDown2 />
                  </TouchableOpacity>

                  <View
                    style={{
                      backgroundColor: '#FFF8F2',
                      marginTop: 16,
                      borderRadius: 8,
                      padding: 16,
                      borderLeftWidth: 1,
                      borderLeftColor: '#EF592E',
                    }}
                  >
                    <MText
                      style={{
                        color: '#EF592E',
                        fontWeight: 'bold',
                      }}
                    >
                      Phí khác
                    </MText>
                    <View
                      style={{
                        flexDirection: 'row',
                        alignItems: 'center',
                        gap: 10,
                        marginTop: 10,
                      }}
                    >
                      <TouchableOpacity
                        onPress={() => {
                          setFieldValue(
                            'buyInsurenceCustomer',
                            !values.buyInsurenceCustomer
                          );
                        }}
                      >
                        {values.buyInsurenceCustomer ? (
                          <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.dispatch(
                            StackActions.push(ScreenNames.CommonSelect, {
                              title: 'Chọn thời gian',
                              data: appStore.listInsurenceTimeAll,
                              callback: (value) => {
                                setFieldValue('timeInsurenceCustomer', value);
                                getInfoInsurence(
                                  values.loanAmount,
                                  values.loanTime?.id,
                                  values?.rateTypeId?.id,
                                  value?.id,
                                  values.timeInsuranceProperty?.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.timeInsurenceCustomer?.name}
                        </MText>
                        <DropDown2 />
                      </TouchableOpacity>
                    </View>
                    <View
                      style={{
                        height: 1,
                        backgroundColor: '#EFEFEF',
                        marginVertical: 8,
                      }}
                    />
                    <View
                      style={{
                        flexDirection: 'row',
                        alignItems: 'center',
                        gap: 10,
                      }}
                    >
                      <TouchableOpacity
                        disabled
                        onPress={() => {
                          setFieldValue(
                            'buyInsuranceProperty',
                            !values.buyInsuranceProperty
                          );
                        }}
                      >
                        {values.buyInsuranceProperty ? (
                          <CheckBoxActive />
                        ) : (
                          <CheckBox />
                        )}
                      </TouchableOpacity>
                      <View style={{ flex: 1 }}>
                        <MText
                          style={{
                            color: '#333333',
                            fontSize: 12,
                            fontWeight: 'bold',
                          }}
                        >
                          Bảo hiểm 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
                        disabled
                        onPress={() => {
                          navigation.dispatch(
                            StackActions.push(ScreenNames.CommonSelect, {
                              title: 'Chọn thời gian',
                              data: appStore.listInsurenceTimeAll,
                              callback: (value) => {
                                setFieldValue('timeInsuranceProperty', value);
                                getInfoInsurence(
                                  values.loanAmount,
                                  values.loanTime?.id,
                                  values?.rateTypeId?.id,
                                  values?.timeInsurenceCustomer?.id,
                                  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}
                        </MText>
                        <DropDown2 />
                      </TouchableOpacity>
                    </View>
                    <View
                      style={{
                        height: 1,
                        backgroundColor: '#EFEFEF',
                        marginVertical: 8,
                      }}
                    />
                    <View
                      style={{
                        flexDirection: 'row',
                        alignItems: 'center',
                        gap: 10,
                      }}
                    >
                      <TouchableOpacity
                        onPress={() => {
                          setFieldValue(
                            'buyInsurranceHospitalization',
                            !values.buyInsurranceHospitalization
                          );
                        }}
                      >
                        {values.buyInsurranceHospitalization ? (
                          <CheckBoxActive />
                        ) : (
                          <CheckBox />
                        )}
                      </TouchableOpacity>
                      <View>
                        <MText
                          style={{
                            color: '#333333',
                            fontSize: 12,
                            fontWeight: 'bold',
                          }}
                        >
                          BH trợ cấp nằm viện
                        </MText>
                        <MText
                          style={{
                            color: '#828282',
                            fontSize: 12,
                            marginTop: 5,
                          }}
                        >
                          Số tiền{' '}
                          <MText
                            style={{
                              fontSize: 12,
                              color: '#333333',
                            }}
                          >
                            {formatMoney(values.moneyInsurranceHospitalization)}
                            đ
                          </MText>
                        </MText>
                      </View>
                    </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>

                  <MText style={[commonStyles.textNormal, { marginTop: 16 }]}>
                    Chọn lịch thanh toán
                  </MText>
                  <TouchableOpacity
                    onPress={() => {
                      navigation.dispatch(
                        StackActions.push(ScreenNames.CommonSelect, {
                          title: 'Chọn ngày thanh toán',
                          data: appStore.listFirstDayPayment.map(
                            (x, index) => ({
                              id: index + 1,
                              name: x,
                            })
                          ),
                          callback: (value) => {
                            setFieldValue('firstPaymentDate', value.name);
                          },
                        })
                      );
                    }}
                    style={[
                      styles.input,
                      {
                        justifyContent: 'space-between',
                        flexDirection: 'row',
                        alignItems: 'center',
                      },
                    ]}
                  >
                    <MText
                      style={[commonStyles.textNormalBold]}
                      numberOfLines={1}
                    >
                      {values?.firstPaymentDate}
                    </MText>
                    <DropDown2 />
                  </TouchableOpacity>
                  {errors && errors.firstPaymentDate && (
                    <MText
                      style={{
                        fontSize: 12,
                        color: 'red',
                        fontStyle: 'italic',
                        marginTop: 5,
                      }}
                    >
                      {errors.firstPaymentDate}
                    </MText>
                  )}
                </View>
              );
            }}
          </Formik>
        </ScrollView>
        <TouchableOpacity
          onPress={formRef.current?.handleSubmit}
          style={{
            marginHorizontal: 16,
            marginVertical: 16,
          }}
        >
          <LinearGradient
            colors={['#FF7A00', '#EF4123']}
            style={{
              alignItems: 'center',
              borderRadius: 30,
              height: 40,
              justifyContent: 'center',
            }}
          >
            <MText
              style={{
                color: 'white',
                fontSize: 16,
              }}
            >
              Cập nhật
            </MText>
          </LinearGradient>
        </TouchableOpacity>
      </SafeAreaView>
      <Loading isLoading={isLoading} />
    </View>
  );
});
const styles = StyleSheet.create({
  input: {
    height: 40,
    marginVertical: 0,
    borderWidth: 0.5,
    borderColor: '#E0E0E0',
    borderRadius: 4,
    marginTop: 8,
    paddingHorizontal: 10,
    fontFamily: 'BeVietnamPro-Regular',
    color: '#333333',
    fontWeight: 'bold',
  },
});
