import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/analytics/modules/air_quality/blocs/air_quality_distribution/air_quality_distribution_bloc.dart';
import 'package:syncrow_web/pages/analytics/modules/air_quality/widgets/aqi_type_dropdown.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/energy_management/widgets/chart_title.dart';
import 'package:syncrow_web/pages/analytics/params/get_air_quality_distribution_param.dart';
import 'package:syncrow_web/pages/analytics/widgets/charts_loading_widget.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart';

class AqiDistributionChartTitle extends StatelessWidget {
  const AqiDistributionChartTitle({required this.isLoading, super.key});

  final bool isLoading;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        ChartsLoadingWidget(isLoading: isLoading),
        const Expanded(
          flex: 4,
          child: FittedBox(
            fit: BoxFit.scaleDown,
            alignment: AlignmentDirectional.centerStart,
            child: ChartTitle(
              title: Text('Distribution over Air Quality Index'),
            ),
          ),
        ),
        Expanded(
          flex: 2,
          child: FittedBox(
            alignment: AlignmentDirectional.centerEnd,
            fit: BoxFit.scaleDown,
            child: AqiTypeDropdown(
              selectedAqiType: context.watch<AirQualityDistributionBloc>().state.selectedAqiType,
              onChanged: (value) {
                if (value != null) {
                  final bloc = context.read<AirQualityDistributionBloc>();
                  try {
                    final param = _makeLoadAqiDistributionParam(context, value);
                    bloc.add(LoadAirQualityDistribution(param));
                  } catch (_) {
                    return;
                  } finally {
                    bloc.add(UpdateAqiTypeEvent(value));
                  }
                }
              },
            ),
          ),
        ),
      ],
    );
  }

  GetAirQualityDistributionParam _makeLoadAqiDistributionParam(
    BuildContext context,
    AqiType aqiType,
  ) {
    final date = context.read<AnalyticsDatePickerBloc>().state.monthlyDate;
    final spaceUuid =
        context.read<SpaceTreeBloc>().state.selectedSpaces.firstOrNull ?? '';
    if (spaceUuid.isEmpty) throw Exception('Space UUID is empty');
    return GetAirQualityDistributionParam(
      date: date,
      spaceUuid: spaceUuid,
      aqiType: aqiType,
    );
  }
}
