import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:syncrow_app/features/devices/bloc/ceiling_bloc/ceiling_sensor_bloc.dart';
import 'package:syncrow_app/features/devices/bloc/ceiling_bloc/ceiling_sensor_event.dart';
import 'package:syncrow_app/features/devices/bloc/ceiling_bloc/ceiling_sensor_state.dart';
import 'package:syncrow_app/features/devices/model/ceiling_sensor_model.dart';
import 'package:syncrow_app/features/devices/model/device_model.dart';
import 'package:syncrow_app/features/devices/view/widgets/ceiling_sensor/ceiling_help_description.dart';
import 'package:syncrow_app/features/devices/view/widgets/ceiling_sensor/double_parameter_control.dart';
import 'package:syncrow_app/features/devices/view/widgets/ceiling_sensor/max_distance_control.dart';
import 'package:syncrow_app/features/devices/view/widgets/ceiling_sensor/presence_record.dart';
import 'package:syncrow_app/features/devices/view/widgets/ceiling_sensor/presence_space_type.dart';
import 'package:syncrow_app/features/devices/view/widgets/device_appbar.dart';
import 'package:syncrow_app/features/devices/view/widgets/wall_sensor/wall_sensor_interface.dart';
import 'package:syncrow_app/features/shared_widgets/default_container.dart';
import 'package:syncrow_app/features/shared_widgets/text_widgets/body_large.dart';
import 'package:syncrow_app/features/shared_widgets/text_widgets/body_medium.dart';
import 'package:syncrow_app/features/shared_widgets/text_widgets/body_small.dart';
import 'package:syncrow_app/generated/assets.dart';
import 'package:syncrow_app/utils/context_extension.dart';
import 'package:syncrow_app/utils/helpers/misc_string_helpers.dart';
import 'package:syncrow_app/utils/resource_manager/color_manager.dart';
import 'package:syncrow_app/utils/resource_manager/constants.dart';
import 'package:syncrow_app/utils/resource_manager/font_manager.dart';

class CeilingSensorInterface extends StatelessWidget {
  const CeilingSensorInterface({super.key, required this.ceilingSensor});

  final DeviceModel ceilingSensor;

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => CeilingSensorBloc(deviceId: ceilingSensor.uuid ?? '')
        ..add(InitialEvent()),
      child: BlocBuilder<CeilingSensorBloc, CeilingSensorState>(
        builder: (context, state) {
          final _bloc = BlocProvider.of<CeilingSensorBloc>(context);

          CeilingSensorModel ceilingSensorModel = _initializeSensorModel(state);

          return AnnotatedRegion(
            value: SystemUiOverlayStyle(
              statusBarColor: ColorsManager.primaryColor.withOpacity(0.5),
              statusBarIconBrightness: Brightness.light,
            ),
            child: Scaffold(
              backgroundColor: ColorsManager.backgroundColor,
              extendBodyBehindAppBar: true,
              extendBody: true,
              appBar: DeviceAppbar(
                deviceName: ceilingSensor.name!,
                deviceUuid: ceilingSensor.uuid!,
              ),
              body: _buildBody(context, state, _bloc, ceilingSensorModel),
            ),
          );
        },
      ),
    );
  }

  CeilingSensorModel _initializeSensorModel(CeilingSensorState state) {
    CeilingSensorModel ceilingSensorModel = CeilingSensorModel(
      spaceType: SpaceTypes.none,
      nobodyTime: '',
      movingMaxDis: 0,
      presenceState: 'none',
      sensitivity: 1,
      checkingResult: '',
      presenceRange: 1,
      sportsPara: 1,
      bodyMovement: 'none',
    );

    if (state is UpdateState) {
      ceilingSensorModel = state.ceilingSensorModel;
    } else if (state is LoadingNewSate) {
      ceilingSensorModel = state.ceilingSensorModel;
    }

    return ceilingSensorModel;
  }

  Widget _buildBody(BuildContext context, CeilingSensorState state,
      CeilingSensorBloc bloc, CeilingSensorModel model) {
    return Container(
      width: MediaQuery.sizeOf(context).width,
      height: MediaQuery.sizeOf(context).height,
      padding: const EdgeInsets.all(Constants.defaultPadding),
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage(Assets.assetsImagesBackground),
          fit: BoxFit.cover,
          opacity: 0.4,
        ),
      ),
      child: state is LoadingInitialState
          ? const Center(child: RefreshProgressIndicator())
          : SafeArea(
              child: RefreshIndicator(
                onRefresh: () async => bloc.add(InitialEvent()),
                child: ListView(
                  shrinkWrap: true,
                  children: [
                    _buildMainContent(context, bloc, model),
                  ],
                ),
              ),
            ),
    );
  }

  Widget _buildMainContent(
      BuildContext context, CeilingSensorBloc bloc, CeilingSensorModel model) {
    return SizedBox(
      height: MediaQuery.of(context).size.height,
      child: Column(
        children: [
          _buildPresenceDisplay(context, model),
          Expanded(flex: 3, child: _buildControlButtons(context, bloc, model)),
        ],
      ),
    );
  }

  Widget _buildPresenceDisplay(BuildContext context, CeilingSensorModel model) {
    return Expanded(
      child: Column(
        children: [
          SvgPicture.asset(
            model.presenceState.toLowerCase() == 'motion'
                ? Assets.assetsIconsPresenceSensorAssetsPresenceSensorMotion
                : Assets.assetsIconsPresenceSensorAssetsPresence,
            width: 100,
            height: 100,
          ),
          const SizedBox(height: 10),
          BodyMedium(
            text: StringHelpers.toTitleCase(model.presenceState),
            style: context.bodyMedium.copyWith(fontWeight: FontsManager.bold),
          ),
        ],
      ),
    );
  }

  Widget _buildControlButtons(
      BuildContext context, CeilingSensorBloc bloc, CeilingSensorModel model) {
    return Column(
      children: [
        DefaultContainer(
          padding: const EdgeInsets.symmetric(vertical: 20),
          child: _buildSensorAttributes(context, model),
        ),
        const SizedBox(height: 15),
        ..._buildActionButtons(context, bloc, model),
      ],
    );
  }

  Widget _buildSensorAttributes(
      BuildContext context, CeilingSensorModel model) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        _buildAttribute(context, 'Sports Para', model.sportsPara.toString()),
        _divider(),
        _buildAttribute(context, 'Detection Range', '${model.presenceRange}M'),
        _divider(),
        _buildAttribute(context, 'Movement', model.bodyMovement),
      ],
    );
  }

  Widget _buildAttribute(BuildContext context, String label, String value) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        BodySmall(
          text: label,
        ),
        BodyLarge(
          text: value,
          style: context.bodyLarge.copyWith(
            fontWeight: FontsManager.bold,
          ),
        ),
      ],
    );
  }

  Widget _divider() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 10),
      child: Container(width: 1, height: 45, color: ColorsManager.greyColor),
    );
  }

  List<Widget> _buildActionButtons(
      BuildContext context, CeilingSensorBloc bloc, CeilingSensorModel model) {
    return ceilingSensorButtons().map((button) {
      return DefaultContainer(
        margin: const EdgeInsets.only(bottom: 5),
        padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 20),
        onTap: () => _handleButtonTap(context, bloc, button, model),
        child: _buildButtonContent(context, button, model),
      );
    }).toList();
  }

  Widget _buildButtonContent(BuildContext context, Map<String, dynamic> button,
      CeilingSensorModel model) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Row(
          children: [
            SvgPicture.asset(button['icon'] as String),
            const SizedBox(width: 25),
            BodyMedium(
              text: button['title'] as String,
              style: context.bodyMedium.copyWith(fontWeight: FontsManager.bold),
            ),
          ],
        ),
        if (button['withArrow'] == true)
          Row(
            children: [
              if (button['title'] == 'Sensitivity') ...[
                Text(
                  model.sensitivity.toString(),
                  style: const TextStyle(color: Colors.black),
                ),
              ] else if (button['title'] == 'Maximum Distance') ...[
                Text(
                  model.movingMaxDis.toString(),
                  style: const TextStyle(color: Colors.black),
                ),
                const Text(
                  "m",
                  style: TextStyle(color: ColorsManager.greyColor),
                ),
              ] else if (button['title'] == 'Nobody Time') ...[
                Text(
                  model.nobodyTime.toString(),
                  style: const TextStyle(color: Colors.black),
                ),
              ] else if (button['title'] == 'Space Type') ...[
                Text(
                  model.spaceType.name.toString() == "none"
                      ? "Office"
                      : model.spaceType.name.toString(),
                  style: const TextStyle(color: Colors.black),
                ),
              ] else ...[
                Text(
                  button['val'].toString(),
                  style: const TextStyle(color: Colors.black),
                ),
              ],
              const Icon(
                Icons.arrow_forward_ios,
                color: ColorsManager.greyColor,
                size: 15,
              ),
            ],
          ),
      ],
    );
  }

  Future<void> _handleButtonTap(BuildContext context, CeilingSensorBloc bloc,
      Map<String, dynamic> button, CeilingSensorModel model) async {
    final title = button['title'];
    if (title == 'Space Type') {
      final result = await _showDialog(
        context,
        PresenceSpaceTypeDialog(
          description: 'Space Type',
          onSpaceTypeSelected: (spaceType) {
            bloc.add(ChangeValueEvent(
                type: title.toString(), value: spaceType.name, code: 'scene'));
          },
          selectedSpaceType: model.spaceType,
        ),
      );
    } else if (title == 'Nobody Time') {
      final result = await _showDialog(
        context,
        MaxDistanceControl(
          title: title.toString(),
          sensor: ceilingSensor,
          value: model.nobodyTime,
          min: 0.0,
          max: 5.0,
          measurement: '',
        ),
      );
      if (result != null) {
        bloc.add(ChangeValueEvent(
            type: title.toString(),
            value: result
                .toString()
                .toLowerCase()
                .replaceAll('sec', 's')
                .replaceAll('1hr', '1hour'),
            code: 'nobody_time'));
      }
    } else if (title == 'Maximum Distance') {
      final result = await _showDialog(
        context,
        DoubleParameterControl(
          title: title.toString(),
          sensor: ceilingSensor,
          value: model.movingMaxDis,
          min: 0,
          max: 500,
          measurement: 'm',
        ),
      );
      if (result != null) {
        bloc.add(ChangeValueEvent(
            type: title.toString(), value: result, code: 'moving_max_dis'));
      }
    } else if (title == 'Sensitivity') {
      final result = await _showDialog(
          context,
          ParameterControlDialog(
            title: title.toString(),
            sensor: ceilingSensor,
            value: model.sensitivity,
            min: 1,
            max: 10,
          ));
      if (result != null) {
        bloc.add(ChangeValueEvent(
            type: title.toString(), value: result, code: 'sensitivity'));
      }
    } else if (title == 'Help Description') {
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => const CeilingHelpDescription()),
      );
    } else if (title == 'Presence Record') {
      Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => PresenceRecord(uuid: ceilingSensor.uuid!)),
      );
    }
  }

  Future<dynamic> _showDialog(BuildContext context, Widget dialog) {
    return showDialog(context: context, builder: (context) => dialog);
  }

  List<Map<String, dynamic>> ceilingSensorButtons({
    sensitivityVal = 0,
    spaceType = 'Office',
    maximumDistanceVal = '3.9m',
    nobodyTimeVal = '1hr',
  }) {
    return [
      {
        'title': 'Space Type',
        'icon': Assets.spaceTypeIcon,
        'page': null,
        'withArrow': true,
        'val': spaceType,
      },
      {
        'title': 'Sensitivity',
        'icon': Assets.sensitivityIcon,
        'page': null,
        'withArrow': true,
        'val': sensitivityVal,
      },
      {
        'title': 'Maximum Distance',
        'icon': Assets.maximumDistanceIcon,
        'page': null,
        'withArrow': true,
        'val': maximumDistanceVal,
      },
      {
        'title': 'Nobody Time',
        'icon': Assets.assetsIconsPresenceSensorAssetsEmpty,
        'page': null,
        'withArrow': true,
        'val': nobodyTimeVal,
      },
      {
        'title': 'Presence Record',
        'icon': Assets.assetsIconsPresenceSensorAssetsInductionRecording,
        'page': null,
        'withArrow': false,
      },
      {
        'title': 'Help Description',
        'icon': Assets.assetsIconsPresenceSensorAssetsHelpDescription,
        'page': null,
        'withArrow': false,
      },
    ];
  }
}
