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

export default function InfoLoanMotobike(props: any) {
  const navigation = useNavigation();
  const loan = props?.route?.params?.loan;
  const [isLoading, setIsLoading] = useState(false);
  const [showDate, setShowDate] = useState(false);
  const [typeDate, setTypeDate] = useState(1);
  const formRef = useRef<any>();
  const getData = async () => {
    try {
      setIsLoading(true);
      const response = await Api.getInstance().getInfoMotobikeLoan(loan?.id);
      setIsLoading(false);
      if (response.kind === 'ok' && response.data?.meta?.errorCode === 200) {
        formRef.current.setFieldValue(
          'loanBriefId',
          response?.data?.data?.loanBriefId
        );
        formRef.current.setFieldValue(
          'customerId',
          response?.data?.data?.customerId
        );
        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(
          'provinceId',
          response?.data?.data?.provinceId
            ? response?.data?.data?.provinceId
            : null
        );
        formRef.current.setFieldValue(
          'provinceName',
          response?.data?.data?.provinceName
            ? response?.data?.data?.provinceName
            : ''
        );
        if (response?.data?.data?.provinceId) {
          ttsStore.getDistrict(response?.data?.data?.provinceId);
        }

        formRef.current.setFieldValue(
          'districtId',
          response?.data?.data?.districtId
            ? response?.data?.data?.districtId
            : null
        );
        formRef.current.setFieldValue(
          'districtName',
          response?.data?.data?.districtName
            ? response?.data?.data?.districtName
            : ''
        );
        if (response?.data?.data?.districtId) {
          ttsStore.getWard(response?.data?.data?.districtId);
        }

        formRef.current.setFieldValue(
          'wardId',
          response?.data?.data?.wardId ? response?.data?.data?.wardId : null
        );
        formRef.current.setFieldValue(
          'wardName',
          response?.data?.data?.wardName ? response?.data?.data?.wardName : ''
        );

        formRef.current.setFieldValue(
          'address',
          response?.data?.data?.address ? response?.data?.data?.address : ''
        );
      } else {
        Alert.alert(
          'Thông báo',
          response?.data?.meta?.errorMessage ||
          'Có lỗi xảy ra, vui lòng thử lại sau'
        );
      }
    } catch (error) {
      Alert.alert('Thông báo', 'Có lỗi xảy ra, vui lòng thử lại sau');
    } finally {
      setIsLoading(false);
    }
  };

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

  const onSubmit = async (values) => {
    const body = {
      LoanBriefId: props?.route?.params?.loan?.id,
      FullName: values.fullName,
      Dob: moment(values.dob, 'DD/MM/YYYY').format('YYYY-MM-DD'),
      Gender: values.gender,
      NationalCard: values.nationalCard,
      DateNationalId: moment(values.dateNationalId, 'DD/MM/YYYY').format(
        'YYYY-MM-DD'
      ),
      ProvinceId: values.provinceId,
      DistrictId: values.districtId,
      WardId: values.wardId,
      Address: values.address,
    };

    try {
      setIsLoading(true);
      const response = await Api.getInstance().updateInfoMotobikeLoan(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);
    }
  };

  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 cá nhân</MText>
          </View>
          <Formik
            onSubmit={onSubmit}
            innerRef={formRef}
            initialValues={{
              loanBriefId: 0,
              customerId: 0,
              fullName: '',
              dob: '',
              gender: null,
              nationalCard: '',
              dateNationalId: '',
              provinceId: null,
              provinceName: '',
              districtId: null,
              districtName: 'null',
              wardId: null,
              wardName: '',
              address: '',
            }}
            validationSchema={yup.object().shape({
              fullName: yup.string().required('Vui lòng nhập họ tên'),
              dob: yup.string().required('Vui lòng nhập ngày sinh').nullable(),
              gender: yup
                .number()
                .required('Vui lòng chọn giới tính')
                .nullable(),
              nationalCard: yup.string().required('Vui lòng nhập CCCD/CMND'),
              dateNationalId: yup
                .string()
                .required('Vui lòng nhập ngày cấp')
                .nullable(),

              provinceName: yup.string().required('Thành phố là bắt buộc'),
              districtName: yup.string().required('Quận huyện là bắt buộc'),
              wardName: yup.string().required('Phường xã là bắt buộc'),
              address: yup.string().required('Địa chỉ là bắt buộc'),
            })}
          >
            {({
              values,
              errors,
              handleChange,
              handleSubmit,
              setFieldValue,
            }) => {
              const renderView = useMemo(
                () => (
                  <ScrollView
                    style={[commonStyles.fill, { paddingHorizontal: 16 }]}
                  >
                    <MText style={$title2}>1.1 Thông tin cá nhân</MText>
                    <MText style={$label}>Họ và tên</MText>
                    <TextInput
                      style={[
                        $textInput,
                        {
                          color: '#333333',
                          fontWeight: '500',
                          fontFamily: 'BeVietnamPro-Medium',
                        },
                      ]}
                      value={values.fullName}
                      onChangeText={handleChange('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}
                          onPress={() => {
                            setTypeDate(1);
                            setShowDate(true);
                          }}
                        >
                          <MText
                            style={{
                              color: '#333333',
                              fontWeight: '500',
                              fontFamily: 'BeVietnamPro-Medium',
                            }}
                          >
                            {values.dob}
                          </MText>
                        </TouchableOpacity>
                        {errors && errors.dob && (
                          <MText style={$error}>{errors.dob}</MText>
                        )}
                      </View>
                      <View style={[commonStyles.fill]}>
                        <MText style={$label}>Giới tính</MText>
                        <TouchableOpacity
                          style={$select}
                          onPress={() => {
                            navigation.push(ScreenNames.MSelect, {
                              title: 'Chọn giới tính',
                              data: EnumGender,
                              callback: (item) => {
                                setFieldValue('gender', item.id);
                              },
                            });
                          }}
                        >
                          <MText
                            style={{
                              color: '#333333',
                              fontWeight: '500',
                              fontFamily: 'BeVietnamPro-Medium',
                              flex: 1,
                            }}
                          >
                            {values.gender === 0
                              ? 'Nam'
                              : values.gender === 1
                                ? 'Nữ'
                                : ''}
                          </MText>
                          <DropDown2 />
                        </TouchableOpacity>
                        {errors && errors.gender && (
                          <MText style={$error}>{errors.gender}</MText>
                        )}
                      </View>
                    </View>

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

                    <MText style={[$title2, { marginTop: 16 }]}>
                      1.2 Nơi ở hiện tại
                    </MText>

                    <View style={[$row, { marginTop: 16 }]}>
                      <View style={[commonStyles.fill]}>
                        <MText style={$label}>Tỉnh/ Thành phố</MText>
                        <TouchableOpacity
                          style={$select}
                          onPress={() => {
                            navigation.push(ScreenNames.CommonSelect, {
                              title: 'Tỉnh/ Thành phố',
                              data: ttsStore.listProvince,
                              callback: (item) => {
                                setFieldValue('provinceId', item.id);
                                setFieldValue('provinceName', item?.name);
                                setFieldValue('districtId', null);
                                setFieldValue('districtName', '');
                                setFieldValue('wardId', null);
                                setFieldValue('wardName', '');
                                ttsStore.getDistrict(item.id);
                              },
                            });
                          }}
                        >
                          <MText
                            numberOfLines={1}
                            style={{
                              color: '#333333',
                              fontWeight: '500',
                              flex: 1,
                              fontFamily: 'BeVietnamPro-Medium',
                            }}
                          >
                            {values.provinceName}
                          </MText>
                          <DropDown2 />
                        </TouchableOpacity>
                        {errors && errors.provinceName && (
                          <MText style={$error}>{errors.provinceName}</MText>
                        )}
                      </View>
                      <View style={[commonStyles.fill]}>
                        <MText style={$label}>Quận/ Huyện</MText>
                        <TouchableOpacity
                          style={$select}
                          onPress={() => {
                            navigation.push(ScreenNames.CommonSelect, {
                              title: 'Quận/ Huyện',
                              data: ttsStore.listDistrict,
                              callback: (item) => {
                                setFieldValue('districtId', item?.id);
                                setFieldValue('districtName', item?.name);
                                setFieldValue('wardId', null);
                                setFieldValue('wardName', '');
                                ttsStore.getWard(item.id);
                              },
                            });
                          }}
                        >
                          <MText
                            numberOfLines={1}
                            style={{
                              color: '#333333',
                              fontWeight: '500',
                              fontFamily: 'BeVietnamPro-Medium',
                              flex: 1,
                            }}
                          >
                            {values.districtName}
                          </MText>
                          <DropDown2 />
                        </TouchableOpacity>
                        {errors && errors.districtName && (
                          <MText style={$error}>{errors.districtName}</MText>
                        )}
                      </View>
                    </View>
                    <MText style={[$label]}>Phường/ Xã</MText>
                    <TouchableOpacity
                      style={$select}
                      onPress={() => {
                        navigation.push(ScreenNames.CommonSelect, {
                          title: 'Phường/ Xã',
                          data: ttsStore.listWard,
                          callback: (item) => {
                            setFieldValue('wardId', item.id);
                            setFieldValue('wardName', item?.name);
                          },
                        });
                      }}
                    >
                      <MText
                        numberOfLines={1}
                        style={{
                          color: '#333333',
                          fontWeight: '500',
                          flex: 1,
                          fontFamily: 'BeVietnamPro-Medium',
                        }}
                      >
                        {values.wardName}
                      </MText>
                      <DropDown2 />
                    </TouchableOpacity>
                    {errors && errors.wardName && (
                      <MText style={$error}>{errors.wardName}</MText>
                    )}
                    <MText style={[$label, { marginTop: 16 }]}>
                      Địa chỉ chi tiết
                    </MText>
                    <TextInput
                      style={[
                        $textInput,
                        {
                          color: '#333333',
                          fontWeight: '500',
                          fontFamily: 'BeVietnamPro-Medium',
                        },
                      ]}
                      value={values.address}
                      onChangeText={handleChange('address')}
                    />
                    {errors && errors.address && (
                      <MText style={$error}>{errors.address}</MText>
                    )}

                    <MButton
                      onPress={() => {
                        handleSubmit();
                      }}
                      style={{
                        marginVertical: 24,
                      }}
                    >
                      <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>
                  </ScrollView>
                ),
                [values, errors]
              );
              return (
                <>
                  {renderView}
                  <DatePicker
                    mode="date"
                    open={showDate}
                    modal
                    title="Chọn thời gian"
                    locale="vi"
                    date={new Date()}
                    onCancel={() => {
                      setShowDate(false);
                    }}
                    onConfirm={(date) => {
                      setShowDate(false);
                      if (typeDate === 1) {
                        setFieldValue('dob', formatDDMMYYY(date));
                      }
                      if (typeDate === 2) {
                        setFieldValue('dateNationalId', formatDDMMYYY(date));
                      }
                    }}
                  />
                </>
              );
            }}
          </Formik>
          <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,
};
