import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:yumi/app_localizations.dart';
import 'package:yumi/ui_kit/components/sc_debounce_widget.dart';
import 'package:yumi/ui_kit/components/sc_compontent.dart';
import 'package:yumi/ui_kit/components/text/sc_text.dart';
import 'package:provider/provider.dart';

import 'package:yumi/ui_kit/components/appbar/socialchat_appbar.dart';
import 'package:yumi/app/constants/sc_screen.dart';
import 'package:yumi/app/routes/sc_fluro_navigator.dart';
import 'package:yumi/services/payment/apple_payment_manager.dart';
import 'package:yumi/services/payment/google_payment_manager.dart';
import 'package:yumi/services/auth/user_profile_manager.dart';
import 'package:yumi/modules/wallet/wallet_route.dart';
import 'package:yumi/app/constants/sc_global_config.dart';

class RechargePage extends StatefulWidget {
  @override
  _RechargePageState createState() => _RechargePageState();
}

class _RechargePageState extends State<RechargePage> {
  @override
  void initState() {
    super.initState();
    Provider.of<SocialChatUserProfileManager>(context, listen: false).balance();
    if (Platform.isAndroid) {
      Provider.of<AndroidPaymentProcessor>(context, listen: false).initializePaymentProcessor(context);
    } else if (Platform.isIOS) {
      Provider.of<IOSPaymentProcessor>(context, listen: false).initializePaymentProcessor(context);
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Image.asset(
          SCGlobalConfig.businessLogicStrategy.getRechargePageBackgroundImage(),
          width: ScreenUtil().screenWidth,
          fit: BoxFit.fill,
        ),
        Scaffold(
          backgroundColor: SCGlobalConfig.businessLogicStrategy.getRechargePageScaffoldBackgroundColor(),
          resizeToAvoidBottomInset: false,
          appBar: SocialChatStandardAppBar(
            title: SCAppLocalizations.of(context)!.recharge,
            actions: [
              GestureDetector(
                child: Container(
                  margin: EdgeInsetsDirectional.only(end: 15.w),
                  child: Image.asset(
                    SCGlobalConfig.businessLogicStrategy.getRechargePageRecordIcon(),
                    width: 24.w,
                    height: 24.w,
                  ),
                ),
                onTap: () {
                  showGeneralDialog(
                    context: context,
                    barrierLabel: '',
                    barrierDismissible: true,
                    transitionDuration: Duration(milliseconds: 350),
                    barrierColor: SCGlobalConfig.businessLogicStrategy.getRechargePageDialogBarrierColor(),
                    pageBuilder: (
                      BuildContext context,
                      Animation animation,
                      Animation secondaryAnimation,
                    ) {
                      return GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {
                          Navigator.pop(context);
                          setState(() {});
                        },
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: <Widget>[
                            SizedBox(height: height(68)),
                            Row(
                              children: [
                                Spacer(),
                                GestureDetector(
                                  child: Container(
                                    decoration: BoxDecoration(
                                      color: SCGlobalConfig.businessLogicStrategy.getRechargePageDialogContainerBackgroundColor(),
                                      borderRadius: BorderRadius.circular(4),
                                    ),
                                    padding: EdgeInsets.symmetric(
                                      horizontal: 8.w,
                                      vertical: 3.w,
                                    ),
                                    child: Column(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        SizedBox(height: 5.w),
                                        GestureDetector(
                                          child: text(
                                            SCAppLocalizations.of(
                                              context,
                                            )!.goldListort,
                                            textColor: SCGlobalConfig.businessLogicStrategy.getRechargePageDialogTextColor(),
                                            fontSize: 14.sp,
                                          ),
                                          onTap: () {
                                            Navigator.of(context).pop();
                                            SCNavigatorUtils.push(
                                              context,
                                              WalletRoute.goldRecord,
                                              replace: false,
                                            );
                                          },
                                        ),
                                        // SizedBox(height: 5.w),
                                        // Container(
                                        //   color: Colors.black26,
                                        //   width: 110.w,
                                        //   height: 0.5.w,
                                        // ),
                                        // SizedBox(height: 5.w,),
                                        // text(
                                        //   SCAppLocalizations.of(
                                        //     context,
                                        //   )!.rechargeList,
                                        //   textColor: Colors.black38,
                                        //   fontSize: 14.sp,
                                        // ),
                                        SizedBox(height: 5.w),
                                      ],
                                    ),
                                  ),
                                  onTap: () {},
                                ),
                                SizedBox(width: 10.w),
                              ],
                            ),
                            Expanded(child: SizedBox(width: width(1))),
                          ],
                        ),
                      );
                    },
                  );
                },
              ),
            ],
          ),
          body: SafeArea(
            top: false,
            child: Column(
              children: [
                _buildWalletSection(),
                SizedBox(height: 60.w),
                Expanded(
                  child: Container(
                    padding: EdgeInsets.symmetric(
                      vertical: 20.w,
                      horizontal: 12.w,
                    ),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(12.0),
                        topRight: Radius.circular(12.0),
                      ),
                      color: SCGlobalConfig.businessLogicStrategy.getRechargePageMainContainerBackgroundColor(),
                    ),
                    child: Column(
                      children: [
                        Expanded(
                          child:
                              Platform.isAndroid
                                  ? Consumer<AndroidPaymentProcessor>(
                                    builder: (context, ref, child) {
                                      return ref.products.isNotEmpty
                                          ? ListView.separated(
                                            itemCount:
                                                ref.products.length, // 列表项数量
                                            padding: EdgeInsets.only(
                                              bottom: 15.w,
                                            ),
                                            itemBuilder: (context, index) {
                                              return _buildGoogleProductItem(
                                                ref.products[index],
                                                ref,
                                                index,
                                              );
                                            },
                                            separatorBuilder: (
                                              BuildContext context,
                                              int index,
                                            ) {
                                              return SizedBox(height: 10.w);
                                            },
                                          )
                                          : mainEmpty();
                                    },
                                  )
                                  : Consumer<IOSPaymentProcessor>(
                                    builder: (context, ref, child) {
                                      return ref.products.isNotEmpty
                                          ? ListView.separated(
                                            itemCount:
                                                ref.products.length, // 列表项数量
                                            padding: EdgeInsets.only(
                                              bottom: 15.w,
                                            ),
                                            itemBuilder: (context, index) {
                                              return _buildAppleProductItem(
                                                ref.products[index],
                                                ref,
                                                index,
                                              );
                                            },
                                            separatorBuilder: (
                                              BuildContext context,
                                              int index,
                                            ) {
                                              return SizedBox(height: 10.w);
                                            },
                                          )
                                          : mainEmpty();
                                    },
                                  ),
                        ),
                        ///针对ios的恢复购买
                        Platform.isIOS?SCDebounceWidget(
                          child: Container(
                            alignment: Alignment.center,
                            margin: EdgeInsets.symmetric(horizontal: 60.w),
                            height: 42.w,
                            decoration: BoxDecoration(
                              color: SCGlobalConfig.businessLogicStrategy.getRechargePageButtonBackgroundColor(),
                              borderRadius: BorderRadius.all(
                                Radius.circular(height(8)),
                              ),
                            ),
                            child: text(
                              SCAppLocalizations.of(context)!.restorePurchases,
                              textColor: SCGlobalConfig.businessLogicStrategy.getRechargePageButtonTextColor(),
                              fontSize: 16.sp,
                            ),
                          ),
                          onTap: () {
                            Provider.of<IOSPaymentProcessor>(
                              context,
                              listen: false,
                            ).recoverTransactions();
                          },
                        ):Container(),
                        SizedBox(height: 15.w),
                        SCDebounceWidget(
                          child: Container(
                            alignment: Alignment.center,
                            margin: EdgeInsets.symmetric(horizontal: 60.w),
                            height: 42.w,
                            decoration: BoxDecoration(
                              color: SCGlobalConfig.businessLogicStrategy.getRechargePageButtonBackgroundColor(),
                              borderRadius: BorderRadius.all(
                                Radius.circular(height(8)),
                              ),
                            ),
                            child: text(
                              SCAppLocalizations.of(context)!.recharge,
                              textColor: SCGlobalConfig.businessLogicStrategy.getRechargePageButtonTextColor(),
                              fontSize: 16.sp,
                            ),
                          ),
                          onTap: () {
                            if (Platform.isAndroid) {
                              Provider.of<AndroidPaymentProcessor>(
                                context,
                                listen: false,
                              ).processPurchase();
                            } else if (Platform.isIOS) {
                              Provider.of<IOSPaymentProcessor>(
                                context,
                                listen: false,
                              ).processPurchase();
                            }
                          },
                        ),
                        SizedBox(height: 45.w),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildWalletSection() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 15.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          SizedBox(height: 45.w),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.asset(
                SCGlobalConfig.businessLogicStrategy.getRechargePageGoldIcon(),
                width: 36.w,
                height: 36.w,
              ),
              SizedBox(width: 3.w),
              Consumer<SocialChatUserProfileManager>(
                builder: (context, ref, child) {
                  return text(
                    ref.myBalance > 1000
                        ? "${(ref.myBalance / 1000).toStringAsFixed(2)}k"
                        : "${ref.myBalance}",
                    fontSize: 16.sp,
                    textColor: SCGlobalConfig.businessLogicStrategy.getRechargePageWalletTextColor(),
                    fontWeight: FontWeight.bold,
                  );
                },
              ),
            ],
          ),
        ],
      ),
    );
  }


  Widget _buildGoogleProductItem(
    SelecteProductConfig productConfig,
      AndroidPaymentProcessor ref,
    int index,
  ) {
    return GestureDetector(
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 5.w, horizontal: 10.w),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(3),
          color: productConfig.isSelecte ? SCGlobalConfig.businessLogicStrategy.getRechargePageSelectedItemBackgroundColor() : SCGlobalConfig.businessLogicStrategy.getRechargePageUnselectedItemBackgroundColor(),
          border: Border.all(
            color: productConfig.isSelecte ? SCGlobalConfig.businessLogicStrategy.getRechargePageSelectedItemBorderColor() : SCGlobalConfig.businessLogicStrategy.getRechargePageUnselectedItemBorderColor(),
            width: 1.w,
          ),
        ),
        child: Row(
          children: [
            Image.asset(
              SCGlobalConfig.businessLogicStrategy.getRechargePageGoldIconByIndex(index),
              width: 34.w,
              height: 34.w,
            ),
            SizedBox(width: 5.w),
            text(
              "${ref.productMap[productConfig.produc.id]?.obtainCandy ?? 0}",
              fontSize: 12.sp,
              textColor: SCGlobalConfig.businessLogicStrategy.getRechargePageItemTextColor(),
            ),
            Spacer(),
            text(
              productConfig.produc.price,
              textColor: SCGlobalConfig.businessLogicStrategy.getRechargePageItemPriceTextColor(),
              fontWeight: FontWeight.w600,
              fontSize: 12.sp,
            ),
          ],
        ),
      ),
      onTap: () {
        ref.chooseProductConfig(index);
      },
    );
  }

  Widget _buildAppleProductItem(
      SelecteProductConfig productConfig,
      IOSPaymentProcessor ref,
    int index,
  ) {
    return GestureDetector(
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 5.w, horizontal: 10.w),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12),
          color: SCGlobalConfig.businessLogicStrategy.getRechargePageAppleItemBackgroundColor(),
          border: Border.all(
            color: productConfig.isSelecte ? SCGlobalConfig.businessLogicStrategy.getRechargePageSelectedItemBorderColor() : SCGlobalConfig.businessLogicStrategy.getRechargePageUnselectedItemBorderColor(),
            width: 1.w,
          ),
        ),
        child: Row(
          children: [
            Image.asset(
              SCGlobalConfig.businessLogicStrategy.getRechargePageGoldIconByIndex(index),
              width: 34.w,
              height: 34.w,
            ),
            SizedBox(width: 5.w),
            text(
              "${ref.productMap[productConfig.produc.id]?.obtainCandy ?? 0}",
              fontSize: 12.sp,
              textColor: SCGlobalConfig.businessLogicStrategy.getRechargePageItemTextColor(),
            ),
            Spacer(),
            text(
              productConfig.produc.price,
              textColor: SCGlobalConfig.businessLogicStrategy.getRechargePageItemPriceTextColor(),
              fontWeight: FontWeight.w600,
              fontSize: 12.sp,
            ),
          ],
        ),
      ),
      onTap: () {
        ref.chooseProductConfig(index);
      },
    );
  }
}

class SelecteProductConfig {
  ProductDetails produc;
  bool isSelecte = false;

  SelecteProductConfig(this.produc, this.isSelecte);
}
