import { _decorator, Node, Button } from 'cc';
import { BaseView } from 'db://assets/scripts/core/BaseView';
import { ViewManager } from 'db://assets/scripts/core/ViewManager';
import { CreatedShareItem } from 'db://assets/scripts/types/ApiTypes';
import { ShareManager } from 'db://assets/scripts/utils/ShareManager';
import { ToastManager } from 'db://assets/scripts/utils/ToastManager';
const { ccclass, property } = _decorator;

@ccclass('PagePKData')
export class PagePKData extends BaseView {
    @property({ type: Node, tooltip: '返回按钮' })
    backBtn: Node | null = null;

    private _createdShares: CreatedShareItem[] = [];
    private _isLoading: boolean = false;

    onViewLoad(): void {
        if (this.backBtn) {
            this.backBtn.on(Button.EventType.CLICK, this._onBackClick, this);
        }
    }

    onViewShow(): void {
        void this._loadCreatedShares();
    }

    onViewHide(): void {
    }

    private _onBackClick(): void {
        ViewManager.instance.back();
    }

    private async _loadCreatedShares(): Promise<void> {
        if (this._isLoading) {
            return;
        }

        this._isLoading = true;
        try {
            const items = await ShareManager.instance.fetchCreatedShares();
            if (!items) {
                ToastManager.instance.show('获取挑战列表失败，请稍后重试');
                return;
            }

            this._createdShares = items;
            console.log('[PagePKData] 我创建的挑战列表:', this._createdShares);
        } finally {
            this._isLoading = false;
        }
    }

    onViewDestroy(): void {
        if (this.backBtn) {
            this.backBtn.off(Button.EventType.CLICK, this._onBackClick, this);
        }
    }
}
