//@ts-nocheck
import { observer, Observer } from 'mobx-react-lite';
import React, { useEffect, useState } from 'react';
import {
  ActivityIndicator,
  Dimensions,
  ScrollView,
  TouchableOpacity,
  View,
} from 'react-native';
import { MText } from '../../components/MText';
import { commonStyles } from '../CommonStyles';
import FastImage from 'react-native-fast-image';
import ImageView from 'react-native-image-viewing';
import { CIMBBank, IConCamera } from '../../assets/icons';
import ImagePicker from 'react-native-image-crop-picker';
import FullSubmitStore from './store';
import { color } from '../../theme';
import LinearGradient from 'react-native-linear-gradient';
import { CommonActions, useNavigation } from '@react-navigation/native';
import { ScreenNames } from '../../navigation';
import Loading from '../../components/Loading';

interface IProps {
  loan: any;
}

export const UpdateDocument = observer(function UpdateDocument({
  loan,
}: IProps) {
  const navigation = useNavigation();
  useEffect(() => {
    if (loan) {
      FullSubmitStore.getDocument(loan?.id, (res) => {
        setData(res);
      });
    }
  }, [loan]);

  const [images, setImages] = useState([
    { uri: 'https://unsplash.it/400/400?image=1' },
  ]);
  const [visible, setIsVisible] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [data, setData] = useState<any[]>();

  const takePhoto = async (typId) => {
    ImagePicker.openCamera({})
      .then((image) => {
        const formData = new FormData();
        formData.append('loanbriefId', loan?.id);
        formData.append('TypeDocumentId', typId);
        formData.append('image', {
          uri: image.path,
          type: image.mime,
          name: 'image.jpg',
        });
        FullSubmitStore.uploadDocument(formData, () => {
          FullSubmitStore.getDocument(loan?.id, (res) => {
            setData(res);
          });
        });
      })
      .catch((err) => {
        console.log(err);
      });
  };
  const handleSubmit = () => {
    setIsLoading(true);
    FullSubmitStore.confirmData(
      loan?.id,
      () => {
        setIsLoading(false);
        FullSubmitStore.tab = 1;
        navigation.dispatch(
          CommonActions.reset({
            index: 1,
            routes: [{ name: ScreenNames.Main }],
          })
        );
      },
      () => {
        setIsLoading(false);
      }
    );
  };

  return (
    <View style={{ flex: 1, backgroundColor: '#FFFFFF' }}>
      {FullSubmitStore.loadingDocument ? (
        <View
          style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}
        >
          <ActivityIndicator size={'small'} color={color.primary} />
        </View>
      ) : (
        <View style={{ flex: 1 }}>
          <ScrollView style={{ flex: 1 }}>
            <View style={{ marginHorizontal: 16, marginBottom: 16 }}>
              <MText style={[commonStyles.textNormalBold, { fontSize: 16 }]}>
                UPLOAD CHỨNG TỪ
              </MText>
              <Observer>
                {() => (
                  <View>
                    {data?.map((item: any, index: number) => (
                      <View key={index} style={{ marginBottom: 16 }}>
                        <View
                          style={{
                            flexDirection: 'row',
                            justifyContent: 'space-between',
                            alignItems: 'center',
                          }}
                        >
                          <View style={{ flex: 1, paddingRight: 15 }}>
                            <MText
                              style={[
                                commonStyles.textNormalBold,
                                { marginTop: 8 },
                              ]}
                            >
                              {item.documentName}
                            </MText>
                          </View>
                          {item?.isUpload && (
                            <TouchableOpacity
                              style={{
                                borderWidth: 1,
                                borderColor: '#D9D9D9',
                                paddingVertical: 8,
                                borderRadius: 6,
                                paddingHorizontal: 10,
                                flexDirection: 'row',
                                alignItems: 'center',
                              }}
                              onPress={() => {
                                takePhoto(item.documentId);
                              }}
                            >
                              <IConCamera />
                              <MText
                                style={[
                                  commonStyles.textNormal,
                                  {
                                    color: '#F05123',
                                    marginLeft: 8,
                                    fontSize: 12,
                                  },
                                ]}
                              >
                                Chụp ảnh
                              </MText>
                            </TouchableOpacity>
                          )}
                        </View>
                        {item?.listFile && (
                          <View style={{ paddingHorizontal: 10 }}>
                            <View style={{ marginVertical: 8 }}>
                              <ScrollView
                                horizontal
                                showsHorizontalScrollIndicator={false}
                              >
                                {item?.listFile.map((image) => (
                                  <TouchableOpacity
                                    style={{ paddingRight: 8 }}
                                    onPress={() => {
                                      setIsVisible(true);
                                      setImages([
                                        {
                                          uri:
                                            `https://file.tima.vn` +
                                            image?.filePath,
                                        },
                                      ]);
                                    }}
                                  >
                                    <FastImage
                                      style={{
                                        width:
                                          Dimensions.get('screen').width * 0.2,
                                        height:
                                          Dimensions.get('screen').height * 0.1,
                                      }}
                                      source={{
                                        uri:
                                          `https://file.tima.vn` +
                                          image?.filePath,
                                        priority: FastImage.priority.normal,
                                      }}
                                      resizeMode={FastImage.resizeMode.cover}
                                    />
                                  </TouchableOpacity>
                                ))}
                              </ScrollView>
                            </View>
                          </View>
                        )}
                        {item?.listChild &&
                          item?.listChild.map((child: any, idx: number) => (
                            <View style={{ marginBottom: 16 }}>
                              <View
                                style={{
                                  flexDirection: 'row',
                                  justifyContent: 'space-between',
                                  alignItems: 'center',
                                  marginHorizontal: 16,
                                }}
                              >
                                <View style={{ flex: 1, paddingRight: 15 }}>
                                  <MText
                                    style={[
                                      commonStyles.textNormalBold,
                                      { marginTop: 8 },
                                    ]}
                                  >
                                    {child.documentName}
                                  </MText>
                                </View>
                                {child?.isUpload && (
                                  <TouchableOpacity
                                    style={{
                                      borderWidth: 1,
                                      borderColor: '#D9D9D9',
                                      paddingVertical: 8,
                                      borderRadius: 6,
                                      paddingHorizontal: 10,
                                      flexDirection: 'row',
                                      alignItems: 'center',
                                    }}
                                    onPress={() => {
                                      takePhoto(child.documentId);
                                    }}
                                  >
                                    <IConCamera />
                                    <MText
                                      style={[
                                        commonStyles.textNormal,
                                        {
                                          color: '#F05123',
                                          marginLeft: 8,
                                          fontSize: 12,
                                        },
                                      ]}
                                    >
                                      Chụp ảnh
                                    </MText>
                                  </TouchableOpacity>
                                )}
                              </View>
                              {child?.listFile && (
                                <View style={{ paddingHorizontal: 10 }}>
                                  <View style={{ marginVertical: 8 }}>
                                    <ScrollView
                                      horizontal
                                      showsHorizontalScrollIndicator={false}
                                    >
                                      {child?.listFile.map((image) => (
                                        <TouchableOpacity
                                          style={{ paddingRight: 8 }}
                                          onPress={() => {
                                            setIsVisible(true);
                                            setImages([
                                              {
                                                uri:
                                                  `https://file.tima.vn` +
                                                  image?.filePath,
                                              },
                                            ]);
                                          }}
                                        >
                                          <FastImage
                                            style={{
                                              width:
                                                Dimensions.get('screen').width *
                                                0.2,
                                              height:
                                                Dimensions.get('screen')
                                                  .height * 0.1,
                                            }}
                                            source={{
                                              uri:
                                                `https://file.tima.vn` +
                                                image?.filePath,
                                              priority:
                                                FastImage.priority.normal,
                                            }}
                                            resizeMode={
                                              FastImage.resizeMode.cover
                                            }
                                          />
                                        </TouchableOpacity>
                                      ))}
                                    </ScrollView>
                                  </View>
                                </View>
                              )}
                            </View>
                          ))}
                      </View>
                    ))}
                  </View>
                )}
              </Observer>
            </View>
          </ScrollView>
          <View style={{ paddingHorizontal: 16 }}>
            <Observer>
              {() => (
                <TouchableOpacity
                  disabled={FullSubmitStore.loadingButton}
                  onPress={() => handleSubmit()}
                >
                  <LinearGradient
                    colors={['#FF7A00', '#EF4123']}
                    style={{
                      alignItems: 'center',
                      borderRadius: 30,
                      height: 40,
                      justifyContent: 'center',
                    }}
                  >
                    {FullSubmitStore.loadingButton ? (
                      <ActivityIndicator size={'small'} color="white" />
                    ) : (
                      <MText
                        style={[
                          commonStyles.textNormalBold,
                          { color: '#FFFFFF' },
                        ]}
                      >
                        Hoàn thành
                      </MText>
                    )}
                  </LinearGradient>
                </TouchableOpacity>
              )}
            </Observer>
          </View>
          <View
            style={{
              marginBottom: 8,
              marginTop: 8,
              flexDirection: 'row',
              justifyContent: 'center',
            }}
          >
            <MText style={{ fontSize: 12, color: '#333333' }}>
              Cung cấp bởi{' '}
            </MText>
            <CIMBBank />
          </View>
        </View>
      )}
      <ImageView
        images={images}
        imageIndex={0}
        visible={visible}
        onRequestClose={() => setIsVisible(false)}
      />
      <Loading isLoading={isLoading} />
    </View>
  );
});
