
import React from 'react';
import {
    ActivityIndicator,
    Dimensions,
    GestureResponderEvent,
    Image,
    ImageStyle,
    StyleSheet,
    Text,
    TextStyle,
    TouchableOpacity,
    View,
    ViewStyle,
} from 'react-native';
import { IStyledProps } from '../common/types';
import { IFile } from '../../store/sharedFile/types';
import { IPeer, PeerType } from '../../store/peer/types';
import { sharedFilesService } from '../../services/sharedFiles';
import FontAwesomeIcon from 'react-native-vector-icons/FontAwesome'
import moment from 'moment';
import { DataProvider, LayoutProvider, RecyclerListView } from 'recyclerlistview';
import { Strings } from '../../resources/localization/Strings'
import { Divider } from 'react-native-paper';
export interface IProps extends IStyledProps<IShardFilesStyleProps> {
    peer: IPeer;
    sharedFileArray: IFile[];
    isLoading: boolean;
    renderFilesItems?: (files: IFile[]) => React.ReactElement;
    onFileItemClicked?: (item: IFile) => void;
    onEndReached?: () => void;
    renderFooter?: () => React.JSX.Element | React.JSX.Element[] | null;
}
export interface IShardFilesStyleProps {
    container?: ViewStyle;
    fileItemContainer?: ViewStyle;
    fileItemImage?: ImageStyle;
    fileItemInfoView?: ViewStyle;
    fileItemName?: TextStyle;
    fileItemDate?: TextStyle;
    spinner?: ViewStyle;
    footerView?: ViewStyle;
}
export const SharedFilesContainer: React.FunctionComponent<IProps> = ({
    style,
    peer,
    isLoading,
    sharedFileArray,
    renderFilesItems,
    onFileItemClicked,
    onEndReached,
    renderFooter
}) => {
    const mergedStyle = { ...defaultStyle, ...(style as IShardFilesStyleProps) };
    const isBubble = peer.type === PeerType.Bubble;


    const renderItems = (_type: string | number, item: IFile) => {
        const fileName = item.name.length >= 20 ? item.name?.slice(0, 20) + ' ...' : item.name;
        return (
            <View style={mergedStyle.container}>
                <TouchableOpacity onPress={handleItemClicked(item)} style={{ overflow: 'hidden' }}>
                    <View style={mergedStyle.row}>
                            {displayPreview(item.ImagePreview)}
                            <View style={mergedStyle.textContainer}>
                                <Text style={mergedStyle.fileName}>{fileName}</Text>
                                <Text style={mergedStyle.fileDetails}>
                                    {formatBytes(item.size)} -{moment(item.date, 'ddd MMM DD HH:mm:ss YYYY').format('MMM DD, YYYY')}
                                </Text>
                        </View>
                    </View>
                    <Divider style={mergedStyle.divider} />
                </TouchableOpacity>
            </View>
        );
    }
    const handleItemClicked = (item: IFile) => (_event: GestureResponderEvent) => {
        if (onFileItemClicked) {
            onFileItemClicked(item);
        }
    }

    const displayPreview = (imagePreview: string) => {
        if (imagePreview == null) {
            return <FontAwesomeIcon name="file-text" style={{ fontSize: 35, color: '#3f8df5', margin:10 }} />
        } else {
            return
            <Image
                resizeMode="contain"
                style={defaultStyle.fileItemImage}
                source={{ uri: `data:image/png;base64,${imagePreview}` }}
            />
        }
    }
    const formatBytes = (bytes: number, decimals = 2) => {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const dm = decimals < 0 ? 0 : decimals;
        const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
    }

    const layoutProvider = new LayoutProvider(() => 'ALLFILES',
        (type: any, dim: { width: number; height: number }) => {
            const width = Dimensions.get('window').width;
            const height = 80;
            switch (type) {
                case 'ALLFILES':
                    dim.width = width;
                    dim.height = height;
                    break;
                default:
                    dim.width = width;
                    dim.height = 0;
            }
        }
    );
    const renderEmptyList = () => {
        return (
            <View style={mergedStyle.noDataMessageView}>
                <Text style={mergedStyle.noDataMessageText}>{Strings.noDataFound}</Text>
            </View>
        );
    };
    const dataProvider = new DataProvider((r1: any, r2: any) => {
        return r1 !== r2;
    }).cloneWithRows(sharedFileArray);

    const onEndScrollReached = () => {
        if (onEndReached) {
            onEndReached();
        }
        else {
            sharedFilesService.loadMoreSharedFiles(peer.jId, isBubble);
        }
    }

    const renderListFooter = () => {
        if (renderFooter) {
            return renderFooter();
        }
        else {
            if (sharedFileArray.length > 10) {
                return (
                    <View style={mergedStyle.footerView} >
                        <ActivityIndicator size="large" style={defaultStyle.spinner} />
                    </View>
                );
            } else {
                return null;
            }

        }
    }

    const renderDefaultAllFilesListView = () => {
        console.log('sharedFileArray', sharedFileArray);
        const isEmptySharedFileArray = sharedFileArray.length === 0;
        if (isEmptySharedFileArray && !isLoading) {
            return renderEmptyList();
        }
        else {
            return (
                <>
                    {isLoading && <ActivityIndicator size="large" color="blue" style={defaultStyle.spinner} />}
                    {!isEmptySharedFileArray && <RecyclerListView
                        layoutProvider={layoutProvider}
                        dataProvider={dataProvider}
                        rowRenderer={renderItems}
                        onEndReached={onEndScrollReached}
                        onEndReachedThreshold={0.2}
                    // renderFooter={renderListFooter}
                    />}
                </>
            );
        }
    }

    if (renderFilesItems) {
        return renderFilesItems(sharedFileArray);
    }
    else {
        return renderDefaultAllFilesListView();
    }
}

const defaultStyle = StyleSheet.create({
    container: {
        flex: 1
    },
    row: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        width: '100%',
        alignContent: 'flex-start',
    },
    fileItemImage: {
        width: 40,
        height: 40,
        margin: 10,
    },
    textContainer: {
        flex: 1, // take remaining space
        flexDirection: 'column',
        justifyContent: 'center',
        marginLeft: 12,
    },
    fileName: {
        fontSize: 16,
    },
    fileDetails: {
        fontSize: 12,
        color: '#6e6e6e',
    },
    divider: {
        marginVertical: 8,
        backgroundColor: '#ccc',
        height: 1,
    },
    spinner: {
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        justifyContent: 'center',
        alignItems: 'center'
    },

    noDataMessageView: {
        fontSize: 25,
        justifyContent: 'center',
        flex: 1,
        marginTop: 100,
    },
    noDataMessageText: {
        textAlign: 'center',
    },
    footerView: {
        flex: 1, backgroundColor: '#E6E6E6', height: 80
    }
});
