import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:hmg_qline/models/global_config_model.dart';
import 'package:hmg_qline/models/ticket_model.dart';
import 'package:hmg_qline/utilities/enums.dart';
import 'package:hmg_qline/view_models/screen_config_view_model.dart';
import 'package:hmg_qline/views/common_widgets/app_general_widgets.dart';
import 'package:hmg_qline/views/main_queue_screen/components/ticket_item_calling_card.dart';
import 'package:hmg_qline/views/main_queue_screen/components/ticket_item_normal_card.dart';
import 'package:hmg_qline/views/view_helpers/size_config.dart';
import 'package:provider/provider.dart';

class PriorityTickets extends StatelessWidget {
  final List<TicketDetailsModel> tickets;
  final GlobalConfigurationsModel globalConfigurationsModel;

  const PriorityTickets({required this.tickets, required this.globalConfigurationsModel, super.key});

  @override
  Widget build(BuildContext context) {
    log("tickets: ${tickets.length}");
    return Directionality(
      textDirection: globalConfigurationsModel.textDirection,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisSize: MainAxisSize.max,
        children: _buildTicketLayout(context),
      ),
    );
  }

  Widget _buildOtherTicketsRow(BuildContext context, {required int noOfTicketsToSkipFromStart, bool isHalf = false}) {
    final otherTickets = tickets.length > 2 ? tickets.sublist(noOfTicketsToSkipFromStart) : <TicketDetailsModel>[];
    if (otherTickets.isEmpty) return const SizedBox.shrink();

    return Row(
      children: List.generate(
        otherTickets.length,
        (index) => Expanded(
          child: Padding(
            padding: EdgeInsets.only(
              right: (index != otherTickets.length - 1 && globalConfigurationsModel.textDirection == TextDirection.ltr) ? SizeConfig.getWidthMultiplier() * 2 : 0,
              left: (index != otherTickets.length - 1 && globalConfigurationsModel.textDirection == TextDirection.rtl) ? SizeConfig.getWidthMultiplier() * 2 : 0,
            ),
            child: _buildSecondaryTicket(context, otherTickets[index], isHalf: isHalf),
          ),
        ),
      ),
    );
  }

  List<Widget> _buildTicketLayout(BuildContext context) {
    if (tickets.isEmpty) return [];

    switch (tickets.length) {
      case 1:
        return [_buildPrimaryTicket(context, tickets[0], isFullWidth: true)];
      case 2:
        return [
          Expanded(child: _buildPrimaryTicket(context, tickets[0], isHalf: true)),
          globalConfigurationsModel.isFromTakhasusiMain ? SizedBox(height: SizeConfig.getHeightMultiplier()! * 0.2) : SizedBox(height: SizeConfig.getHeightMultiplier()! * 0.5),
          Expanded(child: _buildSecondaryTicket(context, tickets[1], isHalf: true)),
        ];
      case 3:
      case 4:
        return [
          Expanded(child: _buildPrimaryTicket(context, tickets[0], isHalf: true)),
          globalConfigurationsModel.isFromTakhasusiMain ? SizedBox(height: SizeConfig.getHeightMultiplier()! * 0.2) : SizedBox(height: SizeConfig.getHeightMultiplier()! * 0.5),
          Expanded(child: _buildOtherTicketsRow(context, noOfTicketsToSkipFromStart: 1, isHalf: true)),
        ];

      default:
        return [
          Expanded(
            child: Row(
              children: [
                Expanded(
                  flex: 2,
                  child: _buildPrimaryTicket(context, tickets[0]),
                ),
                SizedBox(width: SizeConfig.getWidthMultiplier() * 2),
                Expanded(
                  flex: 1,
                  child: _buildSecondaryTicket(context, tickets[1]),
                ),
              ],
            ),
          ),
          // _buildCurrentServeText(),
          SizedBox(height: SizeConfig.getHeightMultiplier()! * 0.15),
          Expanded(child: _buildOtherTicketsRow(context, noOfTicketsToSkipFromStart: 2)),
        ];
    }
  }

  Widget _buildPrimaryTicket(BuildContext context, TicketDetailsModel ticket, {bool isFullWidth = false, bool isHalf = false}) {
    final screenConfigViewModel = context.read<ScreenConfigViewModel>();

    Widget primaryCallingCard = QueueItemCallingCard(
      qTypeEnum: screenConfigViewModel.currentQTypeEnum,
      isGradientRequired: true,
      isBorderRequired: true,
      isSingleTicket: isFullWidth,
      ticketNo: ticket.ticketModel?.queueNo ?? '',
      scale: _getTicketScale(),
      blink: true,
      roomNo: ticket.ticketModel?.roomNo ?? '',
      roomText: _getRoomText(),
      roomTextAr: _getRoomTextAr(),
      isClinicAdded: false,
      callTypeEnum: ticket.ticketModel?.callTypeEnum ?? CallTypeEnum.none,
      textDirection: globalConfigurationsModel.textDirection,
      screenTypeEnum: globalConfigurationsModel.screenTypeEnum,
      langTypeEnum: globalConfigurationsModel.screenLanguageEnum,
      globalConfigurationsModel: globalConfigurationsModel,
    );

    if (isHalf) {
      return Center(
        child: ConstrainedBox(
          constraints: BoxConstraints(
            maxWidth: MediaQuery.of(context).size.width * 0.7, // 60% of screen width
            minHeight: SizeConfig.getHeightMultiplier() * 2.2, // Minimum height
          ),
          child: Transform.scale(
            scale: _getTicketScale(),
            child: primaryCallingCard,
          ),
        ),
      );
    }

    if (isFullWidth) {
      return Center(
        child: ConstrainedBox(
          constraints: BoxConstraints(
            maxWidth: MediaQuery.of(context).size.width * 0.6, // 60% of screen width
            minHeight: SizeConfig.getHeightMultiplier() * 2, // Minimum height
          ),
          child: Transform.scale(
            scale: _getTicketScale() + 0.2,
            child: primaryCallingCard,
          ),
        ),
      );
    }

    return primaryCallingCard;
  }

  Widget _buildSecondaryTicket(BuildContext context, TicketDetailsModel ticket, {EdgeInsets? margin, bool isHalf = false}) {
    final screenConfigViewModel = context.read<ScreenConfigViewModel>();
    Widget secondaryCallingCard = QueueItemNormalCard(
      qTypeEnum: screenConfigViewModel.currentQTypeEnum,
      ticketNo: ticket.ticketModel?.queueNo ?? '',
      roomNo: ticket.ticketModel?.roomNo ?? '',
      roomText: _getRoomText(),
      roomTextAr: _getRoomTextAr(),
      isClinicAdded: false,
      callTypeEnum: ticket.ticketModel?.callTypeEnum ?? CallTypeEnum.none,
      textDirection: globalConfigurationsModel.textDirection,
      screenTypeEnum: globalConfigurationsModel.screenTypeEnum,
      langTypeEnum: globalConfigurationsModel.screenLanguageEnum,
      globalConfigurationsModel: globalConfigurationsModel,
    );

    if (isHalf) {
      return Center(
        child: ConstrainedBox(
          constraints: BoxConstraints(
            maxWidth: MediaQuery.of(context).size.width * 0.65, // 60% of screen width
            minHeight: SizeConfig.getHeightMultiplier() * 2, // Minimum height
          ),
          child: secondaryCallingCard,
        ),
      );
    }

    return secondaryCallingCard;
  }

  Widget _buildCurrentServeText() {
    bool isPortrait = globalConfigurationsModel.orientationTypeEnum == ScreenOrientationEnum.portraitUp || globalConfigurationsModel.orientationTypeEnum == ScreenOrientationEnum.portraitDown;
    return Padding(
      padding: EdgeInsets.symmetric(vertical: isPortrait ? SizeConfig.getHeightMultiplier() * 0.13 : SizeConfig.getHeightMultiplier() * 0.25),
      child: engArabicTextWithSeparatorWidget(
        englishText: globalConfigurationsModel.currentServeTextEng ?? "",
        arabicText: globalConfigurationsModel.currentServeTextArb ?? "",
      ),
    );
  }

  // Helper methods to reduce repetition
  double _getTicketScale() {
    return globalConfigurationsModel.screenTypeEnum == ScreenTypeEnum.roomLevelScreen
        ? 1.5
        : globalConfigurationsModel.isFromTakhasusiMain
            ? 0.9
            : 1.2;
  }

  String _getRoomText() {
    return globalConfigurationsModel.qTypeEnum == QTypeEnum.appointment ? globalConfigurationsModel.roomTextEng ?? "" : globalConfigurationsModel.counterTextEng ?? "";
  }

  String _getRoomTextAr() {
    return globalConfigurationsModel.qTypeEnum == QTypeEnum.appointment ? globalConfigurationsModel.roomTextArb ?? "" : globalConfigurationsModel.counterTextArb ?? "";
  }
}
