import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/common/buttons/search_reset_buttons.dart';
import 'package:syncrow_web/pages/common/text_field/custom_text_field.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/bloc/device_mgmt_bloc/device_managment_bloc.dart';
import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart';

class DeviceSearchFilters extends StatefulWidget {
  const DeviceSearchFilters({super.key});

  @override
  State<DeviceSearchFilters> createState() => _DeviceSearchFiltersState();
}

class _DeviceSearchFiltersState extends State<DeviceSearchFilters>
    with HelperResponsiveLayout {
  late final TextEditingController _unitNameController;
  late final TextEditingController _productNameController;

  @override
  void initState() {
    _unitNameController = TextEditingController();
    _productNameController = TextEditingController();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Wrap(
      alignment: WrapAlignment.start,
      runAlignment: WrapAlignment.start,
      crossAxisAlignment: WrapCrossAlignment.center,
      spacing: 20,
      runSpacing: 10,
      children: [
        _buildSearchField("Space Name", _unitNameController, 200),
        _buildSearchField(
            "Device Name / Product Name", _productNameController, 300),
        _buildSearchResetButtons(),
      ],
    );
  }

  Widget _buildSearchField(
    String title,
    TextEditingController controller,
    double width,
  ) {
    return StatefulTextField(
      title: title,
      width: width,
      elevation: 2,
      controller: controller,
      onSubmitted: () {
        final searchDevicesEvent = SearchDevices(
          deviceNameOrProductName: _productNameController.text,
          unitName: _unitNameController.text,
          searchField: true,
        );
        context.read<DeviceManagementBloc>().add(searchDevicesEvent);
      },
      onChanged: (p0) {},
    );
  }

  Widget _buildSearchResetButtons() {
    return SearchResetButtons(
      onSearch: () => context.read<DeviceManagementBloc>().add(
            SearchDevices(
              unitName: _unitNameController.text,
              deviceNameOrProductName: _productNameController.text,
              searchField: true,
            ),
          ),
      onReset: () {
        _unitNameController.clear();
        _productNameController.clear();
        context.read<DeviceManagementBloc>().add(ResetFilters());
      },
    );
  }
}
