import request from '../../../utils/request';

Page({
    data: {
        favTab: 'all', // 'all', 'plant', 'post'
        favorites: [],
        current: 1,
        pageSize: 10,
        hasMore: true,
        isLoading: false
    },

    onLoad() {
        this.fetchFavorites(true);
    },

    onFavTabChange(e) {
        const val = e.currentTarget.dataset.value;
        if (val === this.data.favTab) return;
        this.setData({ favTab: val }, () => {
            this.fetchFavorites(true);
        });
    },

    fetchFavorites(reset = false) {
        if (this.data.isLoading) return;
        if (!reset && !this.data.hasMore) return;

        this.setData({ isLoading: true });

        const current = reset ? 1 : this.data.current;
        let classType = 0;
        if (this.data.favTab === 'plant') classType = 1;
        if (this.data.favTab === 'post') classType = 2;

        request.post('/plant/profile/star', {
            current,
            pageSize: this.data.pageSize,
            class: classType
        }).then(res => {
            const list = res.list || [];
            const total = res.total || 0;

            const mappedList = list.map(wrapper => {
                const type = wrapper.type; // 1=Wiki, 2=Post
                const isPlant = type === 1;
                const entity = isPlant ? wrapper.wiki : wrapper.post;

                if (!entity) return null;

                // Image Extraction
                let image = '';
                if (entity.imgList && entity.imgList.length > 0) {
                    image = entity.imgList[0].url;
                }

                if (isPlant) {
                    return {
                        id: entity.id,
                        type: 'plant',
                        name: entity.name,
                        latinName: entity.latinName,
                        difficultyLabel: this.getDifficultyLabel(entity.difficulty),
                        image: image
                    };
                } else {
                    // Post
                    return {
                        id: entity.id,
                        type: 'post',
                        content: entity.content,
                        postImage: image,
                        avatar: entity.publisher && entity.publisher.avatar ? entity.publisher.avatar : '', // Publisher is null in sample
                        nickname: entity.publisher && entity.publisher.nickname ? entity.publisher.nickname : '花友',
                        time: wrapper.createdAtStr
                    };
                }
            }).filter(item => item !== null);

            if (reset) {
                this.setData({
                    favorites: mappedList,
                    current: 2,
                    hasMore: mappedList.length < total,
                    isLoading: false
                });
            } else {
                this.setData({
                    favorites: [...this.data.favorites, ...mappedList],
                    current: current + 1,
                    hasMore: (this.data.favorites.length + mappedList.length) < total,
                    isLoading: false
                });
            }
        }).catch(err => {
            console.error('Fetch favorites failed', err);
            this.setData({ isLoading: false });
        });
    },

    getDifficultyLabel(level) {
        const labels = { 1: '简单', 2: '中等', 3: '较难', 4: '困难', 5: '专家' };
        return labels[level] || '未知';
    },

    onSwipeClick(e) {
        // Handle Delete
        // Data item is bound to the swipe-cell or passed via dataset
        // If bind:click is on swipe-cell, e.target might not have the item if not set.
        // We set data-item on swipe-cell.
        const item = e.currentTarget.dataset.item;
        const { id, type } = item;

        const apiPath = type === 'plant' ? '/plant/wiki/star' : '/plant/post/star';

        wx.showModal({
            title: '提示',
            content: '确定要取消收藏吗？',
            success: (modRes) => {
                if (modRes.confirm) {
                    request.get(apiPath, { id, type: 2 }).then(() => {
                        wx.showToast({ title: '已删除', icon: 'success' });
                        // Remove from list
                        const newList = this.data.favorites.filter(i => i.id !== id);
                        this.setData({ favorites: newList });
                    }).catch(err => {
                        console.error('Delete favorite failed', err);
                        wx.showToast({ title: '删除失败', icon: 'none' });
                    });
                }
            }
        });
    },

    goToDetail(e) {
        const item = e.currentTarget.dataset.item;
        if (item.type === 'plant') {
            wx.navigateTo({ url: `/pages/wiki/detail/index?id=${item.id}` });
        } else {
            wx.showToast({ title: '暂不支持查看动态详情', icon: 'none' });
        }
    },

    onReachBottom() {
        this.fetchFavorites(false);
    }
});
