import 'package:auto_route/auto_route.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:telnow_mobile_new/src/cubit/menu_history_cubit.dart';
import 'package:telnow_mobile_new/src/cubit/user_data_cubit.dart';
import 'package:telnow_mobile_new/src/layouts/components/template.dart';
import 'package:telnow_mobile_new/src/layouts/web/request_create.dart';
import 'package:telnow_mobile_new/src/utils/U.dart';
import 'package:telnow_mobile_new/src/utils/dio_logging_interceptors.dart';

import '../../cubit/tab_history_cubit.dart';
import '../../utils/extensions.dart';
import '../../utils/ui_service.dart';
import '../mobile/request_create.dart';
import 'menu-history/build_filter.dart';
import 'menu-history/build_tab.dart';
import 'menu-history/done_container.dart';
import 'menu-history/ongoing_container.dart';

class WebHistoryPage extends StatefulWidget {
  const WebHistoryPage({super.key});

  @override
  State<WebHistoryPage> createState() => _WebHistoryPageState();
}

class _WebHistoryPageState extends State<WebHistoryPage> with TickerProviderStateMixin {
  late AnimationController _animationController;
  late TabController _tabController;

  var rating = [
    {'key': 1, 'image': "assets/image/icon/very_dissatisfied.png", 'label': 'disatisfied'.tr()},
    {'key': 2, 'image': "assets/image/icon/dissatisfied.png", 'label': 'lessSatisfied'.tr()},
    {'key': 3, 'image': "assets/image/icon/neutral.png", 'label': 'satisfied'.tr()},
    {'key': 4, 'image': "assets/image/icon/satisfied.png", 'label': 'verySatisfied'.tr()},
    {'key': 5, 'image': "assets/image/icon/very_satisfied.png", 'label': 'reallyPleased'.tr()},
  ];
  bool _timeLimit = false;

  @override
  void initState() {
    _animationController = AnimationController(vsync: this, duration: Duration(seconds: 1));
    _animationController.repeat(reverse: true);
    _tabController = TabController(length: 2, vsync: this);

    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<UserCubit>().getUser();
    });
    // TODO: implement initState
    _tabController.addListener(() {
      if (_tabController.indexIsChanging) {
        if (_tabController.index == 0) {
          context.read<MenuHistoryCubit>().setActiveTab(HistoryTab.ongoing);
        } else {
          context.read<MenuHistoryCubit>().setActiveTab(HistoryTab.done);
        }
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    _animationController.dispose();
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final userCubit = context.read<UserCubit>();

    eventBus.on().listen((event){
      debugPrint(event.toString());
    });

    if (userCubit.state.reset) {
      return RefreshPage(() {
      userCubit.setReset(false);
    });
    } else {
      if (_timeLimit) {
        return showButton(context);
      } else {
        return MultiBlocProvider(
          providers: [
            BlocProvider(
              create: (context) => MenuHistoryCubit()..init(),
            ),
            BlocProvider(
              create: (context) => OngoingCubit()..loadOngoing(),
            ),
            BlocProvider(
              create: (context) => DoneCubit()..loadDone(),
            ),
          ],
          child: Scaffold(
            backgroundColor: backgroundColor,
            body: BlocConsumer<MenuHistoryCubit, MenuHistoryState>(
              listener: (context, state) {
                if(state is ReloadPage){
                  context.read<MenuHistoryCubit>().setActiveTab(HistoryTab.done);
                  context.read<DoneCubit>().reloadPage();
                }
                if(state is CreateNewRequest){
                  var user = context.read<UserCubit>().state.user;
                  var request = state.request;
                  UIService.navigateTo(
                      U.webView(context) ?
                      WebReqCreatePage(user: user, request: request) :
                      MobReqCreatePage(user: user, request: request)
                  );
                }
                if(state is ShowError){
                  UIService.showError(state.error);
                }
              },
              builder: (context, state){
                return Column(
                  children: [
                    Container(
                      padding: EdgeInsets.symmetric(vertical: 25, horizontal: 100),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text('history'.tr(), style: TextStyle(color: textColor, fontSize: 17, fontWeight: FontWeight.w500), overflow: TextOverflow.ellipsis),
                          state.multiSelectMode ? GestureDetector(
                            child: Container(
                              padding: EdgeInsets.fromLTRB(16, 9, 16, 9),
                              decoration: BoxDecoration(color: primaryColor.withValues(alpha: 0.1), border: Border.all(color: primaryColor), borderRadius: BorderRadius.all(Radius.circular(50))),
                              child: Row(
                                children: [
                                  Text('delete'.tr(), style: TextStyle(color: primaryColor, fontSize: 14)),
                                  SizedBox(width: 5),
                                  U.iconsax('trash', color: primaryColor, size: 20)
                                ],
                              ),
                            ),
                            onTap: () {
                              showDialog(
                                context: context,
                                builder: (BuildContext contexts) {
                                  return AlertDialog(
                                    title: Text("deleteHistory".tr(), style: TextStyle(fontSize: 18),
                                    ),
                                    content: Text("deleteHistoryConfirm".tr()),
                                    actions: <Widget>[
                                      TextButton(
                                        child: Text("buttonNo".tr()),
                                        onPressed: () {
                                          Navigator.of(contexts).pop();
                                        },
                                      ),
                                      TextButton(
                                          onPressed: () async {
                                            Navigator.of(contexts).pop();
                                            // context.read<MenuHistoryCubit>().setLoading(true);
                                            var dataRequest = context.read<DoneCubit>().state.data;

                                            context.read<MenuHistoryCubit>().deleteData(dataRequest);
                                          },
                                          child: Text("buttonYes".tr())),
                                    ],
                                  );
                                },
                              );
                            },
                          ).withHover() : GestureDetector(
                            child: Text('buttonBack'.tr(), style: TextStyle(color: primaryColor, fontSize: 14)),
                            onTap: (){
                              var pid = U.getPidFromUrl(context.router.currentUrl);
                              context.router.removeLast();
                              context.navigateToPath("/app/$pid/menu");
                            },
                          ).withHover()
                        ],
                      ),
                    ),
                    divider(),
                    Container(
                      padding: EdgeInsets.symmetric(horizontal: 100),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(height: 16),
                          BuildTab(controller: _tabController),
                          SizedBox(height: 20),
                          BuildFilter(),
                        ],
                      ),
                    ),
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.fromLTRB(100, 20, 100, 0),
                        child: TabBarView(
                          controller: _tabController,
                          physics: const NeverScrollableScrollPhysics(),
                          children: [
                            OngoingContainer(),
                            DoneContainer(),
                          ],
                        ),
                      ),
                    )
                  ],
                );
              },
            ),
          )
        );
      }
    }
  }
}