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

export default function ReviewLoanMotobike(props) {
  const navigation = useNavigation();
  const loan = props?.route?.params?.loan;
  const formRef = useRef(null);
  const [isLoading, setIsLoading] = useState(false);

  const onSubmit = async (values) => {
    try {
      setIsLoading(true);
      const body = {
        loanBriefId: loan?.id,
        loanAmount: Number(values.loanAmount),
        rateTypeId: values.rateTypeId,
        loanTime: values.loanTime,
      };

      const response = await Api.getInstance().updateInfoMotobikeLoan2(body);
      setIsLoading(false);
      if (response.kind === 'ok') {
        if (response.data?.meta?.errorCode === 200) {
          navigation.dispatch(
            CommonActions.reset({
              index: 1,
              routes: [{ name: ScreenNames.Main }],
            })
          );
        } 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().getInfoMotobikeLoan2(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(
            '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
          );
        } else {
        }
      }
    } catch (error) {
      setIsLoading(false);
      console.log(error);
    }
  };

  useEffect(() => {
    getData();
    appStore.getRateTypeAll();
  }, []);

  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.dispatch(
                  CommonActions.reset({
                    index: 1,
                    routes: [{ name: ScreenNames.Main }],
                  })
                );
              }}
            >
              <IconBack />
            </TouchableOpacity>
            <MText style={$title}>Thông tin chi tiết</MText>
          </View>
          <Formik
            validateOnBlur={false}
            validateOnChange={false}
            innerRef={formRef}
            onSubmit={onSubmit}
            initialValues={{
              loanAmount: '',
              rateTypeId: null,
              loanTime: null,
              isCheck: true,
            }}
            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(),
            })}
          >
            {({
              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(',', ''));
                      }}
                    />
                    {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);
                      },
                    });
                  }}
                >
                  <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>
                )}
                <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('isCheck', !values.isCheck);
                      }}
                    >
                      {values.isCheck === true ? (
                        <CheckBoxActive />
                      ) : (
                        <CheckBox />
                      )}
                    </TouchableOpacity>
                    <View style={{ flex: 1 }}>
                      <MText
                        style={{
                          color: '#333333',
                          fontSize: 12,
                          fontWeight: 'bold',
                        }}
                      >
                        Bảo hiểm kèm khoản vay
                      </MText>
                    </View>
                  </View>
                  <View
                    style={{
                      height: 1,
                      backgroundColor: '#BDBDBD',
                      marginVertical: 8,
                    }}
                  />
                  <View style={{ flexDirection: 'row', gap: 5 }}>
                    <Tick2 />
                    <MText
                      style={{
                        fontSize: 10,
                        color: '#828282',
                        flex: 1,
                      }}
                    >
                      Gói vay kèm bảo hiểm giúp bạn an tâm và giảm áp lực tài
                      chính khi có rủi ro.
                    </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 $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 $select: ViewStyle = {
  flexDirection: 'row',
  height: 40,
  alignItems: 'center',
  paddingHorizontal: 8,
  borderWidth: 1,
  borderRadius: 4,
  borderColor: '#E0E0E0',
};

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