import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/common/text_field/custom_text_field.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/bloc/device_managment_bloc.dart';
import 'package:syncrow_web/pages/common/buttons/search_reset_buttons.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 {
  final TextEditingController communityController = TextEditingController();
  final TextEditingController unitNameController = TextEditingController();
  final TextEditingController productNameController = TextEditingController();

  @override
  void dispose() {
    communityController.dispose();
    unitNameController.dispose();
    productNameController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return isExtraLargeScreenSize(context)
        ? Row(
            children: [
              _buildSearchField("Community", communityController, 200),
              const SizedBox(width: 20),
              _buildSearchField("Unit Name", unitNameController, 200),
              const SizedBox(width: 20),
              _buildSearchField(
                  "Device Name / Product Name", productNameController, 300),
              const SizedBox(width: 20),
              _buildSearchResetButtons(),
            ],
          )
        : Wrap(
            spacing: 20,
            runSpacing: 10,
            children: [
              _buildSearchField("Community", communityController, 200),
              _buildSearchField("Unit 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,
    );
  }

  Widget _buildSearchResetButtons() {
    return SearchResetButtons(
      onSearch: () {
        context.read<DeviceManagementBloc>().add(SearchDevices(
              community: communityController.text,
              unitName: unitNameController.text,
              productName: productNameController.text,
            ));
      },
      onReset: () {
        communityController.clear();
        unitNameController.clear();
        productNameController.clear();
        context.read<DeviceManagementBloc>()
          ..add(ResetFilters())
          ..add(FetchDevices());
      },
    );
  }
}
