import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:hmg_qline/constants/app_constants.dart';
import 'package:hmg_qline/utilities/enums.dart';
import 'package:hmg_qline/utilities/extensions.dart';
import 'package:hmg_qline/utilities/lifecycle_handler.dart';
import 'package:hmg_qline/view_models/queuing_view_model.dart';
import 'package:hmg_qline/view_models/screen_config_view_model.dart';
import 'package:hmg_qline/views/common_widgets/app_footer.dart';
import 'package:hmg_qline/views/common_widgets/app_general_widgets.dart';
import 'package:hmg_qline/views/common_widgets/app_header.dart';
import 'package:hmg_qline/views/common_widgets/app_scaffold.dart';
import 'package:hmg_qline/views/main_queue_screen/components/priority_tickets.dart';
import 'package:hmg_qline/views/main_queue_screen/components/priority_tickets_sidelist.dart';
import 'package:hmg_qline/views/view_helpers/size_config.dart';
import 'package:provider/provider.dart';

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

  @override
  State<MainQueueScreen> createState() => _MainQueueScreenState();
}

class _MainQueueScreenState extends State<MainQueueScreen> {
  late LifecycleHandler lifecycleHandler;

  @override
  void initState() {
    super.initState();
    final ScreenConfigViewModel screenConfigViewModel = context.read<ScreenConfigViewModel>();
    lifecycleHandler = LifecycleHandler(
      onResumed: () => screenConfigViewModel.onAppResumed(),
      onPaused: () => screenConfigViewModel.onAppPaused(),
      onDetached: () => screenConfigViewModel.onAppDetached(),
    );
    lifecycleHandler.register();
  }

  @override
  void dispose() {
    lifecycleHandler.unregister();
    super.dispose();
  }

  Widget dataContent({required BuildContext context}) {
    return Consumer2(
      builder: (BuildContext context, ScreenConfigViewModel screenConfigViewModel, QueuingViewModel queuingViewModel, Widget? child) {
        //
        // // TODO:  FOR TEST
        // queuingViewModel.textToSpeechService.speechText(
        //   globalConfigurationsModel: screenConfigViewModel.globalConfigurationsModel,
        //   ticket: queuingViewModel.currentTickets.first,
        // );
        // screenConfigViewModel.getNextPrayerToShow();

        Widget widget = const SizedBox();
        String text = AppStrings.awaitingArrivalEng;
        String fontFamily = AppStrings.fontNamePoppins;

        // return Center(child: Image.asset("assets/images/majnu.JPG", fit: BoxFit.fill));
        // return intimationWidget(
        //   text: "Sarkar Farmanday nayy\n Jera Dhamaal naa Pavay.... !!",
        //   fontName: AppStrings.fontNamePoppins,
        //   isForRoomLevel: false,
        //   isRoomNoRequired: false,
        //   isForError: true,
        //   counterNo: 0,
        //   roomText: '',
        // );

        log("screenConfigViewModel: ${screenConfigViewModel.currentScreenIP}");
        if (screenConfigViewModel.currentQTypeEnum == QTypeEnum.general) {
          text = AppStrings.awaitingQueueNumberEng;
        }
        if (screenConfigViewModel.globalConfigurationsModel.screenLanguageEnum == LanguageEnum.arabic) {
          if (screenConfigViewModel.currentQTypeEnum == QTypeEnum.general) {
            text = AppStrings.awaitingQueueNumberAr;
          }
          text = AppStrings.awaitingArrivalAr;
          fontFamily = AppStrings.fontNameCairo;
        }

        if (screenConfigViewModel.state == ViewState.error && queuingViewModel.currentTickets.isEmpty) {
          widget = intimationWidget(
            text: AppStrings.configurationIssueContactAdmin,
            fontName: AppStrings.fontNamePoppins,
            isForRoomLevel: false,
            isRoomNoRequired: false,
            isForError: true,
            counterNo: 0,
            roomText: '',
          );
        } else if (queuingViewModel.currentTickets.isEmpty) {
          bool isForRoomLevel = screenConfigViewModel.globalConfigurationsModel.screenTypeEnum == ScreenTypeEnum.roomLevelScreen;
          widget = intimationWidget(
            text: text,
            fontName: fontFamily,
            isForRoomLevel: isForRoomLevel,
            isRoomNoRequired: screenConfigViewModel.globalConfigurationsModel.isRoomNoRequired ?? true,
            counterNo: screenConfigViewModel.globalConfigurationsModel.roomNo ?? 0,
            roomText: screenConfigViewModel.globalConfigurationsModel.roomTextEng ?? AppStrings.counterNo,
          );
        } else if (screenConfigViewModel.globalConfigurationsModel.screenTypeEnum == ScreenTypeEnum.roomLevelScreen) {
          widget = Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  counterNoText(
                    counterNo: screenConfigViewModel.globalConfigurationsModel.roomNo ?? 0,
                    roomText: screenConfigViewModel.globalConfigurationsModel.roomTextEng ?? AppStrings.counterNo,
                    isRoomNoRequired: screenConfigViewModel.globalConfigurationsModel.isRoomNoRequired ?? true,
                  ),
                  PriorityTickets(
                    tickets: [queuingViewModel.currentTickets.first],
                    globalConfigurationsModel: screenConfigViewModel.globalConfigurationsModel,
                  ),
                  const SizedBox.shrink()
                ],
              ),
            ],
          );
        } else {
          widget = PriorityTicketsWithSideSection(
            tickets: queuingViewModel.currentTickets,
            globalConfigurationsModel: screenConfigViewModel.globalConfigurationsModel,
            screenOrientationEnum: screenConfigViewModel.globalConfigurationsModel.orientationTypeEnum,
            showThankyouMessage: queuingViewModel.currentTickets.length <= AppConstants.thresholdForListUI,
            // showThankyouMessage: true,
          );
        }
        // else {
        //   widget = PriorityTickets(
        //     tickets: queuingViewModel.currentTickets,
        //     globalConfigurationsModel: screenConfigViewModel.globalConfigurationsModel,
        //   );
        // }

        return widget;
      },
    );
  }

  Widget getBody({required BuildContext context}) {
    return Consumer<ScreenConfigViewModel>(
      builder: (BuildContext context, ScreenConfigViewModel screenConfigVM, Widget? child) {
        return Column(
          children: [
            // if (screenConfigVM.globalConfigurationsModel.screenTypeEnum != ScreenTypeEnum.roomLevelScreen) ...[
            //   Expanded(
            //     flex: getFlexForScreenTypes(screenConfigVM),
            //     child: Padding(
            //       padding: const EdgeInsets.symmetric(horizontal: 20),
            //       child: Row(
            //         children: [
            //           if (screenConfigVM.globalConfigurationsModel.isWeatherReq) ...[
            //             getWeatherWidget(screenConfigVM),
            //           ],
            //           const SizedBox(width: 20),
            //           if (screenConfigVM.globalConfigurationsModel.isPrayerTimeReq) ...[
            //             getPrayerWidget(screenConfigVM),
            //           ],
            //         ],
            //       ),
            //     ),
            //   )
            // ],
            Expanded(
              flex: 10,
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: SizeConfig.getWidthMultiplier()! * 4),
                child: dataContent(context: context),
              ),
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final globalConfigurationsModel = context.read<ScreenConfigViewModel>().globalConfigurationsModel;
    log("isFromTakhasusiMain: ${globalConfigurationsModel.isFromTakhasusiMain}");
    return Selector<ScreenConfigViewModel, ScreenOrientationEnum>(
      selector: (context, screenConfigViewModel) => screenConfigViewModel.globalConfigurationsModel.orientationTypeEnum,
      builder: (BuildContext context, ScreenOrientationEnum screenOrientationEnum, Widget? child) {
        //TODO: For Testing Only

        log("=== ROTATEDBOX DEBUG ===");
        log("ScreenOrientationEnum: $screenOrientationEnum");
        log("isFromTakhasusiMain: ${globalConfigurationsModel.isFromTakhasusiMain}");
        final quarterTurns =
            globalConfigurationsModel.isFromTakhasusiMain ? screenOrientationEnum.getTurnsByOrientationForOlderVersions() : screenOrientationEnum.getTurnsByOrientationForNewVersions();
        log("QuarterTurns applied: $quarterTurns");
        log("MediaQuery size: ${MediaQuery.of(context).size}");
        log("MediaQuery orientation: ${MediaQuery.of(context).orientation}");
        log("========================");

        return RotatedBox(
          quarterTurns: quarterTurns,
          child: AppScaffold(
            backgroundColor: AppColors.backgroundColor,
            appBar: const AppHeader(),
            body: getBody(context: context),
            bottomNavigationBar: const AppFooter(),
          ),
        );
      },
    );
  }
}
