import 'package:cpt_rewards/modules/rewards_detail/rewards_detail_page.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:cs_resources/theme/app_colors_theme.dart';
import 'package:cs_resources/theme/theme_config.dart';
import 'package:domain/entity/rewards_search_entity.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/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_search_vm.dart';

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

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

  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),
            Row(
              children: [
                Text(
                  '$point',
                  style: TextStyle(fontSize: 19.0, color: context.appColors.textBlack, fontWeight: FontWeight.w500),
                ),
                Text(
                  '$originalPoint',
                  style: TextStyle(
                      decoration: TextDecoration.lineThrough,
                      decorationColor: context.appColors.textBlack,
                      decorationStyle: TextDecorationStyle.solid,
                      fontSize: 12.0,
                      color: context.appColors.textBlack,
                      fontWeight: FontWeight.w400),
                ).marginOnly(left: 5, right: 5),
                Text(
                  S.current.points,
                  style: TextStyle(fontSize: 13.0, color: context.appColors.textBlack, fontWeight: FontWeight.w400),
                ),
              ],
            ),
          ],
        ).onTap(() {
          RewardsDetailPage.startInstance(id: id);
        }),
      ],
    ).paddingOnly(top: 0);
  }

  // listitem
  Widget _buildSaleItem(BuildContext context, WidgetRef ref, _vm, item) {
    return Container(
      decoration: BoxDecoration(
        color: context.appColors.whiteBG,
        borderRadius: const BorderRadius.all(Radius.circular(6.0)),
        boxShadow: [BoxShadow(color: context.appColors.itemBGShadow)],
      ),
      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: [
                _buildItemLeftSection(context, ref, item, _vm).marginOnly(bottom: 5),
              ],
            ).paddingOnly(left: 20, right: 20),
          ).constrained(
            minHeight: 235,
          ),
        ],
      ),
    ).marginOnly(left: 15, bottom: 15, right: 15);
  }

  // SearchOf
  Widget _buildSearchOf(BuildContext context, WidgetRef ref, _vm, detailInfo) {
    List recent = detailInfo.recent;
    List trending = detailInfo.trending;
    List<RewardsSearchRewards> rewards = detailInfo.rewards;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        recent.length > 0 ? _buildSearchRecent(context, ref, _vm, recent) : Container(),
        trending.length > 0 ? _buildSearchTrending(context, ref, _vm, trending) : Container(),
        rewards.length > 0 ? _buildSearchRecently(context, ref, _vm, rewards) : Container(),
      ],
    );
  }

// Recent
  Widget _buildSearchRecent(BuildContext context, WidgetRef ref, _vm, recent) {
    // List itemsList = _vm.state.list.toList();
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text(
          S.current.recent_searches,
          style: TextStyle(fontSize: 16.0, color: context.appColors.textBlack, fontWeight: FontWeight.w500),
        ).marginOnly(bottom: 20),
        Wrap(
            direction: Axis.horizontal, // 水平方向排列
            spacing: 10.0, // 子组件之间的间距
            runSpacing: 15.0, // 子组件行与行之间的间距
            children: List.generate(recent.length, (index) {
              return _buildSearchRecentItem(context, ref, _vm, recent[index]);
            }))
      ],
    ).marginOnly(bottom: 20);
  }

  Widget _buildSearchRecentItem(BuildContext context, WidgetRef ref, _vm, recent) {
    return Container(
      decoration: BoxDecoration(
        color: context.appColors.whiteBG,
        borderRadius: BorderRadius.all(Radius.circular(3.0)),
      ),
      padding: EdgeInsets.all(10),
      child: Text(
        recent,
        style: TextStyle(
            fontSize: 14.0,
            color: DarkThemeUtil.multiColors(context, ColorUtils.string2Color('#969696'), darkColor: Colors.white),
            fontWeight: FontWeight.w400),
      ),
    ).onTap(() {
      _vm.searchIn(recent);
    });
  }

  // Trending
  Widget _buildSearchTrending(BuildContext context, WidgetRef ref, _vm, trending) {
    // List itemsList = _vm.state.list.toList();
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text(
          S.current.trending_searches,
          style: TextStyle(fontSize: 16.0, color: context.appColors.textBlack, fontWeight: FontWeight.w500),
        ).marginOnly(bottom: 20),
        Wrap(
            direction: Axis.horizontal, // 水平方向排列
            spacing: 10.0, // 子组件之间的间距
            runSpacing: 15.0, // 子组件行与行之间的间距
            children: List.generate(trending.length, (index) {
              return _buildSearchTrendingItem(context, ref, _vm, trending[index]);
            }))
      ],
    ).marginOnly(bottom: 20);
  }

  Widget _buildSearchTrendingItem(BuildContext context, WidgetRef ref, _vm, trending) {
    return Container(
      decoration: BoxDecoration(
        color: context.appColors.whiteBG,
        borderRadius: BorderRadius.all(Radius.circular(3.0)),
      ),
      padding: const EdgeInsets.all(10),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
           MyAssetImage(
            Assets.rewardsRewardsHost,
            width: 12,
            height: 14,
             color: DarkThemeUtil.multiColors(context, AppColorsTheme.colorPrimary, darkColor: Colors.white),
          ).marginOnly(right: 5),
          Text(
            trending,
            style: TextStyle(
                fontSize: 14.0,
                color: DarkThemeUtil.multiColors(context, ColorUtils.string2Color('#969696'), darkColor: Colors.white),
                fontWeight: FontWeight.w400),
          ),
        ],
      ),
    ).onTap(() {
      _vm.searchIn(trending);
    });
  }

  // Recently
  Widget _buildSearchRecently(BuildContext context, WidgetRef ref, _vm, rewards) {
    // List itemsList = _vm.state.list.toList();
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text(
          S.current.recently_viewed,
          style: TextStyle(fontSize: 16.0, color: context.appColors.textBlack, fontWeight: FontWeight.w500),
        ).marginOnly(bottom: 18),
        Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: List.generate(rewards.length, (index) {
              return _buildSearchItem(context, ref, _vm, rewards[index]);
            }))
      ],
    );
  }

  Widget _buildSearchItem(BuildContext context, WidgetRef ref, _vm, item) {
    RewardsSearchRewards itm = item;
    int point = itm.point ?? 0;
    int originalPoint = itm.originalPoint ?? 0;
    int id = itm.id;
    return Container(
        // width: MediaQuery.of(context).size.width / 2 - 25,
        // height: 240,
        padding: const EdgeInsets.only(bottom: 20),
        decoration:  BoxDecoration(
          color: context.appColors.whiteBG,
          borderRadius: const BorderRadius.all(Radius.circular(6.0)),
          boxShadow: [BoxShadow(color: context.appColors.itemBGShadow)],
        ),
        child: Column(
          children: [
            MyLoadImage(
              item.resources?[0] ?? '',
              width: MediaQuery.of(context).size.width,
              height: 150,
            ),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  maxLines: 1, // 设置最大行数为2
                  overflow: TextOverflow.ellipsis, // 超出部分用省略号表示
                  item.name ?? '',
                  style:  TextStyle(fontSize: 15.0, color: context.appColors.textBlack, fontWeight: FontWeight.w500),
                ).marginOnly(bottom: 5, top: 10),
                Row(
                  children: [
                    Text(
                      '$point',
                      style:  TextStyle(fontSize: 18.0, color: context.appColors.textBlack, fontWeight: FontWeight.w500),
                    ),
                    Text(
                      '$originalPoint',
                      style: TextStyle(
                          decoration: TextDecoration.lineThrough,
                          decorationColor: ColorUtils.string2Color('#808DAF'),
                          decorationStyle: TextDecorationStyle.solid,
                          fontSize: 13.0,
                          color: DarkThemeUtil.multiColors(context, ColorUtils.string2Color('#808DAF'),darkColor: Colors.white),
                          fontWeight: FontWeight.w400),
                    ).marginOnly(left: 5, right: 5),
                    Text(
                      S.current.points,
                      style:  TextStyle(fontSize: 13.0, color: context.appColors.textBlack, fontWeight: FontWeight.w400),
                    ),
                  ],
                )
              ],
            ).paddingOnly(top: 12, left: 12, right: 12)
          ],
        )).marginOnly(bottom: 13).onTap(() {
      RewardsDetailPage.startInstance(id: id);
    });
  }

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final _vm = ref.read(rewardsSearchVmProvider.notifier);
    final state = ref.watch(rewardsSearchVmProvider);
    bool searchIs = state.searchIs ?? true;
    RewardsSearchEntity? detailInfo = state.detailInfo;
    useEffect(() {
      // 组件挂载时执行 - 执行接口请求
      Future.microtask(() => _vm.initPageData());
      return () {
        // 组件卸载时执行
        Log.d("property_news_page 组件卸载时执行");
      };
    }, []);
    return Scaffold(
      appBar: MyAppBar.searchAppBar(
        context,
        onSearch: (value) {
          _vm.searchIn(value);
        },
        value: state.keyword,
        backgroundColor: context.appColors.backgroundWhite,
        systemUiOverlayStyle: ThemeConfig.systemUiOverlayStyleLightThemeBlack,
      ),
      body: searchIs
          ? LoadStateLayout(
              state: state.loadingState,
              errorMessage: state.errorMessage,
              errorRetry: () {
                _vm.retryRequest();
              },
              successWidget: SingleChildScrollView(
                scrollDirection: Axis.vertical,
                physics: const BouncingScrollPhysics(),
                clipBehavior: Clip.none,
                child: Container(
                    width: MediaQuery.of(context).size.width,
                    color: context.appColors.backgroundDark,
                    padding: const EdgeInsets.only(top: 20, left: 15, right: 15),
                    child: _buildSearchOf(context, ref, _vm, detailInfo)),
              ))
          : Container(
              child: Column(
                children: [
                  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)]),
                      ),
                    ),
                  )
                ],
              ),
            ),
    );
  }
}
