import 'package:cpt_rewards/modules/rewards_detail/rewards_detail_page.dart';
import 'package:cs_resources/theme/app_colors_theme.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:auto_route/auto_route.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:router/ext/auto_router_extensions.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/color_utils.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/my_appbar.dart';
import 'package:widgets/my_load_image.dart';
import 'package:widgets/my_text_view.dart';
import 'package:widgets/shatter/picker_container.dart';
import 'package:widgets/utils/dark_theme_util.dart';
import 'package:widgets/widget_export.dart';
import 'package:cs_resources/generated/assets.dart';

import '../../../router/page/rewards_page_router.dart';
import './rewards_list_vm.dart';

@RoutePage()
class RewardsListPage extends HookConsumerWidget {
  const RewardsListPage({Key? key}) : super(key: key);

  //启动当前页面
  static void startInstance({BuildContext? context}) {
    if (context != null) {
      context.router.push(const RewardsListPageRoute());
    } else {
      appRouter.push(const RewardsListPageRoute());
    }
  }

  Widget _buildItemLeftSection(BuildContext context, WidgetRef ref, item, _vm) {
    int point = item['point'] ?? 0;
    int originalPoint = item['original_point'] ?? 0;
    int id = item['id'];
    return Column(
      children: [
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            MyLoadImage(
              item?['resources']?[0] ?? '',
              width: MediaQuery.of(context).size.width,
              height: 150,
            ),
            Text(
              maxLines: 1, // 设置最大行数为2
              overflow: TextOverflow.ellipsis, // 超出部分用省略号表示
              item?['name'] ?? '',
              style: TextStyle(fontSize: 16.0, color: context.appColors.textBlack, fontWeight: FontWeight.w500),
            ).marginOnly(bottom: 5, top: 10).paddingOnly(left: 20, right: 20),
            Row(
              children: [
                Text(
                  '$point',
                  style: TextStyle(fontSize: 19.0, color: context.appColors.textBlack, fontWeight: FontWeight.w500),
                ),
                Text(
                  '$originalPoint',
                  style: TextStyle(
                      decoration: TextDecoration.lineThrough,
                      decorationColor: ColorUtils.string2Color('#000000'),
                      decorationStyle: TextDecorationStyle.solid,
                      fontSize: 12.0,
                      color: ColorUtils.string2Color('#000000'),
                      fontWeight: FontWeight.w400),
                ).marginOnly(left: 5, right: 5),
                Text(
                  'Points',
                  style: TextStyle(fontSize: 13.0, color: context.appColors.textBlack, fontWeight: FontWeight.w400),
                ),
              ],
            ).paddingOnly(left: 20, right: 20),
          ],
        ).onTap(() {
          RewardsDetailPage.startInstance(id: id);
        }),
      ],
    ).paddingOnly(top: 0);
  }

  // listitem
  Widget _buildSaleItem(BuildContext context, WidgetRef ref, item, _vm) {
    return Container(
      decoration: BoxDecoration(
        color: context.appColors.whiteBG,
        borderRadius: const BorderRadius.all(Radius.circular(6.0)),
        boxShadow: const [BoxShadow(color: Color.fromRGBO(184, 191, 217, 0.3), blurRadius: 6)],
      ),
      child: Column(
        children: [
          SizedBox(
            width: MediaQuery.of(context).size.width - 30,
            height: 235,
            // margin: const EdgeInsets.only(left: 15, right: 15, top: 12.5),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                ClipRRect(borderRadius: const BorderRadius.all(Radius.circular(6.0)), child: _buildItemLeftSection(context, ref, item, _vm))
                // .marginOnly(bottom: 5),
              ],
            ),
          ).constrained(
            minHeight: 235,
          ),
        ],
      ),
    ).marginOnly(left: 15, bottom: 15, right: 15);
  }

  // list
  Widget _buildSaleList(BuildContext context, WidgetRef ref, _vm) {
    final state = ref.watch(rewardsListVmProvider);
    return SliverList(
        delegate: SliverChildBuilderDelegate((context, index) {
      return _buildSaleItem(context, ref, state.list![index], _vm);
    }, childCount: state.list!.length));
  }

  Widget _buildTop(BuildContext context, WidgetRef ref, _vm) {
    final state = ref.watch(rewardsListVmProvider);
    return Container(
      height: 55,
      decoration: BoxDecoration(
        color: context.appColors.whiteBG,
        borderRadius: const BorderRadius.all(Radius.circular(6.0)),
        boxShadow: const [BoxShadow(color: Color.fromRGBO(184, 191, 217, 0.3), blurRadius: 6)],
      ),
      child: Row(
        children: [
          SizedBox(
              width: MediaQuery.of(context).size.width / 2 - 60,
              child:
                  // Column(
                  //   children: [
                  //     PickerContainer(
                  //       content: state.selectedOption ?? "",
                  //       hint: 'All',
                  //       bgColor: Colors.white,
                  //       margin: const EdgeInsets.only(top: 0),
                  //       onClick: _vm.pickCategory,
                  //     ),
                  //   ],
                  // ),
                  Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text(
                    state.category_name!,
                    style: TextStyle(fontSize: 15.0, color: context.appColors.textBlack, fontWeight: FontWeight.w500), // 设置字体大小
                  ),
                  DarkThemeUtil.multiImageColorFit(context, Assets.rewardsRewardsIconDomn, width: 12, height: 7, darkColor: Colors.white),
                ],
              ).onTap(() {
                // _vm.doDeleteAccountAll(context);
                _showMyModalBottomSheet(context, ref, _vm);
              })).paddingOnly(left: 15, right: 15),
          SizedBox(
              width: MediaQuery.of(context).size.width / 2 - 40,
              child:
                  // Column(
                  //   children: [
                  //     PickerContainer(
                  //       content: state.selectedOption ?? "",
                  //       hint: 'Popularity',
                  //       bgColor: Colors.white,
                  //       margin: const EdgeInsets.only(top: 0),
                  //       onClick: _vm.pickCategory,
                  //     ),
                  //   ],
                  // )
                  Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text(
                    'Popularity',
                    style: TextStyle(fontSize: 15.0, color: context.appColors.textBlack, fontWeight: FontWeight.w500), // 设置字体大小
                  ),
                  DarkThemeUtil.multiImageColorFit(context, Assets.rewardsRewardsIconDomn, width: 12, height: 7, darkColor: Colors.white),
                ],
              ).onTap(() {
                // 去详情
                // _vm.doDeleteAccount(context);
                _showMyModalBottom(context, ref, _vm);
              })).paddingOnly(left: 15, right: 15)
        ],
      ),
    ).marginOnly(top: 12, left: 15, right: 15).backgroundColor(context.appColors.backgroundDark);
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final vm = ref.read(rewardsListVmProvider.notifier);
    final state = ref.watch(rewardsListVmProvider);
    useEffect(() {
      // 组件挂载时执行 - 执行接口请求
      Future.microtask(() => vm.initPageData());
      return () {
        // 组件卸载时执行
        Log.d("property_news_page 组件卸载时执行");
      };
    }, []);
    return Scaffold(
      appBar: MyAppBar.appBar(
        context,
        "Recommend",
        backgroundColor: context.appColors.whiteBG,
      ),
      body: Column(
        children: [
          _buildTop(context, ref, vm),
          Expanded(
            child: EasyRefresh(
              controller: vm.refreshController,
              // 上拉加载
              onLoad: () async {
                Log.d("----onLoad");
                vm.loadMore();
              },
              // 下拉刷新
              onRefresh: () async {
                Log.d("----onRefresh");
                vm.onRefresh();
              },
              child: Container(
                color: context.appColors.backgroundDark,
                padding: const EdgeInsets.only(top: 15),
                child: LoadStateLayout(
                  state: state.loadingState,
                  errorMessage: state.errorMessage,
                  errorRetry: () {
                    vm.retryRequest();
                  },
                  successSliverWidget: [_buildSaleList(context, ref, vm)],
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  // showModalBottomSheet（模态底部弹出框）
  Future<void> _showMyModalBottomSheet(BuildContext context, ref, _vm) async {
    final state = ref.watch(rewardsListVmProvider);
    List itemsList = state.categoryList;
    return showModalBottomSheet<void>(
      context: context,
      backgroundColor: Colors.white,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(25.0)),
      ),
      isScrollControlled: true,
      builder: (BuildContext context) {
        return SizedBox(
          height: 500,
          child: Column(
              children: List.generate(
            itemsList.length,
            (index) {
              return Container(
                  height: 45,
                  decoration: BoxDecoration(
                      border: Border(
                          bottom: BorderSide(
                    width: 1.0, // 底边边框的宽度
                    color: ColorUtils.string2Color('#F2F3F6'), // 底边边框的颜色
                  ))),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          Text(
                            itemsList[index]['name'],
                            style: TextStyle(
                                fontSize: 16.0,
                                color: itemsList[index]['id'] == state.category_id ? ColorUtils.string2Color('#FF5E75') : ColorUtils.string2Color('#000000'),
                                fontWeight: FontWeight.w400),
                          ),
                        ],
                      ),
                      itemsList[index]['id'] == state.category_id
                          ? MyAssetImage(
                              Assets.rewardsRewardListChoose,
                              width: 17,
                              height: 17,
                              color: DarkThemeUtil.multiColors(context, AppColorsTheme.colorPrimary, darkColor: Colors.white),
                            )
                          : Container()
                    ],
                  )).onTap(() {
                _vm.categoryClick(itemsList[index]);
                Navigator.of(context).pop();
              });
            },
          )).paddingOnly(left: 15, right: 15, top: 15),
        );
      },
    );
  }

  Future<void> _showMyModalBottom(BuildContext context, ref, _vm) async {
    final _vm = ref.read(rewardsListVmProvider.notifier);
    final state = ref.watch(rewardsListVmProvider);
    return showModalBottomSheet<void>(
        context: context,
        backgroundColor: Colors.white,
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(top: Radius.circular(25.0)),
        ),
        isScrollControlled: true,
        builder: (BuildContext context) {
          var isSelected = true;
          var sortBy = state.sort_by;
          var sort = state.sort;
          int point_min = state.point_min;
          int point_max = state.point_max;
          return StatefulBuilder(builder: (context, setState) {
            return SizedBox(
              height: 550,
              child: Column(
                children: [
                  Container(
                    height: 40,
                    color: ColorUtils.string2Color('#F1F1F1'),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Text(
                          textAlign: TextAlign.center,
                          'Sort by',
                          style: TextStyle(fontSize: 16.0, color: ColorUtils.string2Color('#767676'), fontWeight: FontWeight.w500),
                        ),
                      ],
                    ).paddingOnly(left: 15, right: 15),
                  ),
                  Column(
                    children: [
                      Container(
                          height: 45,
                          decoration: BoxDecoration(
                              border: Border(
                                  bottom: BorderSide(
                            width: 1.0, // 底边边框的宽度
                            color: ColorUtils.string2Color('#F2F3F6'), // 底边边框的颜色
                          ))),
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  const MyAssetImage(
                                    Assets.rewardsRewardListNew,
                                    width: 16,
                                    height: 13,
                                  ).marginOnly(right: 15),
                                  Text(
                                    'Latest',
                                    style: TextStyle(
                                        fontSize: 16.0,
                                        color: sortBy == "created_at" ? ColorUtils.string2Color('#FF5E75') : ColorUtils.string2Color('#000000'),
                                        fontWeight: FontWeight.w400),
                                  ),
                                ],
                              ),
                              sortBy == "created_at"
                                  ? MyAssetImage(
                                      Assets.rewardsRewardListChoose,
                                      width: 17,
                                      height: 17,
                                      color: DarkThemeUtil.multiColors(context, AppColorsTheme.colorPrimary, darkColor: Colors.white),
                                    )
                                  : Container()
                            ],
                          )).onTap(() {
                        setState(() {
                          sortBy = "created_at";
                          _vm.sortByClick('created_at');
                        });
                      }),
                      Container(
                          height: 45,
                          decoration: BoxDecoration(
                              border: Border(
                                  bottom: BorderSide(
                            width: 1.0, // 底边边框的宽度
                            color: ColorUtils.string2Color('#F2F3F6'), // 底边边框的颜色
                          ))),
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  const MyAssetImage(
                                    Assets.rewardsRewardListHot,
                                    width: 13,
                                    height: 17,
                                  ).marginOnly(right: 15),
                                  Text(
                                    'Popularity',
                                    style: TextStyle(
                                        fontSize: 16.0,
                                        color: sortBy == "clicks_count" ? ColorUtils.string2Color('#FF5E75') : ColorUtils.string2Color('#000000'),
                                        fontWeight: FontWeight.w400),
                                  ),
                                ],
                              ),
                              sortBy == "clicks_count"
                                  ? MyAssetImage(
                                      Assets.rewardsRewardListChoose,
                                      width: 17,
                                      height: 17,
                                      color: DarkThemeUtil.multiColors(context, AppColorsTheme.colorPrimary, darkColor: Colors.white),
                                    )
                                  : Container()
                            ],
                          )).onTap(() {
                        setState(() {
                          sortBy = "clicks_count";
                          _vm.sortByClick('clicks_count');
                        });
                      }),
                      Container(
                          height: 45,
                          decoration: BoxDecoration(
                              border: Border(
                                  bottom: BorderSide(
                            width: 1.0, // 底边边框的宽度
                            color: ColorUtils.string2Color('#F2F3F6'), // 底边边框的颜色
                          ))),
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  MyAssetImage(
                                    Assets.rewardsRewardListLow,
                                    width: 14,
                                    height: 17,
                                    color: DarkThemeUtil.multiColors(context, AppColorsTheme.colorPrimary, darkColor: Colors.white),
                                  ).marginOnly(right: 15),
                                  Text(
                                    'Low to High Points',
                                    style: TextStyle(
                                        fontSize: 16.0,
                                        color: sort == "asc" ? ColorUtils.string2Color('#FF5E75') : ColorUtils.string2Color('#000000'),
                                        fontWeight: FontWeight.w400),
                                  ),
                                ],
                              ),
                              sort == "asc"
                                  ? MyAssetImage(
                                      Assets.rewardsRewardListChoose,
                                      width: 17,
                                      height: 17,
                                      color: DarkThemeUtil.multiColors(context, AppColorsTheme.colorPrimary, darkColor: Colors.white),
                                    )
                                  : Container()
                            ],
                          )).onTap(() {
                        setState(() {
                          sort = "asc";
                          _vm.sortClick('asc');
                        });
                      }),
                      Container(
                          height: 45,
                          decoration: BoxDecoration(
                              border: Border(
                                  bottom: BorderSide(
                            width: 1.0, // 底边边框的宽度
                            color: ColorUtils.string2Color('#F2F3F6'), // 底边边框的颜色
                          ))),
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  MyAssetImage(
                                    Assets.rewardsRewardListHigh,
                                    width: 13,
                                    height: 16,
                                    color: DarkThemeUtil.multiColors(context, AppColorsTheme.colorPrimary, darkColor: Colors.white),
                                  ).marginOnly(right: 15),
                                  Text(
                                    'High to Low Points',
                                    style: TextStyle(
                                        fontSize: 16.0,
                                        color: sort == "desc" ? ColorUtils.string2Color('#FF5E75') : ColorUtils.string2Color('#000000'),
                                        fontWeight: FontWeight.w400),
                                  ),
                                ],
                              ),
                              sort == "desc"
                                  ? MyAssetImage(
                                      Assets.rewardsRewardListChoose,
                                      width: 17,
                                      height: 17,
                                      color: DarkThemeUtil.multiColors(context, AppColorsTheme.colorPrimary, darkColor: Colors.white),
                                    )
                                  : Container()
                            ],
                          )).onTap(() {
                        setState(() {
                          sort = "desc";
                          _vm.sortClick('desc');
                        });
                      }),
                    ],
                  ).paddingOnly(left: 15, right: 15),
                  Container(
                    height: 40,
                    color: ColorUtils.string2Color('#F1F1F1'),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Text(
                          textAlign: TextAlign.center,
                          'Filter By',
                          style: TextStyle(fontSize: 16.0, color: ColorUtils.string2Color('#767676'), fontWeight: FontWeight.w500),
                        ),
                      ],
                    ).paddingOnly(left: 15, right: 15),
                  ),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Text(
                        '$point_min',
                        style: TextStyle(fontSize: 16.0, color: ColorUtils.string2Color('#000000'), fontWeight: FontWeight.w400),
                      ).marginOnly(right: 3),
                      Text(
                        'points',
                        style: TextStyle(fontSize: 16.0, color: ColorUtils.string2Color('#000000'), fontWeight: FontWeight.w400),
                      ).marginOnly(right: 3),
                      Text(
                        '-',
                        style: TextStyle(fontSize: 16.0, color: ColorUtils.string2Color('#000000'), fontWeight: FontWeight.w400),
                      ).marginOnly(right: 3),
                      Text(
                        '$point_max',
                        style: TextStyle(fontSize: 16.0, color: ColorUtils.string2Color('#000000'), fontWeight: FontWeight.w400),
                      ).marginOnly(right: 3),
                      Text(
                        'points',
                        style: TextStyle(fontSize: 16.0, color: ColorUtils.string2Color('#000000'), fontWeight: FontWeight.w400),
                      ).marginOnly(right: 3),
                    ],
                  ).paddingOnly(left: 15, right: 15, top: 20),
                  RangeSlider(
                    values: RangeValues(point_min.toDouble(), point_max.toDouble()), // 初始化范围
                    min: 0, // 最小值
                    max: 100, // 最大值
                    onChanged: (RangeValues values) {
                      setState(() {
                        point_min = values.start.toInt();
                        point_max = values.end.toInt();
                        _vm.rangeSliderChanged(values);
                        // 处理范围改变事件
                        print('Selected range: ${values.start} to ${values.end}');
                      });
                    },
                  ).marginOnly(top: 5),
                  CheckboxListTile(
                    title: Container(
                      transform: Matrix4.translationValues(-20.0, 0.0, 0.0),
                      child: Text(
                        'Only show rewards I can redeem',
                        style: TextStyle(fontSize: 14.0, color: ColorUtils.string2Color('#767676'), fontWeight: FontWeight.w400),
                      ),
                    ),
                    controlAffinity: ListTileControlAffinity.leading,
                    value: isSelected,
                    onChanged: (value) {
                      setState(() {
                        isSelected = value!;
                      });
                    },
                  ),
                  Row(
                    children: [
                      const SizedBox(width: 18),
                      Expanded(
                          flex: 1,
                          child: InkWell(
                            onTap: () async {
                              Navigator.of(context).pop();
                              _vm.applyClick();
                            },
                            child: MyTextView(
                              'Apply',
                              fontSize: 16,
                              paddingTop: 13,
                              paddingBottom: 13,
                              isFontMedium: true,
                              textAlign: TextAlign.center,
                              textColor: Colors.white,
                              backgroundColor: context.appColors.btnBgDefault,
                              cornerRadius: 7,
                            ),
                          )),
                      const SizedBox(width: 18),
                    ],
                  ).marginOnly(bottom: 30, top: 28),
                ],
              ),
            );
          });
        });
  }
}
