import { rpxToPx } from "@/utils/tools";
import { PickerView, PickerViewColumn, Text, View } from "@tarojs/components";
import { useEffect, useState } from "react";
import './new_timepicker.scss'
import dayjs from "dayjs";
import { MainColorType } from "@/context/themes/color";
import { TimeFormatter } from "@/utils/time_format";

export default function NewDateTimePicker(props: {
    count?: number, date?: string, time?: string, onChange?: any, color?: string,
    minTimestamp?: number,
    maxTimestamp?: number
}) {
    const [items, setItems] = useState<any>([[0], [0], [0]])
    const [values, setValues] = useState<any>([0, 0, 0])
    const [loaded, setLoaded] = useState(false)

    function longDatas() {
        let result: any = []
        var max = props.maxTimestamp ?? new Date().getTime()
        const currentDate = new Date(max)
        currentDate.setHours(23)
        currentDate.setMinutes(59)
        currentDate.setSeconds(59)
        const startDate = new Date(props.minTimestamp!)
        let date = startDate

        const today = dayjs();
        const yesterday = today.subtract(1, 'day');
        while (date <= currentDate) {
            var dt = dayjs(date.getTime())
            var string = global.language == 'en' ? dt.format('MMM D') : dt.format('MMMD日')
            if (TimeFormatter.isToday(date.getTime())) {
                string = (global.language == 'en' ? 'Today' : '今天 ')// + string
            }
            else if (TimeFormatter.isYesterday(date.getTime())) {
                string = (global.language == 'en' ? 'Yesterday' : '昨天 ')// + string
            }
            else if (TimeFormatter.isTimestampInThisWeek(date.getTime())){
                string = dt.format('dddd')
            }
            debugger
            result.push(string)
            date.setDate(date.getDate() + 1)
        }
        debugger
        return result
    }

    function longValues() {
        if (props.date) {
            var obj = dayjs(props.date)
            const startDate = new Date(props.minTimestamp!)
            let date = startDate
            for (var i = 0; i < longDatas().length; i++) {

                var dt = dayjs(date.getTime())
                if (dt.isSame(obj, 'day') && dt.isSame(obj, 'month') && dt.isSame(obj, 'year')) {
                    return i
                }
                date.setDate(date.getDate() + 1)
            }



        }
        return 0
    }


    useEffect(() => {
        loadData()
    }, [props.count])

    function loadData(){
        var hours: any = []
        var tempValues: any = [longValues(), 0, 0]
        var str = props.time ? props.time : dayjs().format('HH:mm')
        var tempHour = str.split(':')[0]
        var tempMinute = str.split(':')[1]
        for (var i = 0; i <= 23; i++) {
            var str = (i + '').padStart(2, '0')
            if (str == tempHour) {
                tempValues[1] = i
            }
            hours.push(str)
        }
        var minutes: any = []
        for (var i = 0; i <= 59; i++) {
            var str = (i + '').padStart(2, '0')
            if (str == tempMinute) {
                tempValues[2] = i
            }
            minutes.push(str)
        }
        // var dates = ['Today', 'Yesterday', 'Dec 31']
        setItems([longDatas(), hours, minutes])
        setValues(tempValues)
        setLoaded(true)
    }

    useEffect(() => {
        var hours: any = []
        var tempValues: any = [longValues(), 0, 0]
        var str = props.time ? props.time : dayjs().format('HH:mm')
        var tempHour = str.split(':')[0]
        var tempMinute = str.split(':')[1]
        for (var i = 0; i <= 23; i++) {
            var str = (i + '').padStart(2, '0')
            if (str == tempHour) {
                tempValues[1] = i
            }
            hours.push(str)
        }
        var minutes: any = []
        for (var i = 0; i <= 59; i++) {
            var str = (i + '').padStart(2, '0')
            if (str == tempMinute) {
                tempValues[2] = i
            }
            minutes.push(str)
        }
        setValues(tempValues)
    }, [props.date, props.time])

    function onPickerChange(e) {
        setValues(e.detail.value)
        if (props.onChange) {
            var list = e.detail.value
            var timestamp = props.minTimestamp! + list[0] * 24 * 3600 * 1000
            var strDate = dayjs(timestamp).format('YYYY-MM-DD')

            var strTime = (list[1] + '').padStart(2, '0') + ':' + (list[2] + '').padStart(2, '0')
            props.onChange([strDate, strTime])
        }
    }

    function getColor(i, j) {
        if (i == 0 && j == values[0]) {
            return true
        }
        if (i == 1 && j == values[1]) {
            return true
        }
        if (i == 2 && j == values[2]) {
            return true
        }
        return false
    }
    if (!loaded) return <View />

    const bgStyle = `background-color: ${props.color}0D !important;`
    return <PickerView
        value={values}
        // itemStyle={{ color: '#000' }}
        style={{ color: '#000', height: rpxToPx(340), width: rpxToPx(578) }}
        onChange={onPickerChange}
        indicatorClass="pick_sel_item"
        indicatorStyle={bgStyle}//""
        immediateChange={true}
        className="picker"
    // maskClass={props.hideTitle?"picker-mask-small":"picker-mask"}
    >
        {
            items.map((item, index) => {
                return <PickerViewColumn key={index}>
                    {item.map((obj, j) => {
                        return (
                            <Text key={j} className="item_text" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', color: getColor(index, j) ? props.color ?? MainColorType.fast : '#000' }}>{obj}</Text>
                        );
                    })}
                </PickerViewColumn>
            })
        }

    </PickerView >
}