import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';
import 'package:smart_hotel_app/repositories/inspection_history_repository.dart';
import 'package:smart_hotel_app/services/inspection_history_service.dart';
import 'cubit/inspection_history_cubit.dart';
import 'cubit/inspection_history_state.dart';
import 'widget/statistics_card.dart';
import 'widget/inspection_record_item.dart';

@RoutePage()
class InspectionHistoryView extends StatelessWidget {
  final String deviceId;

  const InspectionHistoryView({super.key, @pathParam required this.deviceId});

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (_) => InspectionHistoryCubit(
        deviceId: deviceId,
        service: InspectionHistoryService(
          repository: InspectionHistoryRepository(),
        ),
      ),
      child: const _InspectionHistoryBody(),
    );
  }
}

class _InspectionHistoryBody extends StatefulWidget {
  const _InspectionHistoryBody();

  @override
  State<_InspectionHistoryBody> createState() => _InspectionHistoryBodyState();
}

class _InspectionHistoryBodyState extends State<_InspectionHistoryBody> {
  late final PagingController<int, InspectionRecord> _pagingController;

  @override
  void initState() {
    super.initState();
    _pagingController = PagingController<int, InspectionRecord>(
      getNextPageKey: (state) {
        if (state.keys == null || state.keys!.isEmpty) return 1;
        final total =
            context.read<InspectionHistoryCubit>().state.totalCount;
        final nextKey = state.nextIntPageKey;
        if ((nextKey - 1) * InspectionHistoryCubit.pageSize >= total) {
          return null;
        }
        return nextKey;
      },
      fetchPage: (pageKey) =>
          context.read<InspectionHistoryCubit>().fetchPage(pageKey),
    );
  }

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

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<InspectionHistoryCubit, InspectionHistoryState>(
      builder: (context, state) {
        return Scaffold(
          backgroundColor: const Color.fromRGBO(242, 243, 245, 1),
          appBar: AppBar(
            backgroundColor: Colors.white,
            elevation: 0,
            leading: IconButton(
              icon: const Icon(Icons.arrow_back_ios,
                  color: Color.fromRGBO(100, 116, 139, 1)),
              onPressed: () {
                context.popRoute();
              },
            ),
            title: Text(
              '巡检记录',
              style: TextStyle(
                color: const Color.fromRGBO(10, 13, 20, 1),
                fontSize: 32.sp,
                fontWeight: FontWeight.w500,
              ),
            ),
            centerTitle: true,
          ),
          body: PagingListener<int, InspectionRecord>(
            controller: _pagingController,
            builder: (context, pagingState, fetchNextPage) {
              return CustomScrollView(
                slivers: [
                  SliverToBoxAdapter(
                    child: Padding(
                      padding: EdgeInsets.symmetric(
                          horizontal: 28.w, vertical: 20.h),
                      child: StatisticsCard(
                        totalCount: state.totalCount,
                        passCount: state.passCount,
                        warningCount: state.warningCount,
                        failCount: state.failCount,
                      ),
                    ),
                  ),
                  SliverToBoxAdapter(
                    child: Padding(
                      padding: EdgeInsets.only(
                          left: 28.w, right: 28.w, bottom: 16.h),
                      child: Row(
                        children: [
                          Text(
                            '巡检历史',
                            style: TextStyle(
                              fontSize: 28.sp,
                              fontWeight: FontWeight.bold,
                              color:
                                  const Color.fromRGBO(10, 13, 20, 1.0),
                            ),
                          ),
                          Text(
                            ' (${state.totalCount})',
                            style: TextStyle(
                              fontSize: 28.sp,
                              fontWeight: FontWeight.bold,
                              color: const Color.fromRGBO(10, 13, 20, 1.0),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  SliverPadding(
                    padding: EdgeInsets.symmetric(horizontal: 28.w),
                    sliver: PagedSliverList<int, InspectionRecord>(
                      state: pagingState,
                      fetchNextPage: fetchNextPage,
                      builderDelegate:
                          PagedChildBuilderDelegate<InspectionRecord>(
                        firstPageProgressIndicatorBuilder: (_) => const Center(
                          child: CircularProgressIndicator(
                            color: Color.fromRGBO(66, 165, 245, 1.0),
                          ),
                        ),
                        newPageProgressIndicatorBuilder: (_) => const Center(
                          child: Padding(
                            padding: EdgeInsets.all(16),
                            child: CircularProgressIndicator(
                              color: Color.fromRGBO(66, 165, 245, 1.0),
                            ),
                          ),
                        ),
                        firstPageErrorIndicatorBuilder: (_) => Center(
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Text(
                                '加载失败: ${pagingState.error}',
                                style: TextStyle(
                                  fontSize: 28.sp,
                                  color: const Color.fromRGBO(
                                      255, 100, 101, 1),
                                ),
                                textAlign: TextAlign.center,
                              ),
                              SizedBox(height: 24.h),
                              ElevatedButton(
                                onPressed: fetchNextPage,
                                child: Text('重新加载',
                                    style:
                                        TextStyle(fontSize: 28.sp)),
                              ),
                            ],
                          ),
                        ),
                        noItemsFoundIndicatorBuilder: (_) => Padding(
                          padding: EdgeInsets.only(top: 60.h),
                          child: Text(
                            '暂无数据',
                            style: TextStyle(
                              fontSize: 28.sp,
                              color: const Color.fromRGBO(
                                  100, 116, 139, 1),
                            ),
                          ),
                        ),
                        newPageErrorIndicatorBuilder: (_) => Center(
                          child: Padding(
                            padding:
                                EdgeInsets.symmetric(vertical: 20.h),
                            child: Column(
                              children: [
                                Text(
                                  '加载失败: ${pagingState.error}',
                                  style: TextStyle(
                                    fontSize: 24.sp,
                                    color: const Color.fromRGBO(
                                        255, 100, 101, 1),
                                  ),
                                ),
                                SizedBox(height: 12.h),
                                TextButton(
                                  onPressed: fetchNextPage,
                                  child: Text('重试',
                                      style:
                                          TextStyle(fontSize: 24.sp)),
                                ),
                              ],
                            ),
                          ),
                        ),
                        itemBuilder: (_, item, __) {
                          return InspectionRecordItem(record: item);
                        },
                      ),
                    ),
                  ),
                  SliverToBoxAdapter(
                    child: SizedBox(height: 30.h),
                  ),
                ],
              );
            },
          ),
        );
      },
    );
  }
}