part of "wall_sensor_interface.dart";

class ParametersList extends StatelessWidget {
  const ParametersList({
    super.key,
    required this.wallSensor,
    required this.presenceSensorsModel,
  });

  final DeviceModel wallSensor;
  final WallSensorModel presenceSensorsModel;
  @override
  Widget build(BuildContext context) {
    return Expanded(
      flex: 2,
      child: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          mainAxisSize: MainAxisSize.min,
          children: List.generate(
            wallSensorButtons.length,
            (index) {
              if (index == 3) {
                return Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    DefaultContainer(
                      padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 15),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          InkWell(
                            onTap: () async {
                              if ((wallSensor.isOnline ?? false) == false) {
                                return;
                              }
                              String controlCode = 'motion_sensitivity_value';
                              final result = await showDialog(
                                context: context,
                                builder: (context) => ParameterControlDialog(
                                  title: 'Motion Detection Sensitivity',
                                  sensor: wallSensor,
                                  value: presenceSensorsModel.motionSensitivity,
                                  min: wallSensor.functions
                                          .firstWhere((element) => element.code == controlCode)
                                          .values
                                          ?.min ??
                                      0,
                                  max: wallSensor.functions
                                          .firstWhere((element) => element.code == controlCode)
                                          .values
                                          ?.max ??
                                      0,
                                ),
                              );
                              if (result != null) {
                                BlocProvider.of<WallSensorBloc>(context)
                                    .add(ChangeValueEvent(value: result, code: controlCode));
                              }
                            },
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                const BodySmall(
                                    text: 'Motion\nDetection\nSensitivity',
                                    textAlign: TextAlign.center),
                                BodyLarge(
                                  text: presenceSensorsModel.motionSensitivity.toString(),
                                  style: context.bodyLarge.copyWith(fontWeight: FontsManager.bold),
                                ),
                              ],
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 10),
                            child: Container(
                              width: 1,
                              height: 45,
                              color: ColorsManager.greyColor,
                            ),
                          ),
                          InkWell(
                            onTap: () async {
                              if ((wallSensor.isOnline ?? false) == false) {
                                return;
                              }
                              String controlCode = 'motionless_sensitivity';
                              final result = await showDialog(
                                context: context,
                                builder: (context) => ParameterControlDialog(
                                  title: 'Motionless Detection Sensitivity',
                                  sensor: wallSensor,
                                  value: presenceSensorsModel.motionlessSensitivity,
                                  min: wallSensor.functions
                                          .firstWhere((element) => element.code == controlCode)
                                          .values
                                          ?.min ??
                                      0,
                                  max: wallSensor.functions
                                          .firstWhere((element) => element.code == controlCode)
                                          .values
                                          ?.max ??
                                      0,
                                ),
                              );

                              if (result != null) {
                                BlocProvider.of<WallSensorBloc>(context)
                                    .add(ChangeValueEvent(value: result, code: controlCode));
                              }
                            },
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                const BodySmall(
                                    text: 'Motionless\nDetection\nSensitivity',
                                    textAlign: TextAlign.center),
                                BodyLarge(
                                  text: presenceSensorsModel.motionlessSensitivity.toString(),
                                  style: context.bodyLarge.copyWith(
                                    fontWeight: FontsManager.bold,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 10),
                            child: Container(
                              width: 1,
                              height: 45,
                              color: ColorsManager.greyColor,
                            ),
                          ),
                          InkWell(
                            onTap: () async {
                              if ((wallSensor.isOnline ?? false) == false) {
                                return;
                              }

                              String controlCode = 'far_detection';
                              final result = await showDialog(
                                context: context,
                                builder: (context) => ParameterControlDialog(
                                  title: 'Far Detection',
                                  sensor: wallSensor,
                                  value: presenceSensorsModel.farDetection,
                                  min: wallSensor.functions
                                          .firstWhere((element) => element.code == controlCode)
                                          .values
                                          ?.min ??
                                      0,
                                  max: wallSensor.functions
                                          .firstWhere((element) => element.code == controlCode)
                                          .values
                                          ?.max ??
                                      0,
                                ),
                              );
                              if (result != null) {
                                BlocProvider.of<WallSensorBloc>(context)
                                    .add(ChangeValueEvent(value: result, code: controlCode));
                              }
                            },
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                const BodySmall(
                                    text: 'Far\nDetection', textAlign: TextAlign.center),
                                BodyLarge(
                                  text:
                                      '${presenceSensorsModel.farDetection.toString()}${wallSensor.functions.firstWhere((element) => element.code == 'far_detection').values?.unit ?? ''}',
                                  style: context.bodyLarge.copyWith(
                                    fontWeight: FontsManager.bold,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                    listItem(wallSensorButtons[index], context, wallSensor, presenceSensorsModel)
                  ],
                );
              }
              return listItem(wallSensorButtons[index], context, wallSensor, presenceSensorsModel);
            },
          ),
        ),
      ),
    );
  }

//{"result":{"productId":"awarhusb","productType":"WPS","status":[{"code":"presence_state","value":"none"},{"code":"far_detection","value":75},{"code":"presence_time","value":0},{"code":"motion_sensitivity_value","value":5},{"code":"motionless_sensitivity","value":5},{"code":"dis_current","value":214},{"code":"illuminance_value","value":231},{"code":"indicator","value":true}]},"success":true}
  final List<Map<String, Object?>> wallSensorButtons = const [
    {
      'icon': Assets.assetsIconsPresenceSensorAssetsTime,
      'title': 'Presence Time',
      'code': 'presence_time',
    },
    {
      'icon': Assets.assetsIconsPresenceSensorAssetsDistance,
      'title': 'Current Distance',
      'code': 'dis_current',
    },
    {
      'icon': Assets.assetsIconsPresenceSensorAssetsIlluminanceValue,
      'title': 'Illuminance Value',
      'code': 'illuminance_value',
    },
    {
      'icon': Assets.assetsIconsPresenceSensorAssetsEmpty,
      'title': 'Nobody Time',
      'code': 'no_one_time',
    },
    {
      'icon': Assets.assetsIconsPresenceSensorAssetsIndicator,
      'title': 'Indicator',
      'code': 'indicator',
    },
    {
      'icon': Assets.assetsIconsPresenceSensorAssetsRecord,
      'title': 'Presence Record',
      'code': null
    },
    {
      'icon': Assets.assetsIconsPresenceSensorAssetsIlluminanceRecord,
      'title': 'Illuminance Record',
      'code': 'illuminance_value'
    },
  ];
}

Widget listItem(Map<String, Object?> wallSensorButton, BuildContext context, DeviceModel wallSensor,
    WallSensorModel wallSensorStatus) {
  String? unit;
  dynamic value;
  int noBodyTimeValue;
  if (wallSensorButton['code'] != null) {
    // if (wallSensor.status.any((element) => element.code == wallSensorButton['code'] as String)) {
    //   unit = unitsMap[wallSensorButton['code'] as String];
    //   value = wallSensor.status
    //       .firstWhere((element) => element.code == wallSensorButton['code'] as String)
    //       .value;
    // }
    if (wallSensorButton['code'] == 'presence_time') {
      unit = unitsMap[wallSensorButton['code'] as String];
      value = wallSensorStatus.presenceTime;
    } else if (wallSensorButton['code'] == 'dis_current') {
      unit = unitsMap[wallSensorButton['code'] as String];
      value = wallSensorStatus.currentDistance;
    } else if (wallSensorButton['code'] == 'illuminance_value') {
      unit = unitsMap[wallSensorButton['code'] as String];
      value = wallSensorStatus.illuminance;
    } else if (wallSensorButton['code'] == 'no_one_time') {
      unit = unitsMap[wallSensorButton['code'] as String];
      value = wallSensorStatus.noOneTime;
    }
  }
  return DefaultContainer(
    margin: const EdgeInsets.only(bottom: 5),
    padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 20),
    onTap: () async {
      if (wallSensorButton['page'] != null) {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => wallSensorButton['page'] as Widget,
          ),
        );
      }
      if (wallSensorButton['title'] == 'Presence Record') {
        Navigator.of(context).push(
          MaterialPageRoute(
              builder: (context) => PresenceRecords(
                    deviceId: wallSensor.uuid!,
                    code: 'presence_state',
                    title: 'Presence Record',
                  )),
        );
      }

      if (wallSensorButton['title'] == 'Illuminance Record') {
        Navigator.of(context).push(
          MaterialPageRoute(
              builder: (context) => PresenceRecords(
                    deviceId: wallSensor.uuid!,
                    code: 'illuminance_value',
                    title: 'Illuminance Record',
                  )),
        );
      }

      if (wallSensorButton['title'] == 'Nobody Time') {
        int noBodyTimeValue = value as int;
        String controlCode = 'no_one_time';
        final result = await showDialog(
          context: context,
          builder: (context) => ParameterControlDialog(
              title: 'Nobody Time', sensor: wallSensor, value: noBodyTimeValue, min: 0, max: 10000),
        );

        if (result != null) {
          BlocProvider.of<WallSensorBloc>(context)
              .add(ChangeValueEvent(value: result, code: controlCode));
        }
      }
    },
    child: Row(
      children: [
        SvgPicture.asset(
          wallSensorButton['icon'] as String,
        ),
        const SizedBox(
          width: 25,
        ),
        BodyMedium(
          text: wallSensorButton['title'] as String,
        ),
        if (wallSensorButton['code'] != null) const Spacer(),
        if (wallSensorButton['code'] != null)
          if (wallSensorButton['title'] != 'Indicator')
            BodyMedium(
              text: '${value ?? 'N/A'}${unit ?? ''}',
              style: context.bodyMedium.copyWith(color: ColorsManager.greyColor),
            ),
        if (wallSensorButton['title'] == 'Indicator')
          Expanded(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Transform.scale(
                    scale: .8,
                    child: CupertinoSwitch(
                      value: wallSensorStatus.indicator,
                      onChanged: (value) {
                        if (wallSensor.isOnline ?? false) {
                          BlocProvider.of<WallSensorBloc>(context)
                              .add(ChangeIndicatorEvent(value: wallSensorStatus.indicator));
                        } else {
                          ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(
                              content: Text('Device is offline'),
                              backgroundColor: Colors.red,
                            ),
                          );
                        }
                      },
                      applyTheme: true,
                    )),
              ],
            ),
          ),
        if (wallSensorButton['title'] == 'Nobody Time')
          const Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              Icon(
                Icons.arrow_forward_ios,
                color: ColorsManager.greyColor,
                size: 15,
              ),
            ],
          ),
      ],
    ),
  );
}

Map<String, String> unitsMap = {
  'presence_time': 's',
  'dis_current': 'cm',
  'illuminance_value': 'lux',
  'far_detection': 'cm',
  'motion_sensitivity_value': '',
  'motionless_sensitivity': '',
};
