import * as React from 'react'
import {StyleSheet, ScrollView, DeviceEventEmitter} from 'react-native'
import {
    BirthdayRefreshNotify,
    BirthdaySortKey,
    BirthdaySortTypeDate,
    BirthdaySortTypeName,
    BirthdaySortTypeRemainDays,
    RootTabScreenProps,
    TabPressNotify,
} from '../../Common/define/Defines'
import BirthdaySettingsItem from './BirthdaySettingsItem'
import BirthdaySortSheet from './BirthdaySortSheet'
import StorageTool from '../../Common/tool/StorageTool'

type StateType = {
    sortType: string
}

export default class BirthdaySettings extends React.Component<RootTabScreenProps<'BirthdaySettingsName'>, StateType> {
    sortSheetRef: BirthdaySortSheet | null = null
    constructor(props: any) {
        super(props)
        this.state = {
            sortType: BirthdaySortTypeDate,
        }
    }

    componentDidMount(): void {
        // 第一次点击时监听不到
        this._onTabPress()
        const navigation = this.props.navigation
        navigation.addListener(TabPressNotify, this._onTabPress.bind(this))
    }

    componentWillUnmount(): void {
        const navigation = this.props.navigation
        navigation.removeListener(TabPressNotify, this._onTabPress.bind(this))
    }

    _onTabPress = async () => {
        const sortType = (await StorageTool.getStr(BirthdaySortKey)) || BirthdaySortTypeDate
        this.setState({
            sortType: sortType,
        })
    }

    render() {
        return (
            <ScrollView style={styles.container}>
                <BirthdaySettingsItem
                    title={'排序方式'}
                    info={this.state.sortType}
                    onPress={this._onPressItem.bind(this)}
                />
                <BirthdaySortSheet
                    ref={e => (this.sortSheetRef = e)}
                    data={[BirthdaySortTypeDate, BirthdaySortTypeName, BirthdaySortTypeRemainDays]}
                    onSelectItem={this._onSelectItem.bind(this)}
                />
            </ScrollView>
        )
    }

    _onPressItem = (title: string) => {
        if (title === '排序方式') {
            this.sortSheetRef?.show()
        }
    }

    _onSelectItem = async (str: string) => {
        await StorageTool.saveStr(BirthdaySortKey, str)
        this.setState({
            sortType: str,
        })
        DeviceEventEmitter.emit(BirthdayRefreshNotify)
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        paddingTop: 10,
    },
})
