import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/analytics/modules/air_quality/helpers/fetch_air_quality_data_helper.dart';
import 'package:syncrow_web/pages/analytics/modules/analytics/blocs/analytics_date_picker_bloc/analytics_date_picker_bloc.dart';
import 'package:syncrow_web/pages/analytics/modules/analytics/blocs/analytics_tab/analytics_tab_bloc.dart';
import 'package:syncrow_web/pages/analytics/modules/analytics/enums/analytics_page_tab.dart';
import 'package:syncrow_web/pages/analytics/modules/analytics/widgets/analytics_date_filter_button.dart';
import 'package:syncrow_web/pages/analytics/modules/analytics/widgets/analytics_page_tab_button.dart';
import 'package:syncrow_web/pages/analytics/modules/energy_management/helpers/fetch_energy_management_data_helper.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart';
import 'package:syncrow_web/utils/style.dart';

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

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<AnalyticsTabBloc, AnalyticsPageTab>(
      buildWhen: (previous, current) => previous != current,
      builder: (context, selectedTab) => Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          Expanded(
            child: Container(
              decoration: subSectionContainerDecoration,
              padding: const EdgeInsets.symmetric(horizontal: 32),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(
                    flex: 4,
                    child: FittedBox(
                      alignment: AlignmentDirectional.centerStart,
                      fit: BoxFit.scaleDown,
                      child: Row(
                        spacing: 32,
                        mainAxisSize: MainAxisSize.min,
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          ...AnalyticsPageTab.values.map(
                            (tab) => _buildAnimation(
                              child: AnalyticsPageTabButton(
                                key: ValueKey(selectedTab),
                                tab: tab,
                                isSelected: tab == selectedTab,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  const Spacer(),
                  Visibility(
                    key: ValueKey(selectedTab),
                    visible: selectedTab == AnalyticsPageTab.energyManagement ||
                        selectedTab == AnalyticsPageTab.airQuality,
                    child: Expanded(
                      flex: 2,
                      child: FittedBox(
                        fit: BoxFit.scaleDown,
                        alignment: AlignmentDirectional.centerEnd,
                        child: AnalyticsDateFilterButton(
                          onDateSelected: (value) {
                            _onDateChanged(context, value, selectedTab);
                          },
                          selectedDate: context
                              .watch<AnalyticsDatePickerBloc>()
                              .state
                              .monthlyDate,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          Expanded(
            flex: 8,
            child: _buildAnimation(child: selectedTab.child),
          ),
        ],
      ),
    );
  }

  Widget _buildAnimation({required Widget child}) {
    return AnimatedSwitcher(
      switchInCurve: Curves.easeIn,
      duration: const Duration(milliseconds: 200),
      child: child,
    );
  }

  void _onDateChanged(
    BuildContext context,
    DateTime date,
    AnalyticsPageTab selectedTab,
  ) {
    context.read<AnalyticsDatePickerBloc>().add(
          UpdateAnalyticsDatePickerEvent(montlyDate: date),
        );

    final spaceTreeState = context.read<SpaceTreeBloc>().state;
    final communities = spaceTreeState.selectedCommunities;
    final spaces = spaceTreeState.selectedSpaces;
    if (spaceTreeState.selectedSpaces.isNotEmpty) {
      switch (selectedTab) {
        case AnalyticsPageTab.energyManagement:
          _onEnergyManagementDateChanged(
            context,
            date: date,
            communityUuid: communities.firstOrNull ?? '',
            spaceUuid: spaces.firstOrNull ?? '',
          );
          return;
        case AnalyticsPageTab.airQuality:
          _onAirQualityDateChanged(
            context,
            date: date,
            communityUuid: communities.firstOrNull ?? '',
            spaceUuid: spaces.firstOrNull ?? '',
          );
          return;
        default:
          return;
      }
    }
  }

  void _onEnergyManagementDateChanged(
    BuildContext context, {
    required DateTime date,
    required String communityUuid,
    required String spaceUuid,
  }) {
    context.read<AnalyticsDatePickerBloc>().add(
          UpdateAnalyticsDatePickerEvent(montlyDate: date),
        );

    FetchEnergyManagementDataHelper.loadEnergyManagementData(
      context,
      shouldFetchAnalyticsDevices: false,
      selectedDate: date,
      communityId: communityUuid,
      spaceId: spaceUuid,
    );
  }

  void _onAirQualityDateChanged(
    BuildContext context, {
    required DateTime date,
    required String communityUuid,
    required String spaceUuid,
  }) {
    if (spaceUuid.isEmpty) return;
    FetchAirQualityDataHelper.loadAirQualityData(
      context,
      date: date,
      communityUuid: communityUuid,
      spaceUuid: spaceUuid,
      shouldFetchAnalyticsDevices: false,
    );
  }
}
