import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.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/widgets/analytics_date_filter_button.dart';
import 'package:syncrow_web/pages/analytics/modules/energy_management/widgets/chart_title.dart';
import 'package:syncrow_web/pages/analytics/modules/occupancy/blocs/occupancy_heat_map/occupancy_heat_map_bloc.dart';
import 'package:syncrow_web/pages/analytics/modules/occupancy/helpers/fetch_occupancy_data_helper.dart';
import 'package:syncrow_web/pages/analytics/modules/occupancy/widgets/occupancy_heat_map.dart';
import 'package:syncrow_web/pages/analytics/widgets/analytics_chart_empty_state_widget.dart';
import 'package:syncrow_web/pages/analytics/widgets/analytics_error_widget.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/style.dart';

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

  @override
  Widget build(BuildContext context) {
    final spaceTreeState = context.watch<SpaceTreeBloc>().state;
    return BlocBuilder<OccupancyHeatMapBloc, OccupancyHeatMapState>(
      builder: (context, state) {
        return Container(
          padding: const EdgeInsets.all(30),
          decoration: containerWhiteDecoration,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              AnalyticsErrorWidget(state.errorMessage),
              Row(
                children: [
                  const Expanded(
                    flex: 3,
                    child: FittedBox(
                      alignment: AlignmentDirectional.centerStart,
                      fit: BoxFit.scaleDown,
                      child: ChartTitle(title: Text('Occupancy Heat Map')),
                    ),
                  ),
                  const Spacer(),
                  Expanded(
                    child: FittedBox(
                      fit: BoxFit.scaleDown,
                      alignment: AlignmentDirectional.centerEnd,
                      child: AnalyticsDateFilterButton(
                        onDateSelected: (DateTime value) {
                          context.read<AnalyticsDatePickerBloc>().add(
                                UpdateAnalyticsDatePickerEvent(yearlyDate: value),
                              );
                          if (spaceTreeState.selectedSpaces.isNotEmpty) {
                            FetchOccupancyDataHelper.loadHeatMapData(
                              context,
                              spaceUuid:
                                  spaceTreeState.selectedSpaces.firstOrNull ?? '',
                              year: value,
                            );
                          }
                        },
                        datePickerType: DatePickerType.year,
                        selectedDate: context
                            .watch<AnalyticsDatePickerBloc>()
                            .state
                            .yearlyDate,
                      ),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 20),
              const Divider(),
              const SizedBox(height: 20),
              Visibility(
                visible: state.heatMapData.isNotEmpty &&
                    state.heatMapData.every(
                      (e) => e.countTotalPresenceDetected != 0,
                    ),
                replacement: AnalyticsChartEmptyStateWidget(
                  isLoading: state.status == OccupancyHeatMapStatus.loading,
                  isError: state.status == OccupancyHeatMapStatus.failure,
                  isInitial: state.status == OccupancyHeatMapStatus.initial,
                  errorMessage: state.errorMessage,
                  iconPath: Assets.emptyHeatmap,
                ),
                child: Expanded(
                  child: OccupancyHeatMap(
                    selectedDate:
                        context.watch<AnalyticsDatePickerBloc>().state.yearlyDate,
                    heatMapData: state.heatMapData.asMap().map(
                          (_, value) => MapEntry(
                            value.eventDate,
                            value.countTotalPresenceDetected,
                          ),
                        ),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}
