import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:on_field_work/controller/expense/expense_screen_controller.dart';
import 'package:on_field_work/helpers/utils/base_bottom_sheet.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/mixins/ui_mixin.dart';
import 'package:on_field_work/helpers/widgets/date_range_picker.dart';
import 'package:on_field_work/model/employees/multiple_select_bottomsheet.dart';


class ExpenseFilterBottomSheet extends StatefulWidget {
  final ExpenseController expenseController;
  final ScrollController scrollController;

  const ExpenseFilterBottomSheet({
    super.key,
    required this.expenseController,
    required this.scrollController,
  });

  @override
  State<ExpenseFilterBottomSheet> createState() =>
      _ExpenseFilterBottomSheetState();
}

class _ExpenseFilterBottomSheetState extends State<ExpenseFilterBottomSheet>
    with UIMixin {
  /// Search employees for Paid By / Created By filters
  Future<List<EmployeeModel>> searchEmployeesForBottomSheet(
      String query) async {
    await widget.expenseController.searchEmployees(query);
    return widget.expenseController.employeeSearchResults.toList();
  }

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      return BaseBottomSheet(
        title: 'Filter Expenses',
        onCancel: () => Get.back(),
        onSubmit: () {
          widget.expenseController.fetchExpenses();
          Get.back();
        },
        submitText: 'Submit',
        submitColor: contentTheme.primary,
        submitIcon: Icons.check_circle_outline,
        child: SingleChildScrollView(
          controller: widget.scrollController,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Align(
                alignment: Alignment.centerRight,
                child: TextButton(
                  onPressed: () => widget.expenseController.clearFilters(),
                  child: MyText(
                    "Reset Filter",
                    style: MyTextStyle.labelMedium(
                      color: Colors.red,
                      fontWeight: 600,
                    ),
                  ),
                ),
              ),
              MySpacing.height(8),
              _buildProjectFilter(),
              MySpacing.height(16),
              _buildStatusFilter(),
              MySpacing.height(16),
              _buildDateRangeFilter(),
              MySpacing.height(16),
              _buildPaidByFilter(),
              MySpacing.height(16),
              _buildCreatedByFilter(),
            ],
          ),
        ),
      );
    });
  }

  Widget _buildField(String label, Widget child) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        MyText.labelMedium(label),
        MySpacing.height(8),
        child,
      ],
    );
  }

  Widget _buildProjectFilter() {
    return _buildField(
      "Project",
      _popupSelector(
        currentValue: widget.expenseController.selectedProject.value.isEmpty
            ? 'Select Project'
            : widget.expenseController.selectedProject.value,
        items: widget.expenseController.globalProjects,
        onSelected: (value) =>
            widget.expenseController.selectedProject.value = value,
      ),
    );
  }

  Widget _buildStatusFilter() {
    return _buildField(
      "Expense Status",
      _popupSelector(
        currentValue: widget.expenseController.selectedStatus.value.isEmpty
            ? 'Select Expense Status'
            : widget.expenseController.expenseStatuses
                    .firstWhereOrNull((e) =>
                        e.id == widget.expenseController.selectedStatus.value)
                    ?.name ??
                'Select Expense Status',
        items: widget.expenseController.expenseStatuses
            .map((e) => e.name)
            .toList(),
        onSelected: (name) {
          final status = widget.expenseController.expenseStatuses
              .firstWhere((e) => e.name == name);
          widget.expenseController.selectedStatus.value = status.id;
        },
      ),
    );
  }

  Widget _buildDateRangeFilter() {
    return _buildField(
      "Date Filter",
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // --- Radio Buttons for Transaction Date / Created At ---
          Obx(() {
            return Row(
              children: [
                // --- Transaction Date ---
                Expanded(
                  child: Row(
                    children: [
                      Radio<String>(
                        value: "Transaction Date",
                        groupValue:
                            widget.expenseController.selectedDateType.value,
                        onChanged: (val) {
                          if (val != null) {
                            widget.expenseController.selectedDateType.value =
                                val;
                          }
                        },
                        activeColor: contentTheme.primary,
                      ),
                      Flexible(
                        child: MyText(
                          "Transaction Date",
                        ),
                      ),
                    ],
                  ),
                ),
                // --- Created At ---
                Expanded(
                  child: Row(
                    children: [
                      Radio<String>(
                        value: "Created At",
                        groupValue:
                            widget.expenseController.selectedDateType.value,
                        onChanged: (val) {
                          if (val != null) {
                            widget.expenseController.selectedDateType.value =
                                val;
                          }
                        },
                        activeColor: contentTheme.primary,
                      ),
                      Flexible(
                        child: MyText(
                          "Created At",
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            );
          }),
          MySpacing.height(16),
          // --- Reusable Date Range Picker ---
          DateRangePickerWidget(
            startDate: widget.expenseController.startDate,
            endDate: widget.expenseController.endDate,
            startLabel: "Start Date",
            endLabel: "End Date",
            onDateRangeSelected: (start, end) {
              widget.expenseController.startDate.value = start;
              widget.expenseController.endDate.value = end;
            },
          ),
        ],
      ),
    );
  }

  Widget _buildPaidByFilter() {
    return _buildField(
      "Paid By",
      _employeeSelector(
        selectedEmployees: widget.expenseController.selectedPaidByEmployees,
        searchEmployees: searchEmployeesForBottomSheet,
        title: 'Search Paid By',
      ),
    );
  }

  Widget _buildCreatedByFilter() {
    return _buildField(
      "Created By",
      _employeeSelector(
        selectedEmployees: widget.expenseController.selectedCreatedByEmployees,
        searchEmployees: searchEmployeesForBottomSheet,
        title: 'Search Created By',
      ),
    );
  }

  Widget _popupSelector({
    required String currentValue,
    required List<String> items,
    required ValueChanged<String> onSelected,
  }) {
    return PopupMenuButton<String>(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      onSelected: onSelected,
      itemBuilder: (context) => items
          .map((e) => PopupMenuItem<String>(
                value: e,
                child: MyText(e),
              ))
          .toList(),
      child: Container(
        padding: MySpacing.all(12),
        decoration: BoxDecoration(
          color: Colors.grey.shade100,
          border: Border.all(color: Colors.grey.shade300),
          borderRadius: BorderRadius.circular(12),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
              child: MyText(
                currentValue,
                style: const TextStyle(color: Colors.black87),
                overflow: TextOverflow.ellipsis,
              ),
            ),
            const Icon(Icons.arrow_drop_down, color: Colors.grey),
          ],
        ),
      ),
    );
  }

  Widget _employeeSelector({
    required RxList<EmployeeModel> selectedEmployees,
    required Future<List<EmployeeModel>> Function(String) searchEmployees,
    String title = 'Search Employee',
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Obx(() {
          if (selectedEmployees.isEmpty) return const SizedBox.shrink();
          return Wrap(
            spacing: 8,
            children: selectedEmployees
                .map(
                  (emp) => Chip(
                    label: MyText(emp.name),
                    onDeleted: () => selectedEmployees.remove(emp),
                  ),
                )
                .toList(),
          );
        }),
        MySpacing.height(8),
        GestureDetector(
          onTap: () async {
            final List<EmployeeModel>? result =
                await showModalBottomSheet<List<EmployeeModel>>(
              context: context,
              isScrollControlled: true,
              shape: const RoundedRectangleBorder(
                borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
              ),
              builder: (context) => EmployeeSelectionBottomSheet(
                initiallySelected: selectedEmployees.toList(),
                multipleSelection: true,
                title: title,
              ),
            );

            if (result != null) selectedEmployees.assignAll(result);
          },
          child: Container(
            padding: MySpacing.all(12),
            decoration: BoxDecoration(
              color: Colors.grey.shade100,
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: Colors.grey.shade300),
            ),
            child: Row(
              children: [
                const Icon(Icons.search, color: Colors.grey),
                MySpacing.width(8),
                Expanded(child: MyText(title)),
              ],
            ),
          ),
        ),
      ],
    );
  }
}
