//@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 { MText } from '../../components/MText';
import { ScreenNames } from '../../navigation';
import { CommonActions, useNavigation } from '@react-navigation/native';
import { IconBack } from '../../assets/svgs';
import { Formik } from 'formik';
import { CheckBox, CheckBoxActive, DropDown2, Tick2 } from '../../assets/icons';
import appStore from '../../AppStore';
import { formatDDMMYYY, formatMoney, logEvent, logEventFb } from '../../utils';
import { Api } from '../../services/api';
import { debounce } from 'lodash';
import { color } from '../../theme';
import ttsStore from './store';
import Loading from '../../components/Loading';
import MButton from '../../components/MButton';
import LinearGradient from 'react-native-linear-gradient';
import moment from 'moment';
import * as yup from 'yup';
import DatePicker from 'react-native-date-picker';

export default function TopupLoanInfo(props) {
  const navigation = useNavigation();
  const formRef = useRef(null);
  const [isLoading, setIsLoading] = useState(false);
  const [showDate, setShowDate] = useState(false);
  const getData = async () => {
    try {
      setIsLoading(true);
      const response = await Api.getInstance().getInfoCustomerV2(
        props.route?.params?.loan?.id
      );
      setIsLoading(false);
      if (response.kind === 'ok') {
        if (response.data?.meta.errorCode === 200) {
          formRef.current.setFieldValue(
            'fullName',
            response?.data?.data?.fullName
          );
          formRef.current.setFieldValue(
            'dob',
            response?.data?.data?.dob
              ? formatDDMMYYY(response?.data?.data?.dob)
              : ''
          );
          formRef.current.setFieldValue(
            'gender',
            response?.data?.data?.gender ?? null
          );
          formRef.current.setFieldValue(
            'nationalCard',
            response?.data?.data?.nationalCard
              ? response?.data?.data?.nationalCard
              : ''
          );
          formRef.current.setFieldValue(
            'dateNationalId',
            response?.data?.data?.dateNationalId
              ? formatDDMMYYY(response?.data?.data?.dateNationalId)
              : ''
          );
          formRef.current.setFieldValue(
            'bankAccountName',
            response?.data?.data?.bankAccountName ?? ''
          );
          formRef.current.setFieldValue(
            'bankAccountNumber',
            response?.data?.data?.bankAccountNumber ?? ''
          );
          formRef.current.setFieldValue(
            'bankId',
            response?.data?.data?.bankId ?? null
          );
          formRef.current.setFieldValue(
            'bankName',
            response?.data?.data?.bankName ?? ''
          );
        } else {
        }
      }
    } catch (error) {
      setIsLoading(false);
      console.log(error);
    }
  };

  useEffect(() => {
    getData();
    ttsStore.getListBank();
  }, []);

  const onSubmit = async (values) => {
    try {
      setIsLoading(true);
      const body = {
        LoanBriefId: props.route?.params?.loan?.id,
        DateNationalId: moment(values.dateNationalId, 'DD/MM/YYYY').format(
          'YYYY-MM-DD'
        ),
        bankId: values.bankId,
        bankAccountName: values?.bankAccountName,
        bankAccountNumber: values?.bankAccountNumber,
      };

      const response = await Api.getInstance().updateInfoLoanTopupV2(body);
      setIsLoading(false);
      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: async () => {
                await logEvent('thongtinvay_completed', {
                  event: 'thongtinvay_completed',
                  createdAt: new Date(),
                  deviceId: appStore.deviceId,
                  loanId: String(props.route?.params?.loan?.id),
                  utmSource: props.route?.params?.loan?.utmSource,
                });
                logEventFb('thongtinvay_completed');
                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);
    }
  };

  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={() => {
                Alert.alert(
                  'Thoát cập nhật thông tin',
                  'Bạn có chắc chắn muốn thoát cập nhật thông tin không?',
                  [
                    {
                      text: 'Có',
                      onPress: () => {
                        navigation.dispatch(
                          CommonActions.reset({
                            index: 1,
                            routes: [{ name: ScreenNames.Main }],
                          })
                        );
                      },
                    },
                    {
                      text: 'Không',
                    },
                  ]
                );
              }}
            >
              <IconBack />
            </TouchableOpacity>
            <MText style={$title}>Thông tin chi tiết</MText>
          </View>
          <Formik
            onSubmit={onSubmit}
            innerRef={formRef}
            initialValues={{
              fullName: '',
              dob: '',
              gender: null,
              nationalCard: '',
              dateNationalId: '',
              bankId: null,
              bankName: '',
              bankAccountName: '',
              bankAccountNumber: '',
            }}
            validateOnBlur={false}
            validateOnChange={false}
            validationSchema={yup.object().shape({
              dateNationalId: yup.string().required('Vui lòng chọn ngày cấp CCCD'),
              bankName: yup.string().required('Vui lòng chọn ngân hàng'),
              bankAccountName: yup.string().required('Vui lòng nhập chủ thẻ'),
              bankAccountNumber: yup
                .string()
                .required('Vui lòng nhập số tài khoản'),
            })}
          >
            {({
              values,
              errors,
              setFieldValue,
              handleSubmit,
              handleChange,
            }) => (
              <View style={{ flex: 1, paddingHorizontal: 16 }}>
                <ScrollView
                  style={[commonStyles.fill]}
                  showsVerticalScrollIndicator={false}
                >
                  <MText style={$title2}>1.1 Thông tin cá nhân</MText>
                  <MText style={$label}>Họ và tên</MText>
                  <TextInput
                    editable={false}
                    style={[
                      $textInput,
                      {
                        color: '#333333',
                        fontWeight: '500',
                        fontFamily: 'BeVietnamPro-Medium',
                        backgroundColor: '#EAEAEA',
                      },
                    ]}
                    value={values.fullName}
                  />
                  {errors && errors.fullName && (
                    <MText style={$error}>{errors.fullName}</MText>
                  )}
                  <View style={[$row, { marginTop: 16 }]}>
                    <View style={[commonStyles.fill]}>
                      <MText style={$label}>Sinh ngày</MText>
                      <TouchableOpacity
                        style={[$select, { backgroundColor: '#EAEAEA' }]}
                        disabled
                      >
                        <MText
                          style={{
                            color: '#333333',
                            fontWeight: '500',
                            fontFamily: 'BeVietnamPro-Medium',
                          }}
                        >
                          {values.dob}
                        </MText>
                      </TouchableOpacity>
                    </View>
                    <View style={[commonStyles.fill]}>
                      <MText style={$label}>Giới tính</MText>
                      <TouchableOpacity
                        disabled
                        style={[$select, { backgroundColor: '#EAEAEA' }]}
                      >
                        <MText
                          style={{
                            color: '#333333',
                            fontWeight: '500',
                            fontFamily: 'BeVietnamPro-Medium',
                            flex: 1,
                          }}
                        >
                          {values.gender === 0
                            ? 'Nam'
                            : values.gender === 1
                              ? 'Nữ'
                              : ''}
                        </MText>
                        <DropDown2 />
                      </TouchableOpacity>
                    </View>
                  </View>

                  <View style={[$row]}>
                    <View style={[commonStyles.fill]}>
                      <MText style={$label}>Số CCCD/CMND</MText>
                      <TextInput
                        editable={false}
                        keyboardType="number-pad"
                        style={[
                          $textInput,
                          {
                            color: '#333333',
                            fontWeight: '500',
                            fontFamily: 'BeVietnamPro-Medium',
                            backgroundColor: '#EAEAEA',
                          },
                        ]}
                        value={values.nationalCard}
                        onChangeText={handleChange('nationalCard')}
                      />
                    </View>
                    <View style={[commonStyles.fill]}>
                      <MText style={$label}>Ngày cấp</MText>
                      <TouchableOpacity
                        style={$select}
                        onPress={() => {
                          setShowDate(true);
                        }}
                      >
                        <MText
                          numberOfLines={1}
                          style={{
                            color:
                              values.dateNationalId !== ''
                                ? '#333333'
                                : '#BDBDBD',
                            fontSize: 16,
                            fontWeight: '500',
                            flex: 1,
                          }}
                        >
                          {values.dateNationalId !== ''
                            ? values.dateNationalId
                            : 'DD/MM/YYYY'}
                        </MText>
                      </TouchableOpacity>
                      {errors && errors.dateNationalId && (
                    <MText style={$error}>{errors.dateNationalId}</MText>
                  )}
                    </View>

                    <DatePicker
                      mode="date"
                      open={showDate}
                      modal
                      title="Chọn thời gian"
                      locale="vi"
                      date={new Date()}
                      onCancel={() => {
                        setShowDate(false);
                      }}
                      onConfirm={(date) => {
                        setShowDate(false);

                        setFieldValue('dateNationalId', formatDDMMYYY(date));
                      }}
                    />
                  </View>
                  <MText style={[$title2]}>1.2 Thông tin giải ngân</MText>
                  <MText style={$label}>Ngân hàng</MText>
                  <TouchableOpacity
                    style={$select}
                    onPress={() => {
                      navigation.push(ScreenNames.CommonSelect, {
                        title: 'Chọn ngân hàng',
                        data: ttsStore.listBank,
                        callback: (value) => {
                          setFieldValue('bankName', value.name);
                          setFieldValue('bankId', value.id);
                        },
                      });
                    }}
                  >
                    <MText
                      numberOfLines={1}
                      style={{
                        color: '#333333',
                        fontWeight: '500',
                        flex: 1,
                        fontFamily: 'BeVietnamPro-Medium',
                      }}
                    >
                      {values.bankName}
                    </MText>
                    <DropDown2 />
                  </TouchableOpacity>
                  {errors && errors.bankName && (
                    <MText style={$error}>{errors.bankName}</MText>
                  )}
                  <MText style={[$label, { marginTop: 16 }]}>
                    Tên số tài khoản
                  </MText>
                  <TextInput
                    numberOfLines={1}
                    style={[
                      $textInput,
                      {
                        color: '#333333',
                        fontWeight: '500',
                        fontFamily: 'BeVietnamPro-Medium',
                      },
                    ]}
                    value={values.bankAccountName}
                    onChangeText={handleChange('bankAccountName')}
                  />
                  {errors && errors.bankAccountName && (
                    <MText style={$error}>{errors.bankAccountName}</MText>
                  )}
                  <MText style={[$label, { marginTop: 16 }]}>
                    Số tài khoản
                  </MText>
                  <TextInput
                    keyboardType="number-pad"
                    numberOfLines={1}
                    style={[
                      $textInput,
                      {
                        color: '#333333',
                        fontSize: 16,
                        fontWeight: '500',
                      },
                    ]}
                    value={values.bankAccountNumber}
                    onChangeText={handleChange('bankAccountNumber')}
                  />
                  {errors && errors.bankAccountNumber && (
                    <MText style={$error}>{errors.bankAccountNumber}</MText>
                  )}
                  <View style={{ height: 50 }} />
                </ScrollView>
                <View
                  style={{
                    position: 'absolute',
                    bottom: 24,
                    left: 16,
                    right: 16,
                  }}
                >
                  <MButton
                    onPress={() => {
                      handleSubmit();
                    }}
                    style={{
                      marginVertical: 24,
                    }}
                  >
                    <LinearGradient
                      start={{ x: 1, y: 0 }}
                      end={{ x: 0, y: 1 }}
                      style={{
                        height: 40,
                        borderRadius: 30,
                        alignItems: 'center',
                        justifyContent: 'center',
                      }}
                      colors={['#FF7A00', '#EF4123']}
                    >
                      <MText
                        style={{
                          color: 'white',
                          fontSize: 16,
                        }}
                      >
                        Xác nhận
                      </MText>
                    </LinearGradient>
                  </MButton>
                </View>
              </View>
            )}
          </Formik>
        </View>
      </View>
      <Loading isLoading={isLoading} />
    </View>
  );
}

const $row: ViewStyle = {
  flexDirection: 'row',
  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,
};
