//@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 { CommonActions, useNavigation } from '@react-navigation/native';
import { commonStyles } from '../CommonStyles';
import StepIndicator from '../../components/StepIndicator';
import { IconBack } from '../../assets/svgs';
import { MText } from '../../components/MText';
import { Formik } from 'formik';
import { DropDown2 } from '../../assets/icons';
import ttsStore from './store';
import { ScreenNames } from '../../navigation';
import KeyboardSpacer from '../../components/keyboardspace';
import MButton from '../../components/MButton';
import LinearGradient from 'react-native-linear-gradient';
import {
  EnumRelationshipOption1,
  EnumRelationshipOption2,
  formatMoney,
  logEvent,
  logEventFb,
} from '../../utils';
import { Api } from '../../services/api';
import Loading from '../../components/Loading';
import * as yup from 'yup';
import appStore from '../../AppStore';

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

  const getData = async () => {
    try {
      setIsLoading(true);
      const response = await Api.getInstance().getInfoJobV2(
        props.route?.params?.loan?.id
      );
      setIsLoading(false);
      if (response.kind === 'ok') {
        if (response.data?.meta.errorCode === 200) {
          formRef.current.setFieldValue(
            'jobId',
            response?.data?.data?.jobId ?? null
          );
          formRef.current.setFieldValue(
            'jobName',
            response?.data?.data?.jobName ?? ''
          );
          formRef.current.setFieldValue(
            'totalIncome',
            response?.data?.data?.totalIncome ?? ''
          );
          formRef.current.setFieldValue(
            'companyName',
            response?.data?.data?.companyName ?? ''
          );
          formRef.current.setFieldValue(
            'description',
            response?.data?.data?.description ?? ''
          );
          formRef.current.setFieldValue(
            'provinceId',
            response?.data?.data?.provinceId ?? null
          );
          formRef.current.setFieldValue(
            'provinceName',
            response?.data?.data?.provinceName ?? ''
          );
          formRef.current.setFieldValue(
            'districtId',
            response?.data?.data?.districtId ?? null
          );
          formRef.current.setFieldValue(
            'districtName',
            response?.data?.data?.districtName ?? ''
          );
          formRef.current.setFieldValue(
            'wardId',
            response?.data?.data?.wardId ?? null
          );
          formRef.current.setFieldValue(
            'wardName',
            response?.data?.data?.wardName ?? ''
          );
          formRef.current.setFieldValue(
            'address',
            response?.data?.data?.address ?? ''
          );
          formRef.current.setFieldValue(
            'fullName1',
            response?.data?.data?.listRelationships[0]?.fullName ?? ''
          );
          formRef.current.setFieldValue(
            'phone1',
            response?.data?.data?.listRelationships[0]?.phone ?? ''
          );

          formRef.current.setFieldValue(
            'fullName2',
            response?.data?.data?.listRelationships[1]?.fullName ?? ''
          );
          formRef.current.setFieldValue(
            'phone2',
            response?.data?.data?.listRelationships[1]?.phone ?? ''
          );

          if (response?.data?.data?.provinceId) {
            ttsStore.getDistrict(response?.data?.data?.provinceId);
          }
          if (response?.data?.data?.districtId) {
            ttsStore.getWard(response?.data?.data?.districtId);
          }

          if (response.data?.data?.listRelationships[0]?.relationshipType) {
            let r = EnumRelationshipOption1.find(
              (x) =>
                x.id ===
                response.data?.data?.listRelationships[0]?.relationshipType
            );
            formRef.current.setFieldValue('relationshipType1', r);
          }
          if (response.data?.data?.listRelationships[1]?.relationshipType) {
            let r = ttsStore.listRelationship?.find(
              (x) =>
                x.id ===
                response.data?.data?.listRelationships[1]?.relationshipType
            );
            formRef.current.setFieldValue('relationshipType2', r);
          }
        } else {
        }
      }
    } catch (error) {
      setIsLoading(false);
      console.log(error);
    }
  };

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

  const onSubmit = async (values) => {
    Alert.alert(
      'Thông báo',
      'Bạn đã chắc chắn các thông tin đã nhập liệu là chính xác?',
      [
        {
          text: 'Quay lại',
        },
        {
          text: 'Đồng ý nộp hồ sơ',
          onPress: async () => {
            try {
              setIsLoading(true);
              const body = {
                loanBriefId: props.route?.params?.loan?.id,
                jobId: values.jobId,
                totalIncome: Number(values.totalIncome),
                companyName: values.companyName,
                description: values.description,
                provinceId: values.provinceId,
                districtId: values.districtId,
                wardId: values.wardId,
                address: values?.address,
                listRelationships: [
                  {
                    relationshipType: values.relationshipType1?.id,
                    fullName: values.fullName1,
                    phone: values.phone1,
                  },
                  {
                    relationshipType: values.relationshipType2?.id,
                    fullName: values.fullName2,
                    phone: values.phone2,
                  },
                ],
              };

              const response = await Api.getInstance().updateInfoJobV2(body);
              setIsLoading(false);
              if (response.kind === 'ok') {
                if (response.data?.meta?.errorCode === 200) {
                  await logEvent('lead', {
                    event: 'lead',
                    createdAt: new Date(),
                    deviceId: appStore.deviceId,
                    loanId: String(props.route?.params?.loan?.id),
                    utmSource: props.route?.params?.loan?.utmSource,
                  });
                  logEventFb('lead');
                  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');
                  Alert.alert('Thông báo', 'Cập nhật thông tin thành công', [
                    {
                      text: 'Đồng ý',
                      onPress: () => {
                        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 trực tuyến 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 cá nhân</MText>
          </View>
          {/* <StepIndicator steps={3} currentStep={2} /> */}
          <Formik
            onSubmit={onSubmit}
            validationSchema={yup.object().shape({
              jobName: yup.string().required('Vui lòng chọn nghế nghiệp'),
              totalIncome: yup.string().required('Vui lòng nhập thu nhập'),
              companyName: yup.string().required('Vui lòng nhập tên công ty'),
              description: yup.string().required('Vui lòng nhập vị trí'),
              provinceName: yup.string().required('Vui lòng nhập tỉnh/thành'),
              districtName: yup.string().required('Vui lòng nhập quận/huyện'),
              wardName: yup.string().required('Vui lòng nhập phường/xã'),
              address: yup.string().required('Vui lòng nhập địa chỉ'),
              fullName1: yup.string().required('Vui lòng nhập họ tên'),
              phone1: yup.string().required('Vui lòng nhập số điện thoại'),
              relationshipType1: yup
                .object()
                .required('Vui lòng chọn mối quan hệ')
                .nullable(),
              fullName2: yup.string().required('Vui lòng nhập họ tên'),
              phone2: yup.string().required('Vui lòng nhập số điện thoại'),
              relationshipType2: yup
                .object()
                .required('Vui lòng chọn mối quan hệ')
                .nullable(),
            })}
            innerRef={formRef}
            initialValues={{
              jobId: null,
              jobName: '',
              totalIncome: '',
              companyName: '',
              description: '',
              provinceId: null,
              provinceName: '',
              districtId: null,
              districtName: '',
              wardId: null,
              wardName: '',
              address: '',
              fullName1: '',
              phone1: '',
              relationshipType1: null,
              fullName2: '',
              phone2: '',
              relationshipType2: null,
            }}
          >
            {({
              values,
              setFieldValue,
              handleSubmit,
              errors,
              handleChange,
            }) => (
              <ScrollView
                style={[commonStyles.fill, { paddingHorizontal: 16 }]}
              >
                <MText style={$title2}>1.5 Thông tin công việc</MText>
                <View style={$row}>
                  <View style={{ flex: 1 }}>
                    <MText style={$label}>Nghề nghiệp</MText>
                    <TouchableOpacity
                      style={$select}
                      onPress={() => {
                        navigation.push(ScreenNames.MSelect, {
                          title: 'Nghề nghiệp',
                          data: ttsStore.listJob,
                          callback: (item) => {
                            setFieldValue('jobId', item.id);
                            setFieldValue('jobName', item.name);
                          },
                        });
                      }}
                    >
                      <MText
                        numberOfLines={1}
                        style={{
                          color: '#333333',
                          fontWeight: '500',
                          flex: 1,
                          fontFamily: 'BeVietnamPro-Medium',
                        }}
                      >
                        {values.jobName}
                      </MText>
                      <DropDown2 />
                    </TouchableOpacity>
                    {errors && errors.jobName && (
                      <MText style={$error}>{errors.jobName}</MText>
                    )}
                  </View>
                  <View style={{ flex: 1 }}>
                    <MText style={$label}>Thu nhập hàng tháng</MText>
                    <TextInput
                      keyboardType="number-pad"
                      numberOfLines={1}
                      style={[
                        $textInput,
                        {
                          color: '#333333',
                          fontWeight: '500',
                          fontFamily: 'BeVietnamPro-Medium',
                        },
                      ]}
                      value={formatMoney(values.totalIncome)}
                      onChangeText={(text) => {
                        setFieldValue('totalIncome', text.replaceAll(',', ''));
                      }}
                    />
                    {errors && errors.totalIncome && (
                      <MText style={$error}>{errors.totalIncome}</MText>
                    )}
                  </View>
                </View>

                <MText style={$label}>Tên công ty</MText>
                <TextInput
                  numberOfLines={1}
                  style={[
                    $textInput,
                    {
                      color: '#333333',
                      fontWeight: '500',
                      fontFamily: 'BeVietnamPro-Medium',
                    },
                  ]}
                  value={values.companyName}
                  onChangeText={handleChange('companyName')}
                />
                {errors && errors.companyName && (
                  <MText style={$error}>{errors.companyName}</MText>
                )}

                <MText style={[$label, { marginTop: 16 }]}>
                  Vị trí/ Cấp bậc/ Chức vụ
                </MText>
                <TextInput
                  numberOfLines={1}
                  style={[
                    $textInput,
                    {
                      color: '#333333',
                      fontWeight: '500',
                      fontFamily: 'BeVietnamPro-Medium',
                    },
                  ]}
                  value={values.description}
                  onChangeText={handleChange('description')}
                />
                {errors && errors.description && (
                  <MText style={$error}>{errors.description}</MText>
                )}
                <MText
                  style={{
                    fontWeight: 'bold',
                    marginTop: 16,
                    color: '#333333',
                    fontSize: 14,
                  }}
                >
                  Địa chỉ nơi làm việc
                </MText>
                <View style={[$row, { marginTop: 10 }]}>
                  <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('wardId', null);
                            setFieldValue('districtName', '');
                            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: 'Phường/ Xã',
                          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',
                          flex: 1,
                          fontFamily: 'BeVietnamPro-Medium',
                        }}
                      >
                        {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
                  numberOfLines={1}
                  style={[
                    $textInput,
                    {
                      color: '#333333',
                      fontSize: 16,
                      fontWeight: '500',
                    },
                  ]}
                  value={values.address}
                  onChangeText={handleChange('address')}
                />
                {errors && errors.address && (
                  <MText style={$error}>{errors.address}</MText>
                )}

                <MText style={[$title2, { marginTop: 16 }]}>
                  1.6 Tham chiếu
                </MText>

                <MText
                  style={{
                    color: '#999999',
                  }}
                >
                  a. Người tham chiếu thứ nhất
                </MText>
                <View style={[$row, { marginTop: 10 }]}>
                  <View style={{ flex: 1 }}>
                    <MText style={$label}>Mối quan hệ</MText>
                    <TouchableOpacity
                      style={$select}
                      onPress={() => {
                        navigation.push(ScreenNames.MSelect, {
                          title: 'Mối quan hệ',
                          data: EnumRelationshipOption1,
                          callback: (item) => {
                            setFieldValue('relationshipType1', item);
                          },
                        });
                      }}
                    >
                      <MText
                        numberOfLines={1}
                        style={{
                          color: '#333333',
                          fontWeight: '500',
                          flex: 1,
                          fontFamily: 'BeVietnamPro-Medium',
                        }}
                      >
                        {values.relationshipType1?.name}
                      </MText>
                      <DropDown2 />
                    </TouchableOpacity>
                    {errors && errors.relationshipType1 && (
                      <MText style={$error}>{errors.relationshipType1}</MText>
                    )}
                  </View>
                  <View style={{ flex: 1 }}>
                    <MText style={$label}>Số điện thoại</MText>
                    <TextInput
                      keyboardType="number-pad"
                      numberOfLines={1}
                      style={[
                        $textInput,
                        {
                          color: '#333333',
                          fontWeight: '500',
                          fontFamily: 'BeVietnamPro-Medium',
                        },
                      ]}
                      value={values.phone1}
                      onChangeText={handleChange('phone1')}
                    />
                    {errors && errors.phone1 && (
                      <MText style={$error}>{errors.phone1}</MText>
                    )}
                  </View>
                </View>
                <MText style={$label}>Họ và tên</MText>
                <TextInput
                  numberOfLines={1}
                  style={[
                    $textInput,
                    {
                      color: '#333333',
                      fontWeight: '500',
                      fontFamily: 'BeVietnamPro-Medium',
                    },
                  ]}
                  value={values.fullName1}
                  onChangeText={handleChange('fullName1')}
                />
                {errors && errors.fullName1 && (
                  <MText style={$error}>{errors.fullName1}</MText>
                )}
                <MText
                  ellipsizeMode="clip"
                  numberOfLines={1}
                  style={{
                    marginVertical: 10,
                    flex: 1,
                    color: '#D1D1D6',
                    textAlign: 'center',
                  }}
                >
                  --------------------------------------------------------------------------------------------------------
                </MText>
                <MText
                  style={{
                    color: '#999999',
                  }}
                >
                  b. Người tham chiếu thứ hai
                </MText>
                <View style={[$row, { marginTop: 10 }]}>
                  <View style={{ flex: 1 }}>
                    <MText style={$label}>Mối quan hệ</MText>

                    <TouchableOpacity
                      style={$select}
                      onPress={() => {
                        navigation.push(ScreenNames.MSelect, {
                          title: 'Mối quan hệ',
                          data: ttsStore.listRelationship,
                          callback: (item) => {
                            setFieldValue('relationshipType2', item);
                          },
                        });
                      }}
                    >
                      <MText
                        numberOfLines={1}
                        style={{
                          color: '#333333',
                          fontWeight: '500',
                          flex: 1,
                          fontFamily: 'BeVietnamPro-Medium',
                        }}
                      >
                        {values.relationshipType2?.name}
                      </MText>
                      <DropDown2 />
                    </TouchableOpacity>
                    {errors && errors.relationshipType2 && (
                      <MText style={$error}>{errors.relationshipType2}</MText>
                    )}
                  </View>
                  <View style={{ flex: 1 }}>
                    <MText style={$label}>Số điện thoại</MText>
                    <TextInput
                      keyboardType="number-pad"
                      numberOfLines={1}
                      style={[
                        $textInput,
                        {
                          color: '#333333',
                          fontWeight: '500',
                          fontFamily: 'BeVietnamPro-Medium',
                        },
                      ]}
                      value={values.phone2}
                      onChangeText={handleChange('phone2')}
                    />
                    {errors && errors.phone2 && (
                      <MText style={$error}>{errors.phone2}</MText>
                    )}
                  </View>
                </View>
                <MText style={$label}>Họ và tên</MText>
                <TextInput
                  numberOfLines={1}
                  style={[
                    $textInput,
                    {
                      color: '#333333',
                      fontWeight: '500',
                      fontFamily: 'BeVietnamPro-Medium',
                    },
                  ]}
                  value={values.fullName2}
                  onChangeText={handleChange('fullName2')}
                />
                {errors && errors.fullName2 && (
                  <MText style={$error}>{errors.fullName2}</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,
                      }}
                    >
                      Hoàn thành cập nhật
                    </MText>
                  </LinearGradient>
                </MButton>
              </ScrollView>
            )}
          </Formik>
          <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,
};
