import 'package:comwell_key_app/common/components/comwell_app_bar.dart';
import 'package:comwell_key_app/common/const.dart';
import 'package:comwell_key_app/themes/light_theme.dart';
import 'package:comwell_key_app/common/components/room_image_carousel.dart';
import 'package:comwell_key_app/up_sales/components/facilities_bottom_sheet.dart';
import 'package:comwell_key_app/up_sales/components/facility_icon_text.dart';
import 'package:comwell_key_app/up_sales/components/up_sales_bottom_button.dart';
import 'package:comwell_key_app/up_sales/cubit/up_sales_cubit.dart';
import 'package:comwell_key_app/up_sales/cubit/up_sales_state.dart';
import 'package:comwell_key_app/up_sales/models/facility_type.dart';
import 'package:comwell_key_app/up_sales/models/room_upgrade_list.dart';
import 'package:comwell_key_app/utils/l10n_utils.dart';
import 'package:flutter/material.dart';
import 'package:comwell_key_app/up_sales/components/tags.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class RoomUpgradePage extends StatefulWidget {
  final RoomUpgradeList roomUpgradeList;

  const RoomUpgradePage({super.key, required this.roomUpgradeList});

  @override
  State<RoomUpgradePage> createState() => _RoomUpgradePageState();
}

class _RoomUpgradePageState extends State<RoomUpgradePage> {
  bool _isExpanded = false;

  List<FacilityType> get allFacilities => [
    ...widget.roomUpgradeList.roomUpgrade?.facilityTypes ?? [],
  ];

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final isSelected = widget.roomUpgradeList.isRoomUpgradeSelected;
    final height = MediaQuery.of(context).size.height;

    return BlocBuilder<UpSalesCubit, UpSalesState>(
      builder: (context, state) {
        final cubit = context.read<UpSalesCubit>();
        return Scaffold(
          extendBodyBehindAppBar: true,
          appBar: const ComwellAppBar(),
          backgroundColor: Theme.of(context).colorScheme.surface,
          body: SingleChildScrollView(
            physics: const AlwaysScrollableScrollPhysics(),
            child: ConstrainedBox(
              constraints: BoxConstraints(
                minHeight: height - kComwellAppBarHeight - 80,
              ),
              child: Column(
                children: [
                  RoomImageCarousel(
                    images: widget.roomUpgradeList.roomUpgrade?.images.toList() ?? [],
                  ),
                  Container(
                    width: double.infinity,
                    decoration: BoxDecoration(
                      color: Theme.of(context).colorScheme.surface,
                      borderRadius: const BorderRadius.only(
                        topLeft: Radius.circular(24),
                        topRight: Radius.circular(24),
                      ),
                    ),
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Expanded(
                                child: Text(
                                  widget.roomUpgradeList.roomUpgrade?.name ?? '',
                                  style: theme.textTheme.headlineLarge,
                                ),
                              ),
                              const SizedBox(width: 12),
                              if (widget.roomUpgradeList.roomUpgrade?.roomSize != null)
                                TagWidget(
                                  text: '${widget.roomUpgradeList.roomUpgrade?.roomSize} M2',
                                  textColor: sandColor,
                                ),
                            ],
                          ),
                          const SizedBox(height: 12),
                          Text(
                            widget.roomUpgradeList.roomUpgrade?.description ?? '',
                            style: theme.textTheme.bodySmall,
                            maxLines: _isExpanded ? null : 3,
                            overflow: _isExpanded ? null : TextOverflow.ellipsis,
                          ),
                          const SizedBox(height: 4),
                          GestureDetector(
                            onTap: () {
                              setState(() {
                                _isExpanded = !_isExpanded;
                              });
                            },
                            child: Text(
                              _isExpanded ? context.strings.read_less : context.strings.read_more,
                              style: theme.textTheme.bodySmall?.copyWith(
                                color: sandColor,
                                decoration: TextDecoration.underline,
                                decorationColor: sandColor,
                              ),
                            ),
                          ),
                          const SizedBox(height: 24),
                          // Facilities row
                          Wrap(
                            spacing: 8,
                            runSpacing: 8,
                            children: [
                              ...widget.roomUpgradeList.roomUpgrade?.facilityTypes
                                      .map((f) => FacilityIconText(facility: f, showDivider: true))
                                      .toList() ??
                                  [],
                              GestureDetector(
                                onTap: () => _showFacilitiesSheet(context),
                                child: Padding(
                                  padding: const EdgeInsets.symmetric(horizontal: 4.0),
                                  child: Text(
                                    context.strings.see_all_facilities,
                                    style: theme.textTheme.bodySmall?.copyWith(
                                      color: sandColor,
                                      decoration: TextDecoration.underline,
                                      decorationColor: sandColor,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                          const SizedBox(height: 32),
                        ],
                      ),
                    ),
                  ),
                  // Booking button
                ],
              ),
            ),
          ),
          bottomNavigationBar: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Divider(color: colorDivider),
              UpSalesBottomButton(
                onContinue: () {
                  Navigator.pop(context, [widget.roomUpgradeList.roomUpgrade, isSelected]);
                },
                extrasTotalPrice: cubit.extrasTotalPrice,
                selectedRoomUpgrade: state.selectedRoomUpgrade,
                children: [
                  isSelected
                      ? Text(
                          context.strings.remove_from_booking,
                          style: theme.textTheme.headlineSmall?.copyWith(color: Colors.white),
                        )
                      : Text(
                          context.strings.add_to_booking,
                          style: theme.textTheme.headlineSmall?.copyWith(color: Colors.white),
                        ),
                  isSelected
                      ? Text(
                          "-${context.strings.total_charge_value(widget.roomUpgradeList.roomUpgrade?.price.toString() ?? '0')}",
                          style: theme.textTheme.headlineSmall?.copyWith(color: Colors.white),
                        )
                      : Text(
                          "+${context.strings.total_charge_value(widget.roomUpgradeList.roomUpgrade?.price.toString() ?? '0')}",
                          style: theme.textTheme.headlineSmall?.copyWith(color: Colors.white),
                        ),
                ],
              ),
            ],
          ),
        );
      },
    );
  }

  void _showFacilitiesSheet(BuildContext context) {
    showModalBottomSheet<void>(
      context: context,
      isScrollControlled: true,
      enableDrag: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
      ),
      builder: (context) {
        return ConstrainedBox(
          constraints: BoxConstraints(
            maxHeight: MediaQuery.of(context).size.height - kComwellAppBarHeight,
          ),
          child: FacilitiesBottomSheet(facilities: allFacilities),
        );
      },
    );
  }
}