import 'package:flutter/material.dart';
import 'package:hmg_qline/config/routes.dart';
import 'package:hmg_qline/constants/app_constants.dart';
import 'package:hmg_qline/models/kiosk_language_config_model.dart';
import 'package:hmg_qline/models/kiosk_queue_model.dart';
import 'package:hmg_qline/utilities/enums.dart';
import 'package:hmg_qline/utilities/extensions.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/common_widgets/app_texts_widget.dart';
import 'package:hmg_qline/views/view_helpers/size_config.dart';
import 'package:provider/provider.dart';

class KioskMainScreen extends StatelessWidget {
  const KioskMainScreen({super.key});

  Widget getBody({required BuildContext context}) {
    return Consumer<ScreenConfigViewModel>(
      builder: (BuildContext context, ScreenConfigViewModel screenConfigVM, Widget? child) {
        return Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (screenConfigVM.globalConfigurationsModel.screenTypeEnum != ScreenTypeEnum.roomLevelScreen) ...[
              if (screenConfigVM.globalConfigurationsModel.isWeatherReq || screenConfigVM.globalConfigurationsModel.isPrayerTimeReq) ...[
                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),
                        ],
                      ],
                    ),
                  ),
                ),
                const SizedBox(height: 12),
              ]
            ],
            Expanded(flex: 10, child: Center(child: dataContentKiosk(context: context))),
            if (!screenConfigVM.globalConfigurationsModel.isWeatherReq && !screenConfigVM.globalConfigurationsModel.isPrayerTimeReq) ...[
              const SizedBox(height: 100),
            ],
          ],
        );
      },
    );
  }

  Widget kioskLanguageStateWidget(ScreenConfigViewModel screenConfigViewModel) {
    bool isLanguageConfigAvailable = screenConfigViewModel.globalConfigurationsModel.kioskLanguageConfigList != null;

    if (!isLanguageConfigAvailable) {
      return noPatientInQueue(
        text: AppStrings.configurationIssueContactAdmin,
        fontName: AppStrings.fontNamePoppins,
        isForRoomLevel: false,
        isRoomNoRequired: false,
        counterNo: 0,
        roomText: '',
      );
    }
    return GridView.builder(
      itemCount: isLanguageConfigAvailable ? screenConfigViewModel.globalConfigurationsModel.kioskLanguageConfigList!.length : 2,
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
      itemBuilder: (BuildContext context, int index) {
        KioskLanguageConfigModel languageConfigModel = screenConfigViewModel.globalConfigurationsModel.kioskLanguageConfigList![index];
        return Padding(
          padding: const EdgeInsets.all(20),
          child: commonSelectionCardKiosk(
            textDirection: screenConfigViewModel.globalConfigurationsModel.textDirection,
            screenLanguageEnum: screenConfigViewModel.globalConfigurationsModel.screenLanguageEnum,
            title: languageConfigModel.languageName ?? "",
            icon: AppAssets.languageIcon,
            onTap: () async {
              screenConfigViewModel.updateCurrentSelectedKioskLanguageModel(languageConfigModel);

              if (screenConfigViewModel.globalConfigurationsModel.kioskQueueList != null && screenConfigViewModel.globalConfigurationsModel.kioskQueueList!.length == 1) {
                screenConfigViewModel.updateCurrentSelectedKioskQueueModel(screenConfigViewModel.globalConfigurationsModel.kioskQueueList!.first);

                if (screenConfigViewModel.globalConfigurationsModel.kioskQueueList!.first.isPharmacyQueue ?? false) {
                  screenConfigViewModel.updateKioskScreenState(KioskScreenStateEnums.askPrescriptionState);
                } else {
                  await screenConfigViewModel.generateTicketForQueue(
                    kioskQueueModel: screenConfigViewModel.currentSelectedKioskQueueModel,
                  );
                }
              } else {
                screenConfigViewModel.updateKioskScreenState(KioskScreenStateEnums.queueSelectionState);
              }
            },
          ),
        );
      },
    );
  }

  Widget configurationWidgetIssue() {
    return Center(
      child: noPatientInQueue(
        text: AppStrings.configurationIssueContactAdmin,
        fontName: AppStrings.fontNamePoppins,
        isForRoomLevel: false,
        isRoomNoRequired: false,
        counterNo: 0,
        roomText: '',
      ),
    );
  }

  Widget kioskQueueSelectionStateWidget(ScreenConfigViewModel screenConfigViewModel) {
    bool isQueueListAvailable = screenConfigViewModel.globalConfigurationsModel.kioskQueueList != null && screenConfigViewModel.globalConfigurationsModel.kioskQueueList!.isNotEmpty;
    if (!isQueueListAvailable) {
      return configurationWidgetIssue();
    }
    TextDirection textDirection = screenConfigViewModel.currentSelectedKioskLanguage?.languageTextDirection ?? TextDirection.ltr;
    return Directionality(
      textDirection: textDirection,
      child: GridView.builder(
          itemCount: screenConfigViewModel.globalConfigurationsModel.kioskQueueList!.length,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: (screenConfigViewModel.globalConfigurationsModel.orientationTypeEnum == ScreenOrientationEnum.portraitUp ||
                    screenConfigViewModel.globalConfigurationsModel.orientationTypeEnum == ScreenOrientationEnum.portraitDown)
                ? 2
                : 3,
          ),
          itemBuilder: (BuildContext context, int index) {
            KioskQueueModel kioskQueueModel = screenConfigViewModel.globalConfigurationsModel.kioskQueueList![index];
            return Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                commonSelectionCardKiosk(
                  textDirection: textDirection,
                  screenLanguageEnum: screenConfigViewModel.globalConfigurationsModel.screenLanguageEnum,
                  title: textDirection == TextDirection.ltr ? "${kioskQueueModel.queueName}" : "${kioskQueueModel.queueNameN}",
                  icon: AppAssets.kioskQueueIcon,
                  onTap: () async {
                    screenConfigViewModel.updateCurrentSelectedKioskQueueModel(kioskQueueModel);
                    if (kioskQueueModel.isPharmacyQueue ?? false) {
                      screenConfigViewModel.updateKioskScreenState(KioskScreenStateEnums.askPrescriptionState);
                    } else {
                      await screenConfigViewModel.generateTicketForQueue(kioskQueueModel: kioskQueueModel);
                    }
                  },
                ),
              ],
            );
          }),
    );
  }

  Widget kioskAskPrescriptionState(ScreenConfigViewModel screenConfigViewModel, BuildContext context) {
    KioskLanguageConfigModel? kioskSelectedLanguageModel = screenConfigViewModel.currentSelectedKioskLanguage;
    TextDirection textDirection = screenConfigViewModel.currentSelectedKioskLanguage?.languageTextDirection ?? TextDirection.ltr;
    String fontFamily = (textDirection == TextDirection.rtl) ? AppStrings.fontNameCairo : AppStrings.fontNamePoppins;
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: AppText(
            "If you have a prescription. Please enter your patient number or scan your profile QR from Sulaiman Al Habib Mobile App?",
            fontSize: SizeConfig.getWidthMultiplier() * 4,
            textAlign: TextAlign.center,
            textDirection: textDirection,
            fontFamily: fontFamily,
          ),
        ),
        customShadowTextField(
          controller: screenConfigViewModel.patientIdController,
          hintText: "Enter Patient ID here",
          keyboardType: TextInputType.number,
          onSubmitted: screenConfigViewModel.onPatientIdSubmitted,
        ),
        commonShadowButton(
            screenLanguageEnum: screenConfigViewModel.globalConfigurationsModel.screenLanguageEnum,
            textDirection: textDirection,
            title: "Scan QR from  HMG App",
            icon: "",
            fontSize: SizeConfig.getWidthMultiplier() * 4,
            onTap: () => context.navigateTo(AppRoutes.kioskQrScannerScreen)),
        // const SizedBox(height: 50),
        commonShadowButton(
          screenLanguageEnum: screenConfigViewModel.globalConfigurationsModel.screenLanguageEnum,
          textDirection: textDirection,
          title: "I don't have a prescription.",
          icon: "",
          fontSize: SizeConfig.getWidthMultiplier() * 4,
          onTap: () async {
            await screenConfigViewModel.generateTicketForQueue(
              kioskQueueModel: screenConfigViewModel.currentSelectedKioskQueueModel,
            );
          },
        ),
        const SizedBox(height: 10),
        InkWell(
          onTap: () => screenConfigViewModel.updateKioskScreenState(KioskScreenStateEnums.languageState),
          child: AppText(
            kioskSelectedLanguageModel?.goBackToMainPage ?? "Go to Main Page",
            fontSize: SizeConfig.getWidthMultiplier() * 4,
            textAlign: TextAlign.center,
            textDecoration: TextDecoration.underline,
            textDirection: textDirection,
            fontHeight: 1,
            fontFamily: fontFamily,
          ),
        ),
      ],
    );
  }

  Widget kioskTicketNumberStateWidget(ScreenConfigViewModel screenConfigViewModel) {
    KioskLanguageConfigModel? kioskSelectedLanguageModel = screenConfigViewModel.currentSelectedKioskLanguage;
    TextDirection textDirection = screenConfigViewModel.currentSelectedKioskLanguage?.languageTextDirection ?? TextDirection.ltr;
    String fontFamily = (textDirection == TextDirection.rtl) ? AppStrings.fontNameCairo : AppStrings.fontNamePoppins;
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        AppText(
          kioskSelectedLanguageModel?.yourTicketNoText ?? "",
          fontSize: SizeConfig.getWidthMultiplier() * 6,
          textDirection: textDirection,
          fontHeight: 1,
          fontFamily: fontFamily,
        ),
        const SizedBox(height: 20),
        AppText(
          screenConfigViewModel.kioskPatientTicket!.patientCallNo ?? "",
          fontSize: SizeConfig.getWidthMultiplier() * 10,
          fontHeight: 1,
          fontWeight: FontWeight.bold,
          textDirection: textDirection,
          fontFamily: fontFamily,
        ),
        const SizedBox(height: 20),
        AppText(
          "${kioskSelectedLanguageModel?.waitForYourTurnText ?? "Please take the receipt and wait for your turn."} \n ${kioskSelectedLanguageModel?.thankYouText ?? "Thank you"}",
          fontSize: SizeConfig.getWidthMultiplier() * 3,
          textAlign: TextAlign.center,
          textDirection: textDirection,
          fontHeight: 1,
          fontFamily: fontFamily,
        ),
        const SizedBox(height: 100),
        InkWell(
          onTap: () {
            screenConfigViewModel.updateKioskScreenState(KioskScreenStateEnums.languageState);
          },
          child: AppText(
            kioskSelectedLanguageModel?.goBackToMainPage ?? "Go to Main Page",
            fontSize: SizeConfig.getWidthMultiplier() * 3,
            textAlign: TextAlign.center,
            textDecoration: TextDecoration.underline,
            textDirection: textDirection,
            fontHeight: 1,
            fontFamily: fontFamily,
          ),
        ),
      ],
    );
  }

  Widget dataContentKiosk({required BuildContext context}) {
    return Padding(
      padding: const EdgeInsets.all(10),
      child: Consumer(
        builder: (BuildContext context, ScreenConfigViewModel screenConfigViewModel, Widget? child) {
          return switch (screenConfigViewModel.kioskScreenStateEnum) {
            KioskScreenStateEnums.languageState => kioskLanguageStateWidget(screenConfigViewModel),
            KioskScreenStateEnums.queueSelectionState => kioskQueueSelectionStateWidget(screenConfigViewModel),
            KioskScreenStateEnums.askPrescriptionState => kioskAskPrescriptionState(screenConfigViewModel, context),
            KioskScreenStateEnums.ticketNumState => kioskTicketNumberStateWidget(screenConfigViewModel),
            KioskScreenStateEnums.busyState => const CircularProgressIndicator(),
          };
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Selector<ScreenConfigViewModel, ScreenOrientationEnum>(
      selector: (context, screenConfigViewModel) => screenConfigViewModel.globalConfigurationsModel.orientationTypeEnum,
      builder: (BuildContext context, ScreenOrientationEnum screenOrientationEnum, Widget? child) {
        return RotatedBox(
          quarterTurns: screenOrientationEnum.getTurnsByOrientation(),
          child: AppScaffold(
            resizeToAvoidBottomInset: false,
            appBar: const AppHeader(),
            body: getBody(context: context),
            bottomNavigationBar: const AppFooter(),
          ),
        );
      },
    );
  }
}
