import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:hmg_qline/constants/app_constants.dart';
import 'package:hmg_qline/models/generic_response_model.dart';
import 'package:hmg_qline/models/kiosk_queue_model.dart';
import 'package:hmg_qline/models/kiosk_ticket_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(
          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),
                      ],
                    ],
                  ),
                ),
              )
            ],
            const SizedBox(height: 12),
            Expanded(flex: 10, child: dataContentKiosk(context: context)),
            if (!screenConfigVM.globalConfigurationsModel.isWeatherReq && !screenConfigVM.globalConfigurationsModel.isPrayerTimeReq) ...[
              const SizedBox(height: 100),
            ],
          ],
        );
      },
    );
  }

  Widget kioskLanguageStateWidget(ScreenConfigViewModel screenConfigViewModel) {
    return GridView.builder(
      itemCount: 2,
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
      itemBuilder: (BuildContext context, int index) {
        return Padding(
          padding: const EdgeInsets.all(20),
          child: commonSelectionCardKiosk(
            screenConfigViewModel: screenConfigViewModel,
            title: index == 0 ? "English" : "عربي",
            icon: AppAssets.languageIcon,
            onTap: () async {
              if (index == 0) {
                if (screenConfigViewModel.globalConfigurationsModel.kioskQueueList != null && screenConfigViewModel.globalConfigurationsModel.kioskQueueList!.length == 1) {
                  await generateTicketForQueue(
                    screenConfigViewModel: screenConfigViewModel,
                    kioskQueueModel: screenConfigViewModel.globalConfigurationsModel.kioskQueueList![0],
                  );
                } else {
                  screenConfigViewModel.updateCurrentSelectedKioskLanguage(LanguageEnum.english);
                  screenConfigViewModel.updateKioskScreenState(KioskScreenStateEnums.queueSelectionState);
                }
              } else {
                if (screenConfigViewModel.globalConfigurationsModel.kioskQueueList != null && screenConfigViewModel.globalConfigurationsModel.kioskQueueList!.length == 1) {
                  await generateTicketForQueue(
                    screenConfigViewModel: screenConfigViewModel,
                    kioskQueueModel: screenConfigViewModel.globalConfigurationsModel.kioskQueueList![0],
                  );
                } else {
                  screenConfigViewModel.updateCurrentSelectedKioskLanguage(LanguageEnum.arabic);
                  screenConfigViewModel.updateKioskScreenState(KioskScreenStateEnums.queueSelectionState);
                }
              }
            },
          ),
        );
      },
    );
  }

  Widget kioskQueueSelectionStateWidget(ScreenConfigViewModel screenConfigViewModel) {
    bool isEnglish = screenConfigViewModel.currentSelectedKioskLanguage == LanguageEnum.english;

    return Directionality(
      textDirection: isEnglish ? TextDirection.ltr : TextDirection.rtl,
      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(
                  screenConfigViewModel: screenConfigViewModel,
                  title: screenConfigViewModel.currentSelectedKioskLanguage == LanguageEnum.english ? "${kioskQueueModel.queueName}" : "${kioskQueueModel.queueNameN}",
                  icon: AppAssets.kioskQueueIcon,
                  onTap: () async {
                    await generateTicketForQueue(screenConfigViewModel: screenConfigViewModel, kioskQueueModel: kioskQueueModel);
                  },
                ),
              ],
            );
          }),
    );
  }

  Widget kioskTicketNumberStateWidget(ScreenConfigViewModel screenConfigViewModel) {
    bool isEnglish = screenConfigViewModel.currentSelectedKioskLanguage == LanguageEnum.english;
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        AppText(
          isEnglish ? "Your Ticket Number is: " : "رقم تذكرتك هو:",
          fontSize: SizeConfig.getWidthMultiplier() * 6,
          textDirection: isEnglish ? TextDirection.ltr : TextDirection.rtl,
          fontHeight: 1,
          fontFamily: isEnglish ? AppStrings.fontNameCairo : AppStrings.fontNamePoppins,
        ),
        const SizedBox(height: 20),
        AppText(
          screenConfigViewModel.kioskPatientTicket!.patientCallNo ?? "",
          fontSize: SizeConfig.getWidthMultiplier() * 10,
          fontHeight: 1,
          fontWeight: FontWeight.bold,
          textDirection: isEnglish ? TextDirection.ltr : TextDirection.rtl,
          fontFamily: isEnglish ? AppStrings.fontNameCairo : AppStrings.fontNamePoppins,
        ),
        const SizedBox(height: 20),
        AppText(
          isEnglish ? "Please take the receipt and wait for your turn. \nThank you 😊" : "يرجى أخذ الإيصال وانتظار دورك.\n شكرًا لك 😊",
          fontSize: SizeConfig.getWidthMultiplier() * 3,
          textAlign: TextAlign.center,
          textDirection: isEnglish ? TextDirection.ltr : TextDirection.rtl,
          fontHeight: 1,
          fontFamily: isEnglish ? AppStrings.fontNameCairo : AppStrings.fontNamePoppins,
        ),
        const SizedBox(height: 100),
        InkWell(
          onTap: () {
            screenConfigViewModel.updateKioskScreenState(KioskScreenStateEnums.languageState);
          },
          child: AppText(
            isEnglish ? "Go to Main Page" : "اذهب إلى الصفحة الرئيسية",
            fontSize: SizeConfig.getWidthMultiplier() * 3,
            textAlign: TextAlign.center,
            textDecoration: TextDecoration.underline,
            textDirection: isEnglish ? TextDirection.ltr : TextDirection.rtl,
            fontHeight: 1,
            fontFamily: isEnglish ? AppStrings.fontNameCairo : AppStrings.fontNamePoppins,
          ),
        ),
      ],
    );
  }

  Future<void> generateTicketForQueue({
    required ScreenConfigViewModel screenConfigViewModel,
    required KioskQueueModel kioskQueueModel,
  }) async {
    screenConfigViewModel.updateKioskScreenState(KioskScreenStateEnums.busyState);
    KioskPatientTicket? kioskPatientTicket = await screenConfigViewModel.createTicketFromKiosk(
      projectId: kioskQueueModel.projectID ?? 0,
      queueId: kioskQueueModel.queueID ?? 0,
    );
    if (kioskPatientTicket == null) {
      screenConfigViewModel.updateKioskScreenState(KioskScreenStateEnums.languageState);
      return;
    }
    screenConfigViewModel.updateTicketGeneratedFromKiosk(kioskPatientTicket);
    screenConfigViewModel.updateKioskScreenState(KioskScreenStateEnums.ticketNoState);
  }

  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.ticketNoState => kioskTicketNumberStateWidget(screenConfigViewModel),
            KioskScreenStateEnums.busyState => const Center(child: 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(
            appBar: const AppHeader(),
            body: getBody(context: context),
            bottomNavigationBar: const AppFooter(),
          ),
        );
      },
    );
  }
}
