import 'package:auto_route/auto_route.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:cs_resources/theme/app_colors_theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/my_text_view.dart';
import 'package:widgets/widget_export.dart';

import 'item_manage.dart';
import 'manage_view_model.dart';

@RoutePage()
class ManageScreen extends HookConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final viewModel = ref.read(manageViewModelProvider.notifier);
    final state = ref.watch(manageViewModelProvider);

    useEffect(() {
      // 组件挂载时执行 - 执行接口请求
      Future.microtask(() => viewModel.fetchList());
      return () {
        // 组件卸载时执行
      };
    }, []);

    return SizedBox(
      width: double.infinity,
      height: double.infinity,
      child: EasyRefresh(
        controller: viewModel.refreshController,
        onRefresh: viewModel.onRefresh,
        onLoad: viewModel.loadMore,
        child: LoadStateLayout(
          state: state.loadingState,
          errorMessage: state.errorMessage,
          errorRetry: () {
            viewModel.retryRequest();
          },
          successSliverWidget: [
            //添加新卡
            SliverToBoxAdapter(
              child: MyTextView(
                S.current.add_new_card,
                fontSize: 16,
                textAlign: TextAlign.center,
                marginLeft: 22.5,
                marginTop: 14,
                marginBottom: 15,
                marginRight: 22.5,
                cornerRadius: 5,
                paddingTop: 12,
                paddingBottom: 12,
                onClick: viewModel.gotoAddCardPage,
                borderWidth: 1,
                borderColor: context.appColors.textPrimary,
                isFontMedium: true,
                textColor: context.appColors.textPrimary,
              ),
            ),

            //列表
            SliverList(
                delegate: SliverChildBuilderDelegate(
              (context, index) {
                return ManageItem(
                  index: index,
                  item: state.datas[index],
                  deleteAction: () {
                    viewModel.showDeleteDialog(index);
                  },
                ).onTap(() {
                  viewModel.setAsPrimary(index);
                });
              },
              childCount: state.datas.length,
            ))
          ],
        ),
      ).marginOnly(top: 5, bottom: 5),
    );
  }
}
