import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:yumi/ui_kit/components/sc_compontent.dart';
import 'package:yumi/ui_kit/components/text/sc_text.dart';
import 'package:yumi/ui_kit/theme/socialchat_theme.dart';
import 'package:yumi/shared/business_logic/models/res/gift_res.dart';
import 'package:yumi/services/general/sc_app_general_manager.dart';
import 'package:provider/provider.dart';
import 'package:yumi/app_localizations.dart';
import 'package:yumi/app/config/business_logic_strategy.dart';
import 'package:yumi/app/constants/sc_global_config.dart';

import '../../shared/data_sources/models/enum/sc_gift_type.dart';

class GiftTabPage extends StatefulWidget {
  String type;
  bool isDark = true;
  Function(int checkedIndex) checkedCall;

  GiftTabPage(this.type, this.checkedCall, {super.key, this.isDark = true});

  @override
  _GiftTabPageState createState() => _GiftTabPageState();
}

class _GiftTabPageState extends State<GiftTabPage> {
  PageController _giftPageController = PageController();
  int _index = 0;
  int checkedIndex = 0;

  BusinessLogicStrategy get _strategy => SCGlobalConfig.businessLogicStrategy;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (widget.type == "CUSTOMIZED") {
        widget.checkedCall(1);
      } else {
        widget.checkedCall(0);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<SCAppGeneralManager>(
      builder: (context, ref, child) {
        return (ref.giftByTab[widget.type] ?? []).isEmpty
            ? mainEmpty(
              textColor: Colors.white54,
              msg: SCAppLocalizations.of(context)!.noData,
            )
            : Column(
              children: [
                SizedBox(height: 23.w,),
                Expanded(
                  child: PageView.builder(
                    controller: _giftPageController,
                    onPageChanged: (i) {
                      setState(() {
                        _index = i;
                      });
                    },
                    itemBuilder: (c, i) {
                      var current =
                          (ref.giftByTab[widget.type]!.length - (i * 8));
                      int size =
                          current > 8
                              ? 8
                              : current % 8 == 0
                              ? 8
                              : current % 8;
                      return GridView.builder(
                        shrinkWrap: true,
                        padding: EdgeInsets.symmetric(horizontal: 12.w),
                        physics: NeverScrollableScrollPhysics(),
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 4,
                          childAspectRatio: 0.75,
                          mainAxisSpacing: 8.w,
                          crossAxisSpacing: 8.w,
                        ),
                        itemCount: size,
                        itemBuilder: (BuildContext context, int index) {
                          return _bagItem(
                            ref.giftByTab[widget.type]![(i * 8) + index],
                            ref,
                          );
                        },
                      );
                    },
                    itemCount: (ref.giftByTab[widget.type]!.length / 8).ceil(),
                  ),
                ),
                _indicator(ref),
                SizedBox(height: 10.w),
              ],
            );
      },
    );
  }

  Widget _bagItem(SocialChatGiftRes gift, SCAppGeneralManager ref) {
    return gift.id == "-1000"
        ? GestureDetector(
          child: Stack(
            children: [
              Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(12.w),
                  color: Colors.white10,
                  border: Border.all(color: Colors.transparent, width: 1.w),
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Image.asset(
                      _strategy.getGiftPageCustomizedRuleIcon(),
                      fit: BoxFit.cover,
                      width: 48.w,
                      height: 48.w,
                    ),
                    SizedBox(height: 5.w),
                    Container(
                      height: 23.w,
                      margin: EdgeInsets.symmetric(horizontal: 3.w),
                      alignment: Alignment.center,
                      child: text(
                        SCAppLocalizations.of(context)!.rulesUpload,
                        maxLines: 2,
                        fontSize: 10.sp,
                        letterSpacing: 0.1,
                        lineHeight: 1,
                        textAlign: TextAlign.center,
                        fontWeight: FontWeight.w600,
                        textColor: Colors.white,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          onTap: () {
            SmartDialog.show(
              tag: "showCustomizedRule",
              alignment: Alignment.bottomCenter,
              animationType: SmartAnimationType.fade,
              builder: (_) {
                return SafeArea(
                  top: false,
                  child: ClipRect(
                    child: BackdropFilter(
                      filter: ui.ImageFilter.blur(sigmaX: 15, sigmaY: 15),
                      child: Stack(
                        alignment: Alignment.topCenter,
                        children: [
                          Container(
                            height: ScreenUtil().screenHeight * 0.7,
                            decoration: BoxDecoration(
                              color: Colors.black54,
                              borderRadius: BorderRadius.only(
                                topLeft: Radius.circular(12.w),
                                topRight: Radius.circular(12.w),
                              ),
                            ),
                            child: Column(
                              children: [
                                SizedBox(height: 10.w),
                                text(
                                  SCAppLocalizations.of(
                                    context,
                                  )!.customizedGiftRules,
                                  textColor: Colors.white,
                                  fontSize: 14.sp,
                                  fontWeight: FontWeight.w600,
                                ),
                                SizedBox(height: 7.w),
                                Expanded(
                                  child: SingleChildScrollView(
                                    child: Container(
                                      margin: EdgeInsets.symmetric(
                                        horizontal: 12.w,
                                      ),
                                      child: Text(
                                        SCAppLocalizations.of(
                                          context,
                                        )!.customizedGiftRulesContent,
                                        style: TextStyle(
                                          color: Colors.white,
                                          fontSize: 12.sp,
                                          fontWeight: FontWeight.w600,
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                                SizedBox(height: 10.w),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                );
              },
            );
          },
        )
        : GestureDetector(
          child: Stack(
            children: [
              Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(12.w),
                  color: Colors.white10,
                  border: Border.all(
                    color:
                        checkedIndex ==
                                ref.giftByTab[widget.type]!.indexOf(gift)
                            ? SocialChatTheme.primaryLight
                            : Colors.transparent,
                    width: 1.w,
                  ),
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    netImage(
                      url: gift.giftPhoto ?? "",
                      fit: BoxFit.cover,
                      width: 48.w,
                      height: 48.w,
                    ),
                    SizedBox(height: 5.w),
                    Container(
                      height: 23.w,
                      margin: EdgeInsets.symmetric(horizontal: 3.w),
                      alignment: Alignment.center,
                      child: text(
                        gift.giftName ?? "",
                        maxLines: 2,
                        fontSize: 10.sp,
                        letterSpacing: 0.1,
                        lineHeight: 1,
                        textAlign: TextAlign.center,
                        fontWeight: FontWeight.w600,
                        textColor:  widget.isDark ? Colors.white : Colors.black,
                      ),
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Image.asset(
                          _strategy.getGiftPageGoldCoinIcon(),
                          width: 14.w,
                          height: 14.w,
                        ),
                        SizedBox(width: 3.w),
                        text(
                          "${gift.giftCandy}",
                          fontSize: 10.sp,
                          textColor:
                              widget.isDark ? Colors.white : Colors.black,
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              Positioned(
                right: 3.w,
                child: Column(
                  spacing: 3.w,
                  children: [
                    SizedBox(height: 3.w),
                    // 只添加需要的 widget
                    if (gift.special!.contains(SCGiftType.ANIMSCION.name))
                      Image.asset(
                        _strategy.getGiftPageGiftEffectIcon(SCGiftType.ANIMSCION.name),
                        width: 16.w,
                        height: 16.w,
                        fit: BoxFit.fill,
                      ),
                    if (gift.special!.contains(SCGiftType.MUSIC.name))
                      Image.asset(
                        _strategy.getGiftPageGiftMusicIcon(SCGiftType.MUSIC.name),
                        width: 16.w,
                        height: 16.w,
                        fit: BoxFit.fill,
                      ),
                    if (gift.giftTab == (SCGiftType.LUCKY_GIFT.name))
                      Image.asset(
                        _strategy.getGiftPageGiftLuckIcon(SCGiftType.LUCKY_GIFT.name),
                        width: 16.w,
                        height: 16.w,
                        fit: BoxFit.fill,
                      ),
                    if (gift.giftTab == (SCGiftType.CP.name))
                      Image.asset(
                        _strategy.getGiftPageGiftCpIcon(SCGiftType.CP.name),
                        width: 16.w,
                        height: 16.w,
                        fit: BoxFit.fill,
                      ),
                  ],
                ),
              ),
            ],
          ),
          onTap: () {
            setState(() {
              checkedIndex = ref.giftByTab[widget.type]!.indexOf(gift);
              widget.checkedCall(checkedIndex);
            });
          },
        );
  }

  _indicator(SCAppGeneralManager ref) {
    var size = (ref.giftByTab[widget.type]!.length) / 8;
    var list = <Widget>[];
    for (int i = 0; i < size; i++) {
      list.add(
        Container(
          width: 6.5.w,
          height: 6.5.w,
          margin: EdgeInsets.symmetric(horizontal: 4.w),
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: _index == i ? SocialChatTheme.primaryColor : Color(0xffDADADA),
          ),
        ),
      );
    }
    return Row(mainAxisAlignment: MainAxisAlignment.center, children: list);
  }
}
