import React, { memo } from 'react'
import { FlatList, StyleSheet, Text, View } from 'react-native'
import { Asset } from 'expo-media-library'
import styled from 'styled-components/native'

import { ItemType, AssetListPropTypes } from './Types'
import secondToMMSS from '../utils/secondToMMSS'

const Item = ({
    id,
    screen,
    cols,
    selectedIndex,
    uri,
    mediaType,
    onClick,
    margin,
    selectedIcon,
    width,
    height,
    duration
}: ItemType) => {
    const handleClick = () => {
        onClick({ id, uri, mediaType, width, height, duration });
    }

    const {
        Component: SelectedIndicator,
        color: SelectedColor,
        iconName: SelectedIconName,
        size: SelectedIconSize,
        bg: SelectedIconBg,
    } = selectedIcon

    return (
        <ItemContainer
            margin={margin}
            screen={screen}
            cols={cols}
            onPress={handleClick}
        >
            {mediaType === 'video' && (
                <Text style={{ color:'white', position: 'absolute', bottom: 1, zIndex: 1, right: 5 }}>
                    {secondToMMSS(duration)}
                </Text>
            )}

            {selectedIndex >= 0 && (
                <Selected selectionColor={SelectedIconBg} margin={margin}>
                    {SelectedIndicator && SelectedIconName && (
                        <View style={styles.indexContainer}>
                            <Text style={styles.indexNumber}>{selectedIndex + 1}</Text>
                        </View>
                    )}
                </Selected>
            )}
            <Image source={{ uri }} />
        </ItemContainer>
    )
}

const MemoizedAssetItem = memo(Item)

export const AssetList = ({
    margin,
    data,
    selectedItems,
    onClick,
    getMoreAssets,
    cols,
    screen,
    selectedIcon,
    videoIcon,
}: AssetListPropTypes) => {
    const _renderItem = ({ item }: { item: Asset }) => {
        return (
            <MemoizedAssetItem
                id={item.id}
                uri={item.uri}
                mediaType={item.mediaType}
                width={item.width}
                height={item.height}
                selectedIndex={selectedItems.indexOf(item.id)}
                onClick={onClick}
                cols={cols}
                screen={screen}
                margin={margin}
                selectedIcon={selectedIcon}
                videoIcon={videoIcon}
                duration={item.duration}
            />
        )
    }

    const _getItemLayout = (
        data: Asset[] | null | undefined,
        index: number
    ) => {
        let length = screen / cols
        return { length, offset: length * index, index }
    }

    return (
        <FlatList
            data={data}
            numColumns={cols}
            initialNumToRender={50}
            getItemLayout={_getItemLayout}
            renderItem={_renderItem}
            keyExtractor={(item) => item.id}
            extraData={selectedItems}
            onEndReached={() => getMoreAssets()}
            onEndReachedThreshold={0.5}
        />
    )
}

const Image = styled.Image`
    width: 100%;
    height: 100%;
`

const MediaTypeVideo = styled.View<{ margin: number }>`
    width: 25%;
    justify-content: center;
    align-items: center;
    height: 25%;
    position: absolute;
    z-index: 11;
    margin: ${({ margin }) => margin}px;
`
const Selected = styled.View<{ margin: number; selectionColor: string }>`
    position: absolute;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    z-index: 10;
    background-color: ${({ selectionColor }) =>
        selectionColor ? selectionColor : '#B14AC370'};
    margin: ${({ margin }) => margin}px;
`

const ItemContainer = styled.TouchableOpacity<{
    margin: number
    screen: number
    cols: number
}>`
    width: ${({ screen, cols }) => screen / cols}px;
    height: ${({ screen, cols }) => screen / cols}px;
    padding: ${({ margin }) => margin}px;
`

const styles = StyleSheet.create({
    indexContainer: { 
        width: 25, 
        height: 25, 
        backgroundColor: 'dodgerblue', 
        borderRadius: 25 / 2,
        borderWidth: 1,
        borderColor: 'white',
        justifyContent: 'center',
        alignItems: 'center'
    },
    indexNumber: {
        color: 'white'
    }
})