import { View, Text, Image } from '@tarojs/components'
import './post_moment_time.scss'
import NewModal from '../base/new_modal'
import { useState } from 'react'
import { useSelector } from 'react-redux';
import { getScenario, getThemeColor } from '@/features/health/hooks/health_hooks';
import { rpxToPx } from '@/utils/tools';
import NewTimePicker from '../base/new_timepicker';
import { IconCalendar, IconTarget } from '@/components/basic/Icons';
import NewDurationPicker from '../base/new_durationpicker';
import NewButton, { NewButtonType } from '../base/new_button';
import dayjs from 'dayjs';
import Card from './card';
import CellFooter, { CellFooterType } from '../base/cell_footer';
import CellFooterText from '../base/cell_footer_text';
import ChooseDateTime from './choose_date_time';
import { MainColorType } from '@/context/themes/color';
import Taro from '@tarojs/taro';
import { useTranslation } from 'react-i18next';

let isYesterdayTarget = false
export default function PostMomentTime(props: {
    title?: string,
    date?: string,
    time: string,
    isTemp: boolean,
    onChange: any,
    moment?: any,
    dismiss: any
}) {
    const health = useSelector((state: any) => state.health);
    const [showDurationPicker, setShowDurationPicker] = useState(false)
    const [isYesterday, setIsYesterday] = useState(false)
    const [selDate, setSelDate] = useState(props.date ? props.date : dayjs().format('YYYY-MM-DD'))
    const [showMore, setShowMore] = useState(false)
    const [time, setTime] = useState(props.time)
    const [minutes, setMinutes] = useState(30)
    const { t } = useTranslation()

    function durationTime() {
        var hour = Math.floor(minutes / 60)
        var minute = minutes % 60
        var str = ''
        if (hour > 0) {
            if (global.language == 'en') {
                str = hour + (hour == 1 ? ' hr ' : ' hrs ')
            }
            else {
                str = hour + '小时'
            }

        }
        if (minute > 0) {
            if (global.language == 'en') {
                str += minute + ' mins'
            }
            else {
                str += minute + '分钟'
            }

        }
        if (hour == 0 && minute == 0) {
            if (global.language == 'en') {
                str = '0 mins'
            }
            else {
                str = '0分钟'
            }

        }
        return str
    }

    function endTime() {
        var now = new Date()
        var hour = parseInt(time.split(':')[0] + '')
        var minute = parseInt(time.split(':')[1] + '')
        now.setHours(hour)
        now.setMinutes(minute)
        var timestamp = now.getTime()
        if (isYesterday) {
            timestamp = timestamp - 24 * 3600 * 1000
        }
        timestamp = timestamp + minutes * 60 * 1000

        const today = dayjs();
        const dt = dayjs(timestamp);
        var strTime = dt.format('HH:mm ')
        const yesterday = today.subtract(1, 'day');
        const tomorrow = today.subtract(-1, 'day');

        if (dt.isSame(today, 'day')) {
            return strTime + 'Today';
        } else if (dt.isSame(yesterday, 'day')) {
            return strTime + 'Yesterday';
        } else if (dt.isSame(tomorrow, 'day')) {
            return strTime + 'Tomorrow';
        } else {
            return strTime + dt.format('MM-DD');
        }
    }

    function durationContent() {
        return <View style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            <Card>
                <View style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                    <View className='picker_time_card_header'>
                        <View style={{ width: rpxToPx(40) }} />
                        <Text>Duration</Text>
                        <View style={{ flex: 1 }} />
                        <NewButton
                            type={showDurationPicker ? NewButtonType.alpha : NewButtonType.gray}
                            color={getThemeColor(health.mode)}
                            title={durationTime()}
                            height={rpxToPx(84)}
                            fontNormal
                            onClick={() => {
                                setShowDurationPicker(true)
                            }}
                        />
                        <View style={{ width: rpxToPx(28) }} />
                        <View className='border_footer_line' style={{ left: rpxToPx(40) }} />
                    </View>
                    {
                        showDurationPicker && <NewDurationPicker
                            value={minutes}
                            color={getThemeColor(health.mode)}
                            onChange={(v) => {
                                setMinutes(v)
                            }} />
                    }


                </View>
            </Card>
            <CellFooter
                type={CellFooterType.center}
            >
                <CellFooterText text={`Expect to finish at ${endTime()}`} />
            </CellFooter>
        </View>
    }

    function getMinTimestamp() {
        var scenario = getScenario(health.windows, health.mode)
        return scenario.picker_min_timestamp
    }

    /*
    type={expandIndex == index ? NewButtonType.alpha : NewButtonType.gray}
                    color={iFast ? MainColorType.fast : MainColorType.sleep}
    */
    return <NewModal
        title={props.title ?? '开始时间'}
        dismiss={props.dismiss}
        confirm={() => {
            var date = new Date(selDate + ' ' + time + ':00')
            var now = new Date()
            if (date.getTime() > now.getTime()) {
                setTime(dayjs(now.getTime()).format('HH:mm'))
                Taro.showToast({
                    title: t('health.future_time_limit'),
                    icon: 'none'
                })
                return
            }

            props.onChange({
                date: selDate,
                time: time,
                duration: minutes,
                isYesterday: isYesterday
            })
        }}
        themeColor={getThemeColor(health.mode)}>
        <Card>
            <ChooseDateTime title={null}
                disable={false}
                color={getThemeColor(health.mode)}
                expand={!showDurationPicker}
                choose={() => {
                    setShowDurationPicker(false)
                }}
                time={time}
                // timeChange={(e) => {
                //     setTime(e)
                // }}
                minTimestamp={getMinTimestamp()}

                // footerTitle={scheduleTime()}
                enterTimestamp={global.set_time}
                targetTimestamp={props.moment && props.moment.target ? props.moment.target.timestamp : new Date().getTime()}

                // tapFooter={() => {
                //     if (time == dayjs(props.moment.target.timestamp).format('HH:mm')) {
                //         setSelDate(dayjs(global.set_time).format('YYYY-MM-DD'))
                //         setTime(dayjs(global.set_time).format('HH:mm'))
                //     }
                //     else {
                //         setSelDate(dayjs(props.moment.target.timestamp).format('YYYY-MM-DD'))
                //         setTime(dayjs(props.moment.target.timestamp).format('HH:mm'))
                //     }

                // }}
                date={selDate}
                change={(e) => {
                    setSelDate(e[0])
                    setTime(e[1])
                }}
            // dateChange={(e) => {
            //     setSelDate(e)
            // }}
            />
        </Card>
        {/* <Card>
            <View style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                <View className='picker_time_card'>
                    <View className='picker_time_card_header'>
                        <View style={{ flex: 1 }} />
                        <NewButton
                            type={NewButtonType.gray}
                            title={isYesterday ? 'Yesterday' : 'Today'}
                            height={rpxToPx(84)}
                            onClick={() => {
                                setIsYesterday(!isYesterday)
                            }}
                        />
                        <View style={{ width: rpxToPx(12) }} />
                        <NewButton
                            type={!showDurationPicker ? NewButtonType.alpha : NewButtonType.gray}
                            color={getThemeColor(health.mode)}
                            title={time}
                            height={rpxToPx(84)}
                            onClick={() => {
                                setShowDurationPicker(false)
                            }}
                        />
                        <View style={{ flex: 1 }} />
                        {
                            !showDurationPicker && <View className='border_footer_line' style={{
                                left: rpxToPx(40),
                                right: rpxToPx(40)
                            }} />
                        }
                    </View>
                    {
                        !showDurationPicker && <NewTimePicker time={time} onChange={(e) => {
                            setTime(e)
                        }} color={getThemeColor(health.mode)} />
                    }
                    {
                        !props.isTemp && !showDurationPicker && <View className='picker_time_card_footer' onClick={() => {
                            if (time == dayjs(props.moment.target.timestamp).format('HH:mm')) {
                                setIsYesterday(false)
                                setTime(dayjs(global.set_time).format('HH:mm'))
                            }
                            else {
                                setIsYesterday(isYesterdayTarget)
                                setTime(dayjs(props.moment.target.timestamp).format('HH:mm'))
                            }

                        }}>
                            <IconCalendar width={rpxToPx(24)} color='#5C7099' />
                            <Text style={{ color: '#5C7099', marginLeft: rpxToPx(12), fontSize: rpxToPx(26) }}>{scheduleTime()}</Text>
                        </View>
                    }

                </View>

            </View>

        </Card> */}
        <View style={{ marginTop: rpxToPx(36), display: 'flex', flexDirection: 'column', alignItems: showMore ? 'flex-start' : 'center' }}>
            {
                showMore ? durationContent() :
                    <NewButton
                        onClick={() => setShowMore(true)}
                        type={NewButtonType.link}
                        title={global.language == 'en' ? 'Show More' : '查看更多'}
                    />
            }

        </View>
    </NewModal>

}