import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_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/device_functions.dart';
import 'package:syncrow_web/pages/routines/models/flush/flush_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/flush_presence_sensor/flush_value_selector_widget.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';

class FlushPresenceSensor extends StatefulWidget {
  final List<DeviceFunction> functions;
  final AllDevicesModel? device;
  final List<DeviceFunctionData>? deviceSelectedFunctions;
  final String? uniqueCustomId;
  final String dialogType;
  final bool removeComparetors;

  const FlushPresenceSensor({
    super.key,
    required this.functions,
    this.device,
    this.deviceSelectedFunctions,
    this.uniqueCustomId,
    required this.dialogType,
    this.removeComparetors = false,
  });

  static Future<Map<String, dynamic>?> showFlushFunctionsDialog({
    required BuildContext context,
    required List<DeviceFunction> functions,
    AllDevicesModel? device,
    List<DeviceFunctionData>? deviceSelectedFunctions,
    String? uniqueCustomId,
    required String dialogType,
    bool removeComparetors = false,
  }) async {
    return showDialog<Map<String, dynamic>?>(
      context: context,
      builder: (context) => FlushPresenceSensor(
        functions: functions,
        device: device,
        deviceSelectedFunctions: deviceSelectedFunctions,
        uniqueCustomId: uniqueCustomId,
        removeComparetors: removeComparetors,
        dialogType: dialogType,
      ),
    );
  }

  @override
  State<FlushPresenceSensor> createState() => _WallPresenceSensorState();
}

class _WallPresenceSensorState extends State<FlushPresenceSensor> {
  late final List<FlushFunctions> _flushFunctions;
  @override
  void initState() {
    super.initState();
    _flushFunctions =
        widget.functions.whereType<FlushFunctions>().where((function) {
      if (widget.dialogType == 'THEN') {
        return function.type == 'THEN' || function.type == 'BOTH';
      }
      return function.type == 'IF' || function.type == 'BOTH';
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (_) => FunctionBloc()
        ..add(InitializeFunctions(widget.deviceSelectedFunctions ?? [])),
      child: _buildDialogContent(),
    );
  }

  Widget _buildDialogContent() {
    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'
                    ? 'Presence Sensor Functions'
                    : 'Presence Sensor Condition'),
                Expanded(child: _buildMainContent(context, state)),
                _buildDialogFooter(context, state),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildMainContent(BuildContext context, FunctionBlocState state) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        _buildFunctionList(context),
        if (state.selectedFunction != null) _buildValueSelector(context, state),
      ],
    );
  }

  Widget _buildFunctionList(BuildContext context) {
    return SizedBox(
      width: 360,
      child: ListView.separated(
        shrinkWrap: false,
        physics: const AlwaysScrollableScrollPhysics(),
        itemCount: _flushFunctions.length,
        separatorBuilder: (context, index) => const Padding(
          padding: EdgeInsets.symmetric(horizontal: 40.0),
          child: Divider(color: ColorsManager.dividerColor),
        ),
        itemBuilder: (context, index) {
          final function = _flushFunctions[index];
          return ListTile(
            leading: SvgPicture.asset(
              function.icon,
              width: 24,
              height: 24,
              placeholderBuilder: (context) => const SizedBox(
                width: 24,
                height: 24,
              ),
            ),
            title: Text(
              function.operationName,
              style: context.textTheme.bodyMedium,
            ),
            trailing: const Icon(
              Icons.arrow_forward_ios,
              size: 16,
              color: ColorsManager.textGray,
            ),
            onTap: () => context.read<FunctionBloc>().add(
                  SelectFunction(
                    functionCode: function.code,
                    operationName: function.operationName,
                  ),
                ),
          );
        },
      ),
    );
  }

  Widget _buildValueSelector(BuildContext context, FunctionBlocState state) {
    final selectedFunction = state.selectedFunction ?? '';
    final functionData = state.addedFunctions.firstWhere(
      (f) => f.functionCode == selectedFunction,
      orElse: () => DeviceFunctionData(
        entityId: '',
        functionCode: selectedFunction,
        operationName: state.selectedOperationName ?? '',
        value: null,
      ),
    );

    return Expanded(
      child: FlushValueSelectorWidget(
        selectedFunction: selectedFunction,
        functionData: functionData,
        flushFunctions: _flushFunctions,
        device: widget.device,
        dialogType: widget.dialogType,
        removeComparators: widget.removeComparetors,
      ),
    );
  }

  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!,
                    ),
                  );
              Navigator.pop(
                context,
                {'deviceId': widget.functions.first.deviceId},
              );
            }
          : null,
      isConfirmEnabled: state.selectedFunction != null,
    );
  }
}
