import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/svg.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/devices_model.dart';
import 'package:syncrow_web/pages/routines/bloc/functions_bloc/functions_bloc_bloc.dart';
import 'package:syncrow_web/pages/routines/bloc/routine_bloc/routine_bloc.dart';
import 'package:syncrow_web/pages/routines/models/curtain/curtain_function.dart';
import 'package:syncrow_web/pages/routines/models/curtain/curtain_opertion_value.dart';
import 'package:syncrow_web/pages/routines/models/device_functions.dart';
import 'package:syncrow_web/pages/routines/widgets/dialog_footer.dart';
import 'package:syncrow_web/pages/routines/widgets/dialog_header.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/helpers/routine_tap_function_helper.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';

class CurtainHelper {
  static Future<Map<String, dynamic>?> showControlDialog({
    required String dialogType,
    required BuildContext context,
    required List<DeviceFunction> functions,
    required String uniqueCustomId,
    required AllDevicesModel? device,
  }) async {
    List<ControlCurtainFunction> curtainFunctions =
        functions.whereType<ControlCurtainFunction>().where((function) {
      if (dialogType == 'THEN') {
        return function.type == 'THEN' || function.type == 'BOTH';
      }
      return function.type == 'IF' || function.type == 'BOTH';
    }).toList();
    return showDialog<Map<String, dynamic>?>(
      context: context,
      builder: (context) => BlocProvider(
        create: (_) => FunctionBloc()..add(const InitializeFunctions([])),
        child: AlertDialog(
          contentPadding: EdgeInsets.zero,
          content: BlocBuilder<FunctionBloc, FunctionBlocState>(
            builder: (context, state) {
              final selectedFunction = state.selectedFunction;
              final selectedOperationName = state.selectedOperationName;
              final selectedFunctionData = state.addedFunctions
                  .firstWhere((f) => f.functionCode == selectedFunction,
                      orElse: () => DeviceFunctionData(
                            entityId: '',
                            functionCode: selectedFunction ?? '',
                            operationName: '',
                            value: null,
                          ));

              return Container(
                width: selectedFunction != null ? 600 : 360,
                height: 450,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(20),
                ),
                padding: const EdgeInsets.only(top: 20),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    DialogHeader(dialogType == 'THEN'
                        ? 'Curtain Functions'
                        : 'Curtain Conditions'),
                    Expanded(
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          // Function list
                          SizedBox(
                            width: selectedFunction != null ? 320 : 360,
                            child: _buildFunctionsList(
                                context: context,
                                curtainFunctions: curtainFunctions,
                                onFunctionSelected:
                                    (functionCode, operationName) {
                                  RoutineTapFunctionHelper.onTapFunction(
                                      context,
                                      functionCode: functionCode,
                                      functionOperationName: operationName,
                                      functionValueDescription:
                                          selectedFunctionData.valueDescription,
                                      deviceUuid: device?.uuid,
                                      codesToAddIntoFunctionsWithDefaultValue: [
                                        'temp_set',
                                        'temp_current',
                                      ],
                                      defaultValue: 0);
                                }),
                          ),
                          // Value selector
                          if (selectedFunction != null)
                            Expanded(
                              child: _buildValueSelector(
                                context: context,
                                selectedFunction: selectedFunction,
                                selectedFunctionData: selectedFunctionData,
                                controlFunctions: curtainFunctions,
                                device: device,
                                operationName: selectedOperationName ?? '',
                              ),
                            ),
                        ],
                      ),
                    ),
                    DialogFooter(
                      onCancel: () {
                        Navigator.pop(context);
                      },
                      onConfirm: state.addedFunctions.isNotEmpty
                          ? () {
                              /// add the functions to the routine bloc
                              context.read<RoutineBloc>().add(
                                    AddFunctionToRoutine(
                                      state.addedFunctions,
                                      uniqueCustomId,
                                    ),
                                  );

                              // Return the device data to be added to the container
                              Navigator.pop(context, {
                                'deviceId': functions.first.deviceId,
                              });
                            }
                          : null,
                      isConfirmEnabled: selectedFunction != null,
                    ),
                  ],
                ),
              );
            },
          ),
        ),
      ),
    ).then((value) {
      return value;
    });
  }

  static Widget _buildFunctionsList({
    required BuildContext context,
    required List<ControlCurtainFunction> curtainFunctions,
    required Function(String, String) onFunctionSelected,
  }) {
    return ListView.separated(
      shrinkWrap: false,
      physics: const AlwaysScrollableScrollPhysics(),
      itemCount: curtainFunctions.length,
      separatorBuilder: (context, index) => const Padding(
        padding: EdgeInsets.symmetric(horizontal: 40.0),
        child: Divider(
          color: ColorsManager.dividerColor,
        ),
      ),
      itemBuilder: (context, index) {
        final function = curtainFunctions[index];
        return ListTile(
          leading: SvgPicture.asset(
            function.icon,
            width: 24,
            height: 24,
            placeholderBuilder: (BuildContext context) => Container(
              width: 24,
              height: 24,
              color: Colors.transparent,
            ),
          ),
          title: Text(
            function.operationName,
            style: context.textTheme.bodyMedium,
          ),
          trailing: const Icon(
            Icons.arrow_forward_ios,
            size: 16,
            color: ColorsManager.textGray,
          ),
          onTap: () => onFunctionSelected(
            function.code,
            function.operationName,
          ),
        );
      },
    );
  }

  static Widget _buildValueSelector({
    required BuildContext context,
    required String selectedFunction,
    required DeviceFunctionData? selectedFunctionData,
    required List<ControlCurtainFunction> controlFunctions,
    AllDevicesModel? device,
    required String operationName,
  }) {
    final selectedFn =
        controlFunctions.firstWhere((f) => f.code == selectedFunction);

    // Rest of your existing code for other value selectors
    final values = selectedFn.getOperationalValues();
    return _buildOperationalValuesList(
      context: context,
      values: values,
      selectedValue: selectedFunctionData?.value,
      device: device,
      operationName: operationName,
      selectCode: selectedFunction,
      selectedFunctionData: selectedFunctionData,
    );
  }

  static Widget _buildOperationalValuesList({
    required BuildContext context,
    required List<CurtainOperationalValue> values,
    required dynamic selectedValue,
    AllDevicesModel? device,
    required String operationName,
    required String selectCode,
    DeviceFunctionData? selectedFunctionData,

    // required Function(dynamic) onValueChanged,
  }) {
    return ListView.builder(
      shrinkWrap: false,
      physics: const AlwaysScrollableScrollPhysics(),
      itemCount: values.length,
      itemBuilder: (context, index) {
        final value = values[index];
        final isSelected = selectedValue == value.value;
        return ListTile(
          leading: SvgPicture.asset(
            value.icon,
            width: 24,
            height: 24,
            placeholderBuilder: (BuildContext context) => Container(
              width: 24,
              height: 24,
              color: Colors.transparent,
            ),
          ),
          title: Text(
            value.description,
            style: context.textTheme.bodyMedium,
          ),
          trailing: Icon(
            isSelected
                ? Icons.radio_button_checked
                : Icons.radio_button_unchecked,
            size: 24,
            color: isSelected
                ? ColorsManager.primaryColorWithOpacity
                : ColorsManager.textGray,
          ),
          onTap: () {
            if (!isSelected) {
              context.read<FunctionBloc>().add(
                    AddFunction(
                      functionData: DeviceFunctionData(
                        entityId: device?.uuid ?? '',
                        functionCode: selectCode,
                        operationName: operationName,
                        value: value.value,
                        condition: selectedFunctionData?.condition,
                        valueDescription:
                            selectedFunctionData?.valueDescription,
                      ),
                    ),
                  );
            }
          },
        );
      },
    );
  }
}
