import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:on_field_work/helpers/widgets/my_spacing.dart';
import 'package:on_field_work/helpers/widgets/my_text.dart';
import 'package:on_field_work/helpers/widgets/my_text_style.dart';
import 'package:on_field_work/model/employees/employee_model.dart';
import 'package:on_field_work/helpers/utils/base_bottom_sheet.dart';

class EmployeeSelectorBottomSheet extends StatefulWidget {
  final RxList<EmployeeModel> selectedEmployees;
  final Future<List<EmployeeModel>> Function(String) searchEmployees;
  final String title;

  const EmployeeSelectorBottomSheet({
    super.key,
    required this.selectedEmployees,
    required this.searchEmployees,
    this.title = "Select Employees",
  });

  @override
  State<EmployeeSelectorBottomSheet> createState() =>
      _EmployeeSelectorBottomSheetState();
}

class _EmployeeSelectorBottomSheetState
    extends State<EmployeeSelectorBottomSheet> {
  final TextEditingController _searchController = TextEditingController();
  final RxBool isSearching = false.obs;
  final RxList<EmployeeModel> searchResults = <EmployeeModel>[].obs;

  @override
  void initState() {
    super.initState();
    // Initial fetch (empty text gets all/none as you wish)
    _searchEmployees('');
  }

  void _searchEmployees(String query) async {
    isSearching.value = true;
    List<EmployeeModel> results = await widget.searchEmployees(query);
    searchResults.assignAll(results);
    isSearching.value = false;
  }

  void _submitSelection() =>
      Get.back(result: widget.selectedEmployees.toList());

  @override
  Widget build(BuildContext context) {
    return BaseBottomSheet(
        title: widget.title,
        onCancel: () => Get.back(),
        onSubmit: _submitSelection,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            // Chips
            Obx(() => widget.selectedEmployees.isEmpty
                ? const SizedBox.shrink()
                : Wrap(
                    spacing: 8,
                    children: widget.selectedEmployees
                        .map(
                          (emp) => Chip(
                            label: MyText(emp.name),
                            onDeleted: () =>
                                widget.selectedEmployees.remove(emp),
                          ),
                        )
                        .toList(),
                  )),
            MySpacing.height(8),

            // Search box
            TextField(
              controller: _searchController,
              decoration: InputDecoration(
                hintText: "Search Employees...",
                border:
                    OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
                prefixIcon: Icon(Icons.search),
              ),
              onChanged: _searchEmployees,
            ),
            MySpacing.height(12),

            SizedBox(
              height: 320, // CHANGE AS PER DESIGN!
              child: Obx(() {
                if (isSearching.value) {
                  return Center(child: CircularProgressIndicator());
                }
                if (searchResults.isEmpty) {
                  return Padding(
                    padding: EdgeInsets.all(20),
                    child:
                        MyText('No results', style: MyTextStyle.bodyMedium()),
                  );
                }
                return ListView.separated(
                  itemCount: searchResults.length,
                  separatorBuilder: (_, __) => Divider(height: 1),
                  itemBuilder: (context, index) {
                    final emp = searchResults[index];
                    final isSelected = widget.selectedEmployees.contains(emp);
                    return ListTile(
                        title: MyText(emp.name),
                        trailing: isSelected
                            ? Icon(Icons.check_circle, color: Colors.indigo)
                            : Icon(Icons.radio_button_unchecked,
                                color: Colors.grey),
                        onTap: () {
                          if (isSelected) {
                            widget.selectedEmployees.remove(emp);
                          } else {
                            widget.selectedEmployees.add(emp);
                          }
                        });
                  },
                );
              }),
            ),
          ],
        ));
  }
}
