import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_app/features/scene/bloc/smart_scene/smart_scene_select_dart_bloc.dart';
import 'package:syncrow_app/features/scene/model/scene_static_function.dart';
import 'package:syncrow_app/features/scene/model/scenes_model.dart';
import 'package:syncrow_app/features/scene/model/smart_scene_enable.dart';
import 'package:syncrow_app/features/scene/widgets/scene_list_tile.dart';
import 'package:syncrow_app/features/shared_widgets/text_widgets/body_medium.dart';
import 'package:syncrow_app/generated/assets.dart';
import 'package:syncrow_app/utils/context_extension.dart';
import 'package:syncrow_app/utils/resource_manager/color_manager.dart';

class SmartSceneSelectAutomationList extends StatefulWidget {
  const SmartSceneSelectAutomationList({
    super.key,
    required this.automationList,
    required this.automationId,
  });

  final List<ScenesModel> automationList;
  final String automationId;

  @override
  State<SmartSceneSelectAutomationList> createState() =>
      _SmartSceneSelectAutomationListState();
}

class _SmartSceneSelectAutomationListState
    extends State<SmartSceneSelectAutomationList> {
  final List<Color> colorList = _generateDarkColors(100);

  static List<Color> _generateDarkColors(int count) {
    final random = Random();
    final colors = <Color>[];

    while (colors.length < count) {
      final color =
          Color((random.nextDouble() * 0xFFFFFF).toInt()).withOpacity(1.0);
      if (_isDark(color)) {
        colors.add(color);
      }
    }
    return colors;
  }

  static bool _isDark(Color color) {
    final brightness =
        ((color.red * 299) + (color.green * 587) + (color.blue * 114)) / 1000;
    return brightness < 128;
  }

  @override
  Widget build(BuildContext context) {
    //  Filter the automation list to exclude the sceneId
    final filteredAutomationList = widget.automationList
        .where((e) => e.id != widget.automationId.toString())
        .toList();
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            // Expanded(
            //   child: TextButton(
            //       onPressed: () => Navigator.pop(context),
            //       child: BodySmall(
            //         text: 'Save',
            //         style: context.bodySmall
            //             .copyWith(color: ColorsManager.primaryColorWithOpacity),
            //       )),
            // ),
            const Spacer(),
            Expanded(
              flex: 2,
              child: Padding(
                padding: const EdgeInsets.symmetric(vertical: 8.0),
                child: BodyMedium(
                  text: 'Automation',
                  textAlign: TextAlign.center,
                  style: context.bodyMedium.copyWith(
                      color: ColorsManager.primaryColorWithOpacity,
                      fontWeight: FontWeight.bold),
                ),
              ),
            ),
            const Spacer(),
          ],
        ),
        const Divider(
          color: ColorsManager.dividerColor,
        ),
        Expanded(
          child: BlocBuilder<SmartSceneSelectBloc, SmartSceneSelectState>(
            builder: (context, state) {
              final smartSceneEnable = ((state is SmartSceneSelected))
                  ? state.smartSceneEnable
                  : context.read<SmartSceneSelectBloc>().smartSceneEnable;

              return ListView.builder(
                shrinkWrap: true,
                itemCount: filteredAutomationList.length,
                itemBuilder: (context, index) {
                  final automation = filteredAutomationList[index];
                  final isSelected =
                      smartSceneEnable?.entityId == automation.id;
                  final descriptionSelected = isSelected
                      ? (smartSceneEnable?.actionExecutor == 'rule_enable'
                          ? 'Enable'
                          : 'Disable')
                      : automation.status == 'enable'
                          ? 'Enable'
                          : 'Disable';

                  return SceneListTile(
                    padding: const EdgeInsets.symmetric(horizontal: 10),
                    leadingWidget: CircleAvatar(
                      backgroundColor: colorList[index % colorList.length],
                      radius: 15,
                      child: Text(
                        index.toString(),
                        style: context.bodyMedium.copyWith(color: Colors.white),
                      ),
                    ),
                    titleString: automation.name,
                    trailingWidget: TextButton.icon(
                      iconAlignment: IconAlignment.end,
                      onPressed: () {
                        context.customAlertDialog(
                          alertBody: EnableDisableAutomationDialog(
                            automationId: automation.id,
                            descriptionSelected: descriptionSelected,
                            sceneORAutomationName: automation.name,
                            type: automation.type,
                          ),
                          title: automation.name,
                          onConfirm: () {
                            context
                                .read<SmartSceneSelectBloc>()
                                .add(const SmartSceneConfirmSelectionEvent());
                            Navigator.pop(context);
                          },
                          onDismiss: () {
                            context
                                .read<SmartSceneSelectBloc>()
                                .add(const SmartSceneClearEvent());
                            Navigator.pop(context);
                          },
                        );
                      },
                      label: BodyMedium(
                        text: _capitalizeFirst(descriptionSelected),
                        style: context.bodyMedium
                            .copyWith(color: ColorsManager.greyColor),
                      ),
                      icon: const Icon(
                        Icons.arrow_forward_ios_rounded,
                        color: ColorsManager.greyColor,
                        size: 14,
                      ),
                      style: const ButtonStyle(
                        padding: WidgetStatePropertyAll(EdgeInsets.zero),
                      ),
                    ),
                    onPressed: () {
                      context.customAlertDialog(
                        alertBody: EnableDisableAutomationDialog(
                          automationId: automation.id,
                          descriptionSelected: descriptionSelected,
                          sceneORAutomationName: automation.name,
                          type: automation.type,
                        ),
                        title: automation.name,
                        onConfirm: () {
                          context
                              .read<SmartSceneSelectBloc>()
                              .add(const SmartSceneConfirmSelectionEvent());
                          Navigator.pop(context);
                        },
                        onDismiss: () {
                          context
                              .read<SmartSceneSelectBloc>()
                              .add(const SmartSceneClearEvent());
                          Navigator.pop(context);
                        },
                      );
                    },
                  );
                },
              );
            },
          ),
        ),
      ],
    );
  }

  String _capitalizeFirst(String description) {
    if (description.isEmpty) return description;
    return '${description[0].toUpperCase()}${description.substring(1)}';
  }
}

class EnableDisableAutomationDialog extends StatefulWidget {
  const EnableDisableAutomationDialog({
    super.key,
    required this.automationId,
    required this.descriptionSelected,
    required this.sceneORAutomationName,
    required this.type,
  });

  final String automationId;
  final String descriptionSelected;
  final String sceneORAutomationName;
  final String type;

  @override
  State<EnableDisableAutomationDialog> createState() =>
      _EnableDisableAutomationDialogState();
}

class _EnableDisableAutomationDialogState
    extends State<EnableDisableAutomationDialog> {
  String? groupValue;
  final List<SceneOperationalValue> values = [
    SceneOperationalValue(
      icon: Assets.assetsAcPower,
      description: 'Enable',
      value: 'rule_enable',
    ),
    SceneOperationalValue(
      icon: Assets.assetsAcPowerOFF,
      description: 'Disable',
      value: 'rule_disable',
    ),
  ];

  @override
  void initState() {
    super.initState();
    groupValue =
        widget.descriptionSelected == 'Enable' ? 'rule_enable' : 'rule_disable';

    context.read<SmartSceneSelectBloc>().add(SmartSceneEnableEvent(
        SmartSceneEnable(
            entityId: widget.automationId,
            actionExecutor: groupValue!,
            sceneORAutomationName: widget.sceneORAutomationName,
            type: widget.type,
            isAutomation: true)));
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<SmartSceneSelectBloc, SmartSceneSelectState>(
      builder: (context, state) {
        return Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ...values.map(
              (operation) => SceneListTile(
                iconsSize: 25,
                minLeadingWidth: 15,
                padding: const EdgeInsets.symmetric(horizontal: 16),
                assetPath: operation.icon,
                assetHeaderValue: operation.iconValue,
                titleString: operation.description.toString(),
                textAlign: TextAlign.start,
                trailingWidget: Radio(
                  value: operation.value,
                  groupValue: groupValue,
                  onChanged: (value) {
                    setState(() {
                      groupValue = value;
                    });
                    context
                        .read<SmartSceneSelectBloc>()
                        .add(SmartSceneEnableEvent(
                          SmartSceneEnable(
                              entityId: widget.automationId,
                              actionExecutor: value!,
                              sceneORAutomationName:
                                  widget.sceneORAutomationName,
                              type: widget.type,
                              isAutomation: true),
                        ));
                  },
                ),
                onPressed: () {
                  setState(() {
                    groupValue = operation.value;
                  });
                  context
                      .read<SmartSceneSelectBloc>()
                      .add(SmartSceneEnableEvent(
                        SmartSceneEnable(
                          entityId: widget.automationId,
                          actionExecutor: operation.value,
                          sceneORAutomationName: widget.sceneORAutomationName,
                          type: widget.type,
                          isAutomation: true,
                        ),
                      ));
                },
              ),
            ),
          ],
        );
      },
    );
  }
}
