import { View, Image, Text } from "@tarojs/components";
import './FoodTimelineItem.scss'
import Taro from "@tarojs/taro";
import { useTranslation } from "react-i18next";
import { editFoodJournal } from "@/services/foodJournal";
import { useEffect, useState } from "react";
import LimitPickers from "@/components/input/LimitPickers";
import Modal from "@/components/layout/Modal";
import { ColorType } from "@/context/themes/color";
import { useSelector } from "react-redux";
import PickerViews from "@/components/input/PickerViews";

export default function Component(props: { data: any, index: number, delete: Function, preview: Function, update: Function }) {
    const common = useSelector((state: any) => state.common);
    const [detail, setDetail] = useState(props.data)
    const [count, setCount] = useState(0)
    const [showModal, setShowModal] = useState(false)
    const [showTagModal, setShowTagModal] = useState(false)
    const [isStart, setIsStart] = useState(false)
    const { t } = useTranslation()

    useEffect(() => {
        setDetail(props.data)
    }, [props.data])

    function preview() {
        // Taro.previewImage({
        //     current: props.data.cover,
        //     urls: [props.data.cover]
        // })
        props.preview()
    }

    function showActionSheet() {
        Taro.showActionSheet({
            itemList: [t('feature.common.action_sheet.delete')]
        })
            .then(res => {
                switch (res.tapIndex) {
                    case 0:
                        Taro.showModal({
                            title: t('feature.common.modal.delete_item_title'),
                            content: t('feature.common.modal.delete_item_content'),
                            success: function (res) {
                                if (res.confirm) {
                                    props.delete();
                                }
                            }
                        })
                        break;
                }
            })
            .catch(err => {
                console.log(err.errMsg)
            })
    }

    function operateActionSheet() {
        Taro.showActionSheet({
            alertText: t('feature.food.action_sheet.title'),
            itemList: [t('feature.food.action_sheet.tag'),
            t('feature.food.action_sheet.start_time'),
            t('feature.food.action_sheet.end_time')]
        })
            .then(res => {
                switch (res.tapIndex) {
                    case 0:
                        setShowTagModal(true)
                        break;
                    case 1:
                        {
                            global.set_time = new Date().getTime()
                            setIsStart(true)
                            setShowModal(true)
                        }
                        break;
                    case 2:
                        {
                            global.set_time = new Date().getTime()
                            setIsStart(false)
                            setShowModal(true)
                        }
                        break;
                }
            })
            .catch(err => {
                console.log(err.errMsg)
            })
    }

    function updateTag(index) {
        var tag = common.meal_tags[index]
        editFoodJournal({
            meal_tag: {
                code: tag.code
            }
        }, detail.id).then(res => {
            var obj = detail
            // obj.tags = [tag]
            obj.meal_tag = {
                code: tag.code,
                label: tag.label
            }
            setDetail(obj)
            setCount(count + 1)

            props.update(res)
        }).catch(e => {

        })
    }

    function updateTime(e) {
        var date = new Date(e)
        var year = date.getFullYear()
        var month = date.getMonth() + 1
        var day = date.getDate()
        var obj: any;
        obj = {
            start: {
                date: (year + '') + (month < 10 ? '0' + month : month) + (day < 10 ? '0' + day : day),
                timestamp: e
            }
        }
        if (!isStart) {
            obj = {
                end: {
                    date: (year + '') + (month < 10 ? '0' + month : month) + (day < 10 ? '0' + day : day),
                    timestamp: e
                }
            }
        }

        editFoodJournal({
            ...obj
        }, detail.id).then(res => {
            setDetail(res)
            setCount(count + 1)
            props.update(res)
        }).catch(e => {

        })
    }

    function getTime(t) {
        var date = new Date(t)
        var hour = date.getHours()
        var minute = date.getMinutes()
        return (hour < 10 ? '0' + hour : hour) + ':' + (minute < 10 ? '0' + minute : minute)
    }

    function pickerTagIndex() {
        var list = common.meal_tags
        if (detail.meal_tag) {
            for (var i = 0; i < list.length; i++) {
                if (list[i].label == detail.meal_tag.label) {
                    return i;
                }
            }
        }

        return 0;
    }

    function pickerTagItems() {
        var list = common.meal_tags
        var tags: any = []
        list.map(item => {
            tags.push(item.label)
        })
        return [tags];
    }

    function tagChanged(data) {
        setShowTagModal(false)
        updateTag(data[0])
    }

    function getPickerLimit() {
        if (isStart) {
            return new Date().getTime() - 7 * 24 * 3600 * 1000
        }
        else {
            return detail.start.timestamp
        }
    }

    function getPickerInitValue() {
        if (isStart) {
            return detail.start.timestamp
        }
        else {
            return detail.end.timestamp ? detail.end.timestamp : new Date().getTime()
        }
    }

    return <View className="food_timeline_item" onLongPress={showActionSheet}>
        {/* <View className="thumb" style={{backgroundColor:'pink'}}/> */}
        <View className="tags">
            {
                props.index == 0 && !detail.meal_tag && common.meal_tags.map((item, index) => {
                    return <Text onClick={() => updateTag(index)}>{item.label}</Text>
                })
            }
        </View>
        <View className="thumb_bg">
            <Image className="thumb" src={detail.cover} mode="aspectFill" onClick={preview} />
            <View className="food_desc" onClick={operateActionSheet}>
                <Text>{detail.meal_tag && detail.meal_tag.label}</Text>
                <Text>{detail.start && getTime(detail.start.timestamp)} </Text>
                {
                    detail.end.timestamp && <Text>{'-' + getTime(detail.end.timestamp)}</Text>
                }
            </View>
        </View>
        <Text className="food_item_date">{detail.start.date}</Text>
        {
            showModal && <Modal dismiss={() => { setShowModal(false) }} confirm={() => { setShowModal(false) }}>
                <View className='modal_content'>
                    <LimitPickers
                        isRealTime={true} time={getPickerInitValue()} limit={getPickerLimit()}
                        title={isStart ? t('feature.food.picker_start_title') : t('feature.food.picker_end_title')}
                        themeColor={ColorType.food}
                        limitDay={7} onCancel={() => { setShowModal(false) }}
                        onChange={(e) => {
                            updateTime(e)
                            setShowModal(false)
                        }} />
                </View>
            </Modal>
        }
        {
            showTagModal && <Modal dismiss={() => { setShowTagModal(false) }} confirm={() => { setShowTagModal(false) }}>
                <PickerViews title={t('feature.food.picker_tag_title')}
                    value={[pickerTagIndex()]}
                    items={pickerTagItems()}
                    onChange={(e) => { tagChanged(e) }}
                    onCancel={() => { setShowTagModal(false) }}
                    themeColor={ColorType.food}

                />
            </Modal>
        }

    </View>
}