import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/devices_model.dart';
import 'package:syncrow_web/pages/device_managment/shared/table/description_view.dart';
import 'package:syncrow_web/pages/device_managment/shared/table/report_table.dart';
import 'package:syncrow_web/pages/device_managment/wall_sensor/bloc/wall_bloc.dart';
import 'package:syncrow_web/pages/device_managment/wall_sensor/bloc/wall_event.dart';
import 'package:syncrow_web/pages/device_managment/wall_sensor/bloc/wall_state.dart';
import 'package:syncrow_web/pages/device_managment/shared/sensors_widgets/presence_display_data.dart';
import 'package:syncrow_web/pages/device_managment/shared/sensors_widgets/presence_static_widget.dart';
import 'package:syncrow_web/pages/device_managment/shared/sensors_widgets/presence_status.dart';
import 'package:syncrow_web/pages/device_managment/shared/sensors_widgets/presence_update_data.dart';
import 'package:syncrow_web/pages/device_managment/wall_sensor/factories/wall_sensor_bloc_factory.dart';
import 'package:syncrow_web/pages/device_managment/wall_sensor/model/wall_sensor_model.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart';

class WallSensorControlsView extends StatelessWidget with HelperResponsiveLayout {
  const WallSensorControlsView({super.key, required this.device});

  final AllDevicesModel device;

  @override
  Widget build(BuildContext context) {
    final isExtraLarge = isExtraLargeScreenSize(context);
    final isLarge = isLargeScreenSize(context);
    final isMedium = isMediumScreenSize(context);
    return BlocProvider(
      create: (context) =>
          WallSensorBlocFactory.create(deviceId: device.uuid!)..add(WallSensorFetchStatusEvent()),
      child: BlocBuilder<WallSensorBloc, WallSensorState>(
        builder: (context, state) {
          if (state is WallSensorLoadingInitialState || state is DeviceReportsLoadingState) {
            return const Center(child: CircularProgressIndicator());
          } else if (state is WallSensorUpdateState) {
            return _buildGridView(context, state.wallSensorModel, isExtraLarge, isLarge, isMedium);
          } else if (state is DeviceReportsState) {
            return ReportsTable(
              report: state.deviceReport,
              thirdColumnTitle: state.code == 'illuminance_value' ? "Value" : 'Status',
              thirdColumnDescription: state.code == 'illuminance_value' ? "Lux" : null,
              onRowTap: (index) {},
              onClose: () {
                context.read<WallSensorBloc>().add(BackToGridViewEvent());
              },
            );
          } else if (state is WallSensorShowDescriptionState) {
            return DescriptionView(
              description: state.description,
              onClose: () {
                context.read<WallSensorBloc>().add(BackToGridViewEvent());
              },
            );
          } else if (state is DeviceReportsFailedState) {
            final model = context.read<WallSensorBloc>().deviceStatus;
            return _buildGridView(context, model, isExtraLarge, isLarge, isMedium);
          }
          return const Center(child: Text('Error fetching status'));
        },
      ),
    );
  }

  Widget _buildGridView(
      BuildContext context, WallSensorModel model, bool isExtraLarge, bool isLarge, bool isMedium) {
    return GridView(
      padding: const EdgeInsets.symmetric(horizontal: 50),
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: isLarge || isExtraLarge
            ? 3
            : isMedium
                ? 2
                : 1,
        mainAxisExtent: 140,
        crossAxisSpacing: 12,
        mainAxisSpacing: 12,
      ),
      children: [
        PresenceState(
          value: model.presenceState,
        ),
        PresenceDisplayValue(
          value: model.presenceTime.toString(),
          postfix: 'min',
          description: 'Presence Time',
        ),
        PresenceDisplayValue(
          value: model.currentDistance.toString(),
          postfix: 'cm',
          description: 'Current Distance',
        ),
        PresenceDisplayValue(
          value: model.illuminance.toString(),
          postfix: 'Lux',
          description: 'Illuminance Value',
        ),
        PresenceUpdateData(
          value: model.motionSensitivity.toDouble(),
          title: 'Motion Detection Sensitivity:',
          minValue: 1,
          maxValue: 5,
          steps: 1,
          action: (int value) {
            context.read<WallSensorBloc>().add(
                  WallSensorChangeValueEvent(
                    code: 'motion_sensitivity_value',
                    value: value,
                  ),
                );
          },
        ),
        PresenceUpdateData(
          value: model.motionlessSensitivity.toDouble(),
          title: 'Motionless Detection Sensitivity:',
          minValue: 1,
          maxValue: 5,
          steps: 1,
          action: (int value) => context.read<WallSensorBloc>().add(
                WallSensorChangeValueEvent(
                  code: 'motionless_sensitivity',
                  value: value,
                ),
              ),
        ),
        PresenceUpdateData(
            value: model.noBodyTime.toDouble(),
            title: 'Nobody Time:',
            minValue: 10,
            maxValue: 10000,
            steps: 1,
            description: 'sec',
            action: (int value) => context.read<WallSensorBloc>().add(WallSensorChangeValueEvent(
                  code: 'no_one_time',
                  value: value,
                ))),
        PresenceUpdateData(
          value: model.farDetection.toDouble(),
          title: 'Far Detection:',
          minValue: 75,
          maxValue: 600,
          steps: 75,
          description: 'cm',
          action: (int value) => context.read<WallSensorBloc>().add(
                WallSensorChangeValueEvent(
                  code: 'far_detection',
                  value: value,
                ),
              ),
        ),
        GestureDetector(
          onTap: () {
            context
                .read<WallSensorBloc>()
                .add(GetDeviceReportsEvent(code: 'illuminance_value', deviceUuid: device.uuid!));
          },
          child: const PresenceStaticWidget(
            icon: Assets.illuminanceRecordIcon,
            description: 'Illuminance Record',
          ),
        ),
        GestureDetector(
          onTap: () {
            context
                .read<WallSensorBloc>()
                .add(GetDeviceReportsEvent(code: 'presence_state', deviceUuid: device.uuid!));
          },
          child: const PresenceStaticWidget(
            icon: Assets.presenceRecordIcon,
            description: 'Presence Record',
          ),
        ),
      ],
    );
  }
}
