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/flush_mounted_presence_sensor/bloc/flush_mounted_presence_sensor_bloc.dart';
import 'package:syncrow_web/pages/device_managment/flush_mounted_presence_sensor/factories/flush_mounted_presence_sensor_bloc_factory.dart';
import 'package:syncrow_web/pages/device_managment/flush_mounted_presence_sensor/models/flush_mounted_presence_sensor_model.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/shared/table/description_view.dart';
import 'package:syncrow_web/pages/device_managment/shared/table/report_table.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart';

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

  final AllDevicesModel device;

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => FlushMountedPresenceSensorBlocFactory.create(
        deviceId: device.uuid ?? '-1',
      )..add(FlushMountedPresenceSensorFetchStatusEvent()),
      child: BlocBuilder<FlushMountedPresenceSensorBloc,
          FlushMountedPresenceSensorState>(
        builder: (context, state) {
          if (state is FlushMountedPresenceSensorLoadingInitialState ||
              state is FlushMountedPresenceSensorDeviceReportsLoadingState) {
            return const Center(child: CircularProgressIndicator());
          } else if (state is FlushMountedPresenceSensorUpdateState) {
            return _buildGridView(context, state.model);
          } else if (state is FlushMountedPresenceSensorDeviceReportsState) {
            return ReportsTable(
              report: state.deviceReport,
              thirdColumnTitle:
                  state.code == 'illuminance_value' ? "Value" : 'Status',
              thirdColumnDescription:
                  state.code == 'illuminance_value' ? "Lux" : null,
              onRowTap: (index) {},
              onClose: () {
                context
                    .read<FlushMountedPresenceSensorBloc>()
                    .add(FlushMountedPresenceSensorBackToGridViewEvent());
              },
            );
          } else if (state is FlushMountedPresenceSensorShowDescriptionState) {
            return DescriptionView(
              description: state.description,
              onClose: () {
                context
                    .read<FlushMountedPresenceSensorBloc>()
                    .add(FlushMountedPresenceSensorBackToGridViewEvent());
              },
            );
          } else if (state is FlushMountedPresenceSensorDeviceReportsFailedState) {
            final model =
                context.read<FlushMountedPresenceSensorBloc>().deviceStatus;
            return _buildGridView(context, model);
          }
          return const Center(
            child: Text('Error fetching status', textAlign: TextAlign.center),
          );
        },
      ),
    );
  }

  Widget _buildGridView(
    BuildContext context,
    FlushMountedPresenceSensorModel model,
  ) {
    final isExtraLarge = isExtraLargeScreenSize(context);
    final isLarge = isLargeScreenSize(context);
    final isMedium = isMediumScreenSize(context);
    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.illuminance.toString(),
          postfix: 'Lux',
          description: 'Illuminance Value',
        ),
        PresenceUpdateData(
          value: model.sensitivity.toDouble(),
          title: 'Sensitivity:',
          minValue: 0,
          maxValue: 9,
          steps: 1,
          action: (int value) => context.read<FlushMountedPresenceSensorBloc>().add(
                FlushMountedPresenceSensorChangeValueEvent(
                  code: FlushMountedPresenceSensorModel.codeSensitivity,
                  value: value,
                ),
              ),
        ),
        PresenceUpdateData(
          value: (model.nearDetection / 100).clamp(0.0, double.infinity),
          title: 'Nearest Detect Dist:',
          description: 'm',
          minValue: 0.0,
          maxValue: 9.5,
          steps: 0.1,
          valuesPercision: 1,
          action: (double value) =>
              context.read<FlushMountedPresenceSensorBloc>().add(
                    FlushMountedPresenceSensorChangeValueEvent(
                      code: FlushMountedPresenceSensorModel.codeNearDetection,
                      value: (value * 100).toInt(),
                    ),
                  ),
        ),
        PresenceUpdateData(
          value: (model.farDetection / 100).clamp(0.0, double.infinity),
          title: 'Max Detect Dist:',
          description: 'm',
          minValue: 0.0,
          maxValue: 9.5,
          steps: 0.1,
          valuesPercision: 1,
          action: (double value) =>
              context.read<FlushMountedPresenceSensorBloc>().add(
                    FlushMountedPresenceSensorChangeValueEvent(
                      code: FlushMountedPresenceSensorModel.codeFarDetection,
                      value: (value * 100).toInt(),
                    ),
                  ),
        ),
        PresenceUpdateData(
          value: model.sensiReduce.toDouble(),
          title: 'Trigger Level:',
          minValue: 0,
          maxValue: 3,
          steps: 1,
          action: (int value) => context.read<FlushMountedPresenceSensorBloc>().add(
                FlushMountedPresenceSensorChangeValueEvent(
                  code: FlushMountedPresenceSensorModel.codeSensiReduce,
                  value: value,
                ),
              ),
        ),
        PresenceUpdateData(
          value: model.occurDistReduce.toDouble(),
          title: 'Indent Level:',
          minValue: 0,
          maxValue: 3,
          steps: 1,
          action: (int value) => context.read<FlushMountedPresenceSensorBloc>().add(
                FlushMountedPresenceSensorChangeValueEvent(
                  code: FlushMountedPresenceSensorModel.codeOccurDistReduce,
                  value: value,
                ),
              ),
        ),
        PresenceUpdateData(
          value: (model.presenceDelay / 10).toDouble(),
          valuesPercision: 1,
          title: 'Target Confirm Time:',
          description: 's',
          minValue: 0.0,
          maxValue: 0.5,
          steps: 0.1,
          action: (double value) =>
              context.read<FlushMountedPresenceSensorBloc>().add(
                    FlushMountedPresenceSensorChangeValueEvent(
                      code: FlushMountedPresenceSensorModel.codePresenceDelay,
                      value: (value * 10).toInt(),
                    ),
                  ),
        ),
        PresenceUpdateData(
          value: (model.noneDelay / 10).toDouble(),
          description: 's',
          title: 'Disappe Delay:',
          minValue: 20,
          maxValue: 300,
          steps: 1,
          action: (double value) =>
              context.read<FlushMountedPresenceSensorBloc>().add(
                    FlushMountedPresenceSensorChangeValueEvent(
                      code: FlushMountedPresenceSensorModel.codeNoneDelay,
                      value: (value * 10).round(),
                    ),
                  ),
        ),
        GestureDetector(
          onTap: () => context.read<FlushMountedPresenceSensorBloc>().add(
                FlushMountedPresenceSensorGetDeviceReportsEvent(
                  code: 'presence_state',
                  deviceUuid: device.uuid!,
                ),
              ),
          child: const PresenceStaticWidget(
            icon: Assets.presenceRecordIcon,
            description: 'Presence Record',
          ),
        ),
      ],
    );
  }
}
