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/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/device_functions.dart';
import 'package:syncrow_web/pages/routines/models/gateway.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/gateway/gateway_dialog_value_selector.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/gateway/gateway_functions_list.dart';

class GatewayDialog extends StatefulWidget {
  const GatewayDialog({
    required this.uniqueCustomId,
    required this.functions,
    required this.deviceSelectedFunctions,
    required this.device,
    required this.dialogType,
    super.key,
  });
  final String dialogType;
  final String? uniqueCustomId;
  final List<DeviceFunction> functions;
  final List<DeviceFunctionData> deviceSelectedFunctions;
  final AllDevicesModel? device;

  @override
  State<GatewayDialog> createState() => _GatewayDialogState();
}

class _GatewayDialogState extends State<GatewayDialog> {
  late final List<GatewayFunctions> _gatewayFunctions;

  @override
  void initState() {
    super.initState();
    _gatewayFunctions = widget.functions.whereType<GatewayFunctions>().toList();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      contentPadding: EdgeInsets.zero,
      content: BlocBuilder<FunctionBloc, FunctionBlocState>(
        builder: (context, state) {
          final selectedFunction = state.selectedFunction;
          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(widget.dialogType == 'THEN'
                    ? 'Gateway Functions'
                    : 'Gateway Conditions'),
                Expanded(child: _buildMainContent(context, state)),
                _buildDialogFooter(context, state),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildMainContent(BuildContext context, FunctionBlocState 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,
      ),
    );
    final selectedGatewayFunctions = _gatewayFunctions.firstWhere(
      (f) => f.code == selectedFunction,
      orElse: () => GatewaySwitchAlarmSound(
        deviceId: '',
        deviceName: '',
        type: '',
      ),
    );
    final operations = selectedGatewayFunctions.getOperationalValues();

    return Row(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        GatewayFunctionsList(gatewayFunctions: _gatewayFunctions),
        if (state.selectedFunction != null)
          Expanded(
            child: GatewayDialogValueSelector(
              operations: operations,
              selectedFunction: selectedFunction ?? '',
              selectedFunctionData: selectedFunctionData,
              gatewayFunctions: _gatewayFunctions,
              operationName: selectedOperationName ?? '',
              device: widget.device,
            ),
          ),
      ],
    );
  }

  Widget _buildDialogFooter(BuildContext context, FunctionBlocState state) {
    return DialogFooter(
      onCancel: () => Navigator.pop(context),
      onConfirm: state.addedFunctions.isNotEmpty
          ? () {
              final selectedFunctionData = state.addedFunctions.firstWhere(
                (f) => f.functionCode == state.selectedFunction,
                orElse: () => DeviceFunctionData(
                  entityId: '',
                  functionCode: state.selectedFunction ?? '',
                  operationName: '',
                  value: null,
                ),
              );
              context.read<RoutineBloc>().add(
                    AddFunctionToRoutine(
                      [selectedFunctionData],
                      widget.uniqueCustomId ?? '-1',
                    ),
                  );
              Navigator.pop(
                context,
                {'deviceId': widget.functions.firstOrNull?.deviceId},
              );
            }
          : null,
      isConfirmEnabled: state.selectedFunction != null,
    );
  }
}
