import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hoshan/data/model/ai/credit_model.dart';
import 'package:hoshan/data/model/plans_model.dart';
import 'package:hoshan/data/model/purchase_args.dart';
import 'package:hoshan/ui/screens/purchase_page/bloc/plans_bloc.dart';
import 'package:hoshan/ui/screens/setting/bloc/paymant_history_bloc.dart';
import 'package:hoshan/ui/screens/splash/cubit/user_info_cubit.dart';
import 'package:hoshan/ui/theme/responsive.dart';
import 'package:hoshan/ui/widgets/components/dialog/dialog_handler.dart';
import 'package:hoshan/ui/widgets/components/purchase/purchase_card.dart';
import 'package:hoshan/ui/widgets/components/purchase/purchase_card_placeholder.dart';
import 'package:hoshan/ui/widgets/sections/header/reversible_appbar.dart';

class PurchasePage extends StatefulWidget {
  final PurchaseArgs? args;
  const PurchasePage({super.key, this.args});

  @override
  State<PurchasePage> createState() => _PurchasePageState();
}

class _PurchasePageState extends State<PurchasePage> {
  @override
  void initState() {
    try {
      if (widget.args != null) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          DialogHandler(context: context).showPurchStatus(
              success: widget.args!.success, detail: widget.args!.message);
          context.read<PaymantHistoryBloc>().add(GetAllHistory());
          if (widget.args!.success) {
            context
                .read<UserInfoCubit>()
                .changeCredit(CreditModel(credit: widget.args!.credit));
          }
        });
      }
    } catch (e) {
      if (kDebugMode) {
        print('Error DeepLinking: $e');
      }
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: ReversibleAppbar(
        context,
        titleText: 'افزایش اعتبار',
      ),
      body: Responsive(context).maxWidthInDesktop(
        maxWidth: 800,
        child: (contxet, maxWidth) => SingleChildScrollView(
            physics: context.watch<PlansBloc>().state is PlansLoading
                ? const NeverScrollableScrollPhysics()
                : const BouncingScrollPhysics(),
            child: Responsive(context).builder(
              desktop: Column(
                children: [
                  BlocBuilder<PlansBloc, PlansState>(
                    builder: (context, state) {
                      if (state is PlansSuccess) {
                        final plans = state.plans
                          ..add(Plans(
                              title: 'بسته ویژه سازمان‌ها',
                              image: '/paymant/6/cover.png'));
                        List<List<Plans>> separatedPlans = [];
                        for (int i = 0; i < plans.length; i += 2) {
                          if (i + 1 < plans.length) {
                            separatedPlans.add([plans[i], plans[i + 1]]);
                          } else {
                            separatedPlans.add([plans[i]]);
                          }
                        }

                        return ListView.builder(
                          physics: const NeverScrollableScrollPhysics(),
                          shrinkWrap: true,
                          itemCount: separatedPlans.length,
                          itemBuilder: (context, index) {
                            return Row(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: List.generate(
                                separatedPlans[index].length,
                                (innerIndex) {
                                  final plan =
                                      separatedPlans[index][innerIndex];
                                  return Expanded(child: SizedBox()
                                      // PurchaseCard(
                                      //   plan: plan,
                                      //   button: plan.title ==
                                      //           'بسته ویژه سازمان‌ها'
                                      //       ? () => Padding(
                                      //             padding:
                                      //                 const EdgeInsets.symmetric(
                                      //                     vertical: 16.0),
                                      //             child: LoadingButton(
                                      //                 onPressed: () async {
                                      //                   await launchUrl(
                                      //                           Uri.parse(
                                      //                               'tel:03132611885'),
                                      //                           mode: LaunchMode
                                      //                               .externalApplication)
                                      //                       .onError(
                                      //                     (error, stackTrace) {
                                      //                       if (kDebugMode) {
                                      //                         print(
                                      //                             'error open Link is: $error');
                                      //                       }
                                      //                       return false;
                                      //                     },
                                      //                   );
                                      //                 },
                                      //                 radius: 360,
                                      //                 color: AppColors
                                      //                     .green.defaultShade,
                                      //                 width: MediaQuery.sizeOf(
                                      //                         context)
                                      //                     .width,
                                      //                 child: Text(
                                      //                   'با تیم پشتیبانی تماس بگیرید',
                                      //                   style: AppTextStyles.body4
                                      //                       .copyWith(
                                      //                           color:
                                      //                               Colors.white),
                                      //                 )),
                                      //           )
                                      //       : null,
                                      // ),
                                      );
                                },
                              ),
                            );
                          },
                        );
                      }
                      if (state is PlansFail) {
                        return const SizedBox.shrink();
                      }

                      return ListView.builder(
                        physics: const NeverScrollableScrollPhysics(),
                        shrinkWrap: true,
                        itemCount: 6,
                        itemBuilder: (context, index) {
                          return Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: List.generate(
                              2,
                              (innerIndex) {
                                return const Expanded(
                                  child: PurchaseCardPlaceholder(),
                                );
                              },
                            ),
                          );
                        },
                      );
                    },
                  ),
                ],
              ),
              mobile: Column(
                children: [
                  BlocBuilder<PlansBloc, PlansState>(
                    builder: (context, state) {
                      if (state is PlansSuccess) {
                        return ListView.builder(
                            shrinkWrap: true,
                            physics: const NeverScrollableScrollPhysics(),
                            itemCount: state.plans.length,
                            itemBuilder: (context, index) {
                              final plan = state.plans[index];
                              return PurchaseCard(
                                plan: plan,
                              );
                            });
                      }
                      if (state is PlansFail) {
                        return const SizedBox.shrink();
                      }
                      return ListView.builder(
                          shrinkWrap: true,
                          physics: const NeverScrollableScrollPhysics(),
                          itemCount: 4,
                          itemBuilder: (context, index) {
                            return const PurchaseCardPlaceholder();
                          });
                    },
                  ),
                  // PurchaseCard(
                  //   plan: Plans(
                  //       title: 'بسته ویژه سازمان‌ها',
                  //       image: '/paymant/6/cover.png'),
                  //   button: () => Padding(
                  //     padding: const EdgeInsets.symmetric(vertical: 16.0),
                  //     child: LoadingButton(
                  //         onPressed: () async {
                  //           await launchUrl(Uri.parse('tel:03132611885'),
                  //                   mode: LaunchMode.externalApplication)
                  //               .onError(
                  //             (error, stackTrace) {
                  //               if (kDebugMode) {
                  //                 print('error open Link is: $error');
                  //               }
                  //               return false;
                  //             },
                  //           );
                  //         },
                  //         radius: 360,
                  //         color: AppColors.green.defaultShade,
                  //         width: MediaQuery.sizeOf(context).width,
                  //         child: Text(
                  //           'با تیم پشتیبانی تماس بگیرید',
                  //           style: AppTextStyles.body4
                  //               .copyWith(color: Colors.white),
                  //         )),
                  //   ),
                  // ),
                ],
              ),
            )),
      ),
    );
  }
}
