import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/analytics/models/power_clamp_energy_status.dart';
import 'package:syncrow_web/pages/analytics/modules/analytics/blocs/analytics_devices/analytics_devices_bloc.dart';
import 'package:syncrow_web/pages/analytics/modules/energy_management/blocs/realtime_device_changes/realtime_device_changes_bloc.dart';
import 'package:syncrow_web/pages/analytics/modules/energy_management/helpers/fetch_energy_management_data_helper.dart';
import 'package:syncrow_web/pages/analytics/modules/energy_management/widgets/analytics_device_dropdown.dart';
import 'package:syncrow_web/pages/analytics/modules/energy_management/widgets/power_clamp_energy_status_widget.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/device_status.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';
import 'package:syncrow_web/utils/style.dart';

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

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<RealtimeDeviceChangesBloc, RealtimeDeviceChangesState>(
      builder: (context, state) {
        return Container(
          decoration: subSectionContainerDecoration.copyWith(
            borderRadius: BorderRadius.circular(30),
          ),
          padding: const EdgeInsetsDirectional.all(32),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildHeader(context),
              Text(
                'Device ID:',
                style: context.textTheme.bodySmall?.copyWith(
                  color: ColorsManager.textPrimaryColor,
                  fontWeight: FontWeight.w400,
                  fontSize: 12,
                ),
              ),
              const SizedBox(height: 6),
              SelectableText(
                context.watch<AnalyticsDevicesBloc>().state.selectedDevice?.uuid ??
                    'N/A',
                style: context.textTheme.bodySmall?.copyWith(
                  color: ColorsManager.blackColor,
                  fontWeight: FontWeight.w400,
                  fontSize: 12,
                ),
              ),
              const SizedBox(height: 10),
              const Divider(height: 1, color: ColorsManager.greyColor),
              const SizedBox(height: 50),
              SizedBox(
                height: MediaQuery.sizeOf(context).height * 0.2,
                child: PowerClampEnergyStatusWidget(
                  status: [
                    PowerClampEnergyStatus(
                      iconPath: Assets.presenceState,
                      title: 'Presence Status',
                      value: _valueFromCode(
                        'presence_state',
                        state.deviceStatusList,
                      ),
                      unit: '',
                    ),
                    PowerClampEnergyStatus(
                      iconPath: Assets.presenceTimeIcon,
                      title: 'Presence Time',
                      value:
                          '${_valueFromCode('none_body_time', state.deviceStatusList)} Min',
                      unit: '',
                    ),
                    PowerClampEnergyStatus(
                      iconPath: Assets.currentDistanceIcon,
                      title: 'Detection Distance',
                      value:
                          '${_valueFromCode('space_move_val', state.deviceStatusList)} M',
                      unit: '',
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 20),
            ],
          ),
        );
      },
    );
  }

  String _valueFromCode(
    String code,
    List<Status> status, {
    String? defaultValue,
  }) {
    final value = status
        .firstWhere(
          (e) => e.code == code,
          orElse: () => Status(code: '--', value: '--'),
        )
        .value
        .toString();
    return value == 'null' ? defaultValue ?? '--' : value;
  }

  Widget _buildHeader(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Expanded(
          flex: 3,
          child: FittedBox(
            fit: BoxFit.scaleDown,
            alignment: AlignmentDirectional.centerStart,
            child: SelectableText(
              'Presnce Sensor',
              style: context.textTheme.headlineSmall?.copyWith(
                fontWeight: FontWeight.w700,
                color: ColorsManager.vividBlue.withValues(alpha: 0.6),
                fontSize: 18,
              ),
            ),
          ),
        ),
        const Spacer(),
        Expanded(
          flex: 2,
          child: FittedBox(
            fit: BoxFit.scaleDown,
            alignment: AlignmentDirectional.centerEnd,
            child: AnalyticsDeviceDropdown(
              onChanged: (value) =>
                  FetchEnergyManagementDataHelper.loadRealtimeDeviceChanges(
                context,
                deviceUuid: value.uuid,
              ),
            ),
          ),
        ),
      ],
    );
  }
}
