import * as React from 'react'
import {View, StyleSheet, TouchableOpacity, Text, ScrollView, TextInput, Image, DeviceEventEmitter} from 'react-native'
import {
    BirthdayDetailRefreshNotify,
    BirthdayEditName,
    BirthdayRefreshNotify,
    RootStackScreenProps,
} from '../../Common/define/Defines'
import BirthdaySelectDateAlert from './BirthdaySelectDateAlert'
import BirthdaySelectTimeAlert from './BirthdaySelectTimeAlert'
import {isString} from '../../Common/tool/TypeTool'
import PYResultTips from '../../Common/alert/PYResultTips'
import Lunar from '../../Common/Solar&Lunar/Lunar'
import Solar from '../../Common/Solar&Lunar/Solar'
import BirthdayData from '../data/BirthdayData'
import LunarSolarTransform from '../../Common/Solar&Lunar/LunarSolarTransform'
import LunarSolarHelper from '../../Common/Solar&Lunar/LunarSolarHelper'
import BirthdayDataManager from '../data/BirthdayDataManager'

interface StateType {
    name: string
    remark: string
    year: number
    month: number
    day: number
    hour: number
    minute: number
    id: number
    isLunar: boolean
    isSecondLeapMonth: boolean
}

export default class BirthdayEdit extends React.Component<RootStackScreenProps<'BirthdayEditName'>, StateType> {
    dateSelectRef: BirthdaySelectDateAlert | null = null
    timeSelectRef: BirthdaySelectTimeAlert | null = null
    nameInputRef: TextInput | null = null
    remarkInputRef: TextInput | null = null
    tipsRef: PYResultTips | null = null
    constructor(props: any) {
        super(props)
        const data = this._getBirthdayData()
        const birthday = data?.birthday || 0
        const date = new Date(birthday)
        const solar = Solar.createByDate(date)
        const lunar = LunarSolarTransform.solarToLunar(solar)
        const isLunar = data?.isLunar || false
        this.state = {
            name: data?.name || '',
            remark: data?.remark || '',
            id: data?.id || -1,
            year: isLunar ? lunar.year : solar.year,
            month: isLunar ? lunar.month : solar.month,
            day: isLunar ? lunar.day : solar.day,
            hour: date.getHours(),
            minute: date.getMinutes(),
            isLunar: isLunar,
            isSecondLeapMonth: isLunar ? lunar.isSecondLeapMonth : false,
        }

        const navigation = this.props.navigation
        navigation.setOptions({
            title: '编辑生日',
            headerLeft: this._headerLeft.bind(this),
            headerRight: this._headerRight.bind(this),
        })
    }

    _headerLeft = () => {
        return (
            <TouchableOpacity style={styles.naviBackBtn} onPress={this._onPressNaviBackBtn.bind(this)}>
                <Image style={styles.naviBackBtnImg} source={require('../../Common/img/back_white_icon.png')} />
            </TouchableOpacity>
        )
    }

    _onPressNaviBackBtn = () => {
        const navigation = this.props.navigation
        navigation.pop(1)
    }

    _headerRight = () => {
        return (
            <TouchableOpacity style={styles.saveBtn} onPress={this._onPressSave.bind(this)}>
                <Text style={styles.saveBtnTitle}>{'保存'}</Text>
            </TouchableOpacity>
        )
    }

    _onPressSave = async () => {
        const id = this.state.id
        if (id === -1) {
            return
        }
        const name = this.state.name
        if (!isString(name) || name.length <= 0) {
            this.tipsRef?.show('请输入姓名', false)
            return
        }
        const isLunar = this.state.isLunar
        const year = this.state.year
        const month = this.state.month
        const day = this.state.day
        let solar = new Solar(year, month, day)
        if (isLunar) {
            const lunar = new Lunar(year, month, day, this.state.isSecondLeapMonth)
            solar = LunarSolarTransform.lunarToSolar(lunar)
        }
        const hour = this.state.hour
        const minute = this.state.minute
        const birthday = solar.getTimeInterval() + hour * 3600 * 1000 + minute * 60 * 1000
        const birthdayData = new BirthdayData(id, name, this.state.remark, birthday, isLunar)
        await BirthdayDataManager.updateData(birthdayData)
        DeviceEventEmitter.emit(BirthdayRefreshNotify)
        DeviceEventEmitter.emit(BirthdayDetailRefreshNotify)
        const navigation = this.props.navigation
        navigation.pop(2)
    }

    render() {
        return (
            <ScrollView style={styles.scrollView}>
                {this._renderNameInput()}
                {this._renderDateSelect()}
                {this._renderTimeSelect()}
                {this._renderRemarkInput()}
                {this._renderDateSelectAlert()}
                {this._renderTimeSelectAlert()}
                {this._renderResultTips()}
                {this._renderDeleteBtn()}
            </ScrollView>
        )
    }

    _renderNameInput = () => {
        return (
            <View style={styles.container}>
                <Text style={styles.itemLbl}>{'姓名'}</Text>
                <TextInput
                    ref={e => (this.nameInputRef = e)}
                    style={styles.input}
                    placeholder={'请输入姓名（必填）'}
                    placeholderTextColor={'#aaaaaa'}
                    value={this.state.name}
                    onChangeText={this._onChangeName.bind(this)}
                />
                <View style={styles.separateLine} />
            </View>
        )
    }

    _onChangeName = (name: string) => {
        this.setState({
            name: name,
        })
    }

    _renderDateSelect = () => {
        let dateStr: string = ''
        if (this.state.isLunar) {
            const lunar = new Lunar(this.state.year, this.state.month, this.state.day, this.state.isSecondLeapMonth)
            dateStr = lunar.getInputDisplayStr()
        } else {
            const solar = new Solar(this.state.year, this.state.month, this.state.day)
            dateStr = solar.getInputDisplayStr()
        }
        return (
            <View style={styles.container}>
                <Text style={styles.itemLbl}>{'生日'}</Text>
                <TouchableOpacity style={styles.itemBtn} onPress={this._onPressDate.bind(this)}>
                    <Text style={styles.itemBtnTitle}>{dateStr}</Text>
                </TouchableOpacity>
                <View style={styles.separateLine} />
            </View>
        )
    }

    _onPressDate = () => {
        this.dateSelectRef?.show(
            this.state.year,
            this.state.month,
            this.state.day,
            this.state.isLunar,
            this.state.isSecondLeapMonth,
        )
    }

    _renderDateSelectAlert = () => {
        return <BirthdaySelectDateAlert ref={e => (this.dateSelectRef = e)} onSelect={this._onSelectDate.bind(this)} />
    }

    _onSelectDate = (year: number, month: number, day: number, isLunar: boolean, isSecondLeapMonth: boolean) => {
        this.setState({
            year: year,
            month: month,
            day: day,
            isLunar: isLunar,
            isSecondLeapMonth: isSecondLeapMonth,
        })
    }

    _renderTimeSelect = () => {
        const zhiName = LunarSolarHelper.getHourName(this.state.hour)
        const hourStr = String(this.state.hour).padStart(2, '0')
        const minuteStr = String(this.state.minute).padStart(2, '0')
        const timeStr = hourStr + ':' + minuteStr + '（' + zhiName + '）'
        return (
            <View style={styles.container}>
                <Text style={styles.itemLbl}>{'时间'}</Text>
                <TouchableOpacity style={styles.itemBtn} onPress={this._onPressTime.bind(this)}>
                    <Text style={styles.itemBtnTitle}>{timeStr}</Text>
                </TouchableOpacity>
                <View style={styles.separateLine} />
            </View>
        )
    }

    _onPressTime = () => {
        this.timeSelectRef?.show(this.state.hour, this.state.minute)
    }

    _renderTimeSelectAlert = () => {
        return <BirthdaySelectTimeAlert ref={e => (this.timeSelectRef = e)} onSelect={this._onSelectTime.bind(this)} />
    }

    _onSelectTime = (hour: number, minute: number) => {
        this.setState({
            hour: hour,
            minute: minute,
        })
    }

    _renderRemarkInput = () => {
        return (
            <View style={styles.container}>
                <Text style={styles.itemLbl}>{'备注'}</Text>
                <TextInput
                    ref={e => (this.remarkInputRef = e)}
                    style={styles.input}
                    placeholder={'描述一下你们的关系（选填）'}
                    placeholderTextColor={'#aaaaaa'}
                    value={this.state.remark}
                    onChangeText={this._onChangeRemark.bind(this)}
                />
                <View style={styles.separateLine} />
            </View>
        )
    }

    _onChangeRemark = (remark: string) => {
        this.setState({
            remark: remark,
        })
    }

    _renderResultTips = () => {
        return <PYResultTips ref={e => (this.tipsRef = e)} />
    }

    _renderDeleteBtn = () => {
        return (
            <TouchableOpacity style={styles.deleteBtn} onPress={this._onPressDelete.bind(this)}>
                <Text style={styles.deleteBtnTitle}>{'删除'}</Text>
            </TouchableOpacity>
        )
    }

    _onPressDelete = async () => {
        const id = this.state.id
        if (id === -1) {
            return
        }
        await BirthdayDataManager.removeData(id)
        DeviceEventEmitter.emit(BirthdayRefreshNotify)
        const navigation = this.props.navigation
        navigation.pop(2)
    }

    _getBirthdayData = (): BirthdayData | null => {
        const routes = this.props.navigation.getState().routes
        let data: BirthdayData | null = null
        for (let i = 0; i < routes.length; i++) {
            const route = routes[i]
            if (route.name === BirthdayEditName) {
                data = route.params as BirthdayData
                break
            }
        }
        return data
    }
}

const styles = StyleSheet.create({
    scrollView: {
        flex: 1,
        paddingTop: 10,
    },
    container: {
        width: '100%',
        height: 55,
        paddingHorizontal: 15,
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: 'white',
    },
    itemLbl: {
        width: 70,
        fontSize: 17,
        color: '#191919',
    },
    separateLine: {
        left: 85,
        right: 25,
        position: 'absolute',
        backgroundColor: '#e8e8e8',
        bottom: 0,
        height: 1,
    },
    input: {
        height: 55,
        width: '100%',
        fontSize: 17,
        marginRight: 25,
    },
    itemBtn: {
        height: 55,
        width: '100%',
        marginRight: 25,
        justifyContent: 'center',
    },
    itemBtnTitle: {
        fontSize: 17,
        color: '#191919',
    },
    saveBtn: {
        width: 40,
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
    },
    saveBtnTitle: {
        fontSize: 17,
        color: '#191919',
    },
    naviBackBtn: {
        width: 40,
        height: 40,
        justifyContent: 'center',
    },
    naviBackBtnImg: {
        width: 24,
        height: 24,
        resizeMode: 'contain',
        tintColor: '#191919',
    },
    deleteBtn: {
        borderRadius: 5,
        marginTop: 15,
        marginLeft: 15,
        marginRight: 15,
        height: 40,
        backgroundColor: '#FF464A',
        justifyContent: 'center',
        alignItems: 'center',
    },
    deleteBtnTitle: {
        fontSize: 17,
        color: 'white',
    },
})
