import React, { Component } from 'react'
import { View, FlatList, Alert, StyleSheet, SafeAreaView, StatusBar, Dimensions, } from 'react-native'
import { StackNavigationProp, } from '@react-navigation/stack'
import RNFS from 'react-native-fs'
import { SwipeListView } from 'react-native-swipe-list-view'
import { store } from '../../redux/store'
import { LangGlobalModalAC, } from '../../redux/actionCreators'
import FileViewer from 'react-native-file-viewer'
import { StorageService, } from '../../others'
import { MyVideoMobM, } from '../../models/mobileModels'
import Sound from 'react-native-sound'
import c from '../../color/colors'
import t from '../../translator/translator'

import { MyText, } from '../../components/texts'
import BasePage from '../BasePage'
import TabPagePageViewer from '../../components/pageViewers/TabPagePageViewer'
import TabHeaderView from '../../components/headers/TabHeaderView'
import TitleView from './TitleView'
import EmptyTextView from './EmptyTextView'
import ItemView from './itemView/ItemView'


type Props = {
    navigation: StackNavigationProp<''>,
}


export default class Tab_4_Page extends BasePage<Props>
{
    isAlertShow: Boolean = false

    state: {
        myVideos: MyVideoMobM[]
    }

    constructor(props)
    {
        super(props)
        this.onFocus = this.onFocus.bind(this)
        this.onSwipeValueChange = this.onSwipeValueChange.bind(this)
        this.onPressItem = this.onPressItem.bind(this)

        this.state = {
            myVideos: [],
        }
    }


    componentDidMount()
    {
        this.props.navigation.addListener('focus', this.onFocus)
        this.onFocus()
    }

    componentWillUnmount()
    {
        this.props.navigation.removeListener('focus', this.onFocus)
    }

    onFocus()
    {
        this.getAllVideos()
    }

    async getAllVideos()
    {
        StorageService.getMyVideos()
        .then(myVideos => { this.setState({ myVideos: myVideos || [] }) })
    }


    render()
    {
        return (
            <TabPagePageViewer>

                <StatusBar barStyle={ 'light-content' } backgroundColor={ c().main_black }/>
                <SafeAreaView/>

                <TabHeaderView
                    // title = { t().tab_4 }
                    onPressLang = { () => store.dispatch(LangGlobalModalAC.toggleVisibility(true)) }
                />

                <View style={ styles.container }>

                    <SwipeListView
                        ListEmptyComponent = { <EmptyTextView/> }
                        contentContainerStyle = { styles.scrollCnt }
                        showsVerticalScrollIndicator = { false }
                        ListHeaderComponent = { <TitleView/> }
                        data = { this.state.myVideos }
                        keyExtractor = { (x) => x.name }
                        renderItem = { ({ item, index }) => (
                            <ItemView
                                index = { index }
                                myVideoItem = { item }
                                onPress = { () => this.onPressItem(item) }
                            />
                        ) }
                        onSwipeValueChange = { this.onSwipeValueChange }
                        renderHiddenItem = { (data, rowMap) => (
                            <View style={ styles.deleteTextView }>
                                <MyText style={ styles.deleteText }>{ t().Delete }</MyText>
                            </View>
                        )}
                        previewOpenValue = { -100 }
                        useNativeDriver = { false }
                        disableRightSwipe
                    />

                </View>
            </TabPagePageViewer>
        )
    }


    onSwipeValueChange(swipeData)
    {
        if(this.isAlertShow)
            return

        const { key, value } = swipeData

        if(-value > (Dimensions.get('screen').width - 200))
        {
            const prevIndex = this.state.myVideos.findIndex(x => x.name === key)
            if(prevIndex >= 0)
            {
                this.isAlertShow = true

                Alert.alert(
                    t().Warning,
                    t().AreYouSureYouWantToPerformThisAction,
                    [
                        {
                            text: t().No,
                            onPress: () => this.isAlertShow = false,
                            style: 'cancel'
                        },
                        {
                            text: t().Yes,
                            onPress: () =>
                            {
                                this.isAlertShow = false

                                let item = this.state.myVideos[prevIndex]

                                this.state.myVideos.splice(prevIndex, 1)
                                this.setState({ myVideos: this.state.myVideos })
                                StorageService.saveMyVideos(this.state.myVideos)

                                RNFS.exists(item.path)
                                .then((res) => {
                                    if (res) {
                                        RNFS.unlink(item.path)
                                        .then(() => console.log('FILE DELETED'))
                                    }
                                }).catch(err => console.log('--- err', err))
                            }
                        },
                    ],
                    {
                        cancelable: false,
                    },
                )
            }
        }
    }

    onPressItem(item: MyVideoMobM)
    {
        this.props.navigation.navigate('ShareVideoPage', {
            videoPath: item.path,
            prankType: item.prankType,
            isMyVideosPage: true,
        })
    }

}



const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: c().d_background,
    },
    scrollCnt: {
        paddingBottom: 100,
    },

    deleteTextView: {
        flex: 1,
        marginLeft: 100,
        paddingRight: 16,
        alignItems: 'flex-end',
        justifyContent: 'center',
        backgroundColor: c().main_red,
    },
    deleteText: {
        color: c().main_white,
    },
})
