import 'package:flutter/material.dart';
import 'package:get/get.dart';

import 'package:on_field_work/controller/task_planning/daily_task_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/date_range_picker.dart';

class DailyTaskFilterBottomSheet extends StatelessWidget {
  final DailyTaskController controller;

  const DailyTaskFilterBottomSheet({super.key, required this.controller});

  @override
  Widget build(BuildContext context) {
    final filterData = controller.taskFilterData;
    if (filterData == null) return const SizedBox.shrink();

    final hasFilters = [
      filterData.buildings,
      filterData.floors,
      filterData.activities,
      filterData.services,
    ].any((list) => list.isNotEmpty);

    return SafeArea(
      // ✅ PREVENTS GOING UNDER NAV BUTTONS
      bottom: true,
      child: BaseBottomSheet(
        title: "Filter Tasks",
        submitText: "Apply",
        showButtons: hasFilters,
        onCancel: () => Get.back(),
        onSubmit: () {
          if (controller.selectedProjectId != null) {
            controller.fetchTaskData(controller.selectedProjectId!);
          }
          Get.back();
        },
        child: SingleChildScrollView(
          padding: const EdgeInsets.only(bottom: 40), // ✅ EXTRA SAFETY PADDING
          child: hasFilters
              ? Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Align(
                      alignment: Alignment.centerRight,
                      child: TextButton(
                        onPressed: () {
                          controller.clearTaskFilters();
                        },
                        child: MyText(
                          "Reset Filter",
                          style: const TextStyle(
                            color: Colors.red,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),
                    ),
                    MySpacing.height(8),
                    _multiSelectField(
                      label: "Buildings",
                      items: filterData.buildings,
                      fallback: "Select Buildings",
                      selectedValues: controller.selectedBuildings,
                    ),
                    _multiSelectField(
                      label: "Floors",
                      items: filterData.floors,
                      fallback: "Select Floors",
                      selectedValues: controller.selectedFloors,
                    ),
                    _multiSelectField(
                      label: "Activities",
                      items: filterData.activities,
                      fallback: "Select Activities",
                      selectedValues: controller.selectedActivities,
                    ),
                    _multiSelectField(
                      label: "Services",
                      items: filterData.services,
                      fallback: "Select Services",
                      selectedValues: controller.selectedServices,
                    ),
                    MySpacing.height(8),
                    _dateRangeSelector(context),
                  ],
                )
              : Center(
                  child: Padding(
                    padding: const EdgeInsets.all(24.0),
                    child: MyText(
                      "No filters available",
                      style: const TextStyle(color: Colors.grey),
                    ),
                  ),
                ),
        ),
      ),
    );
  }

  // MULTI SELECT FIELD
  Widget _multiSelectField({
    required String label,
    required List<dynamic> items,
    required String fallback,
    required RxSet<String> selectedValues,
  }) {
    if (items.isEmpty) return const SizedBox.shrink();

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        MyText.labelMedium(label),
        MySpacing.height(8),
        Obx(() {
          final selectedNames = items
              .where((item) => selectedValues.contains(item.id))
              .map((item) => item.name)
              .join(", ");

          final displayText =
              selectedNames.isNotEmpty ? selectedNames : fallback;

          return Builder(
            builder: (context) {
              return GestureDetector(
                onTap: () async {
                  final RenderBox button =
                      context.findRenderObject() as RenderBox;
                  final RenderBox overlay = Overlay.of(context)
                      .context
                      .findRenderObject() as RenderBox;

                  final position = button.localToGlobal(Offset.zero);

                  await showMenu(
                    context: context,
                    position: RelativeRect.fromLTRB(
                      position.dx,
                      position.dy + button.size.height,
                      overlay.size.width - position.dx - button.size.width,
                      0,
                    ),
                    items: items.map((item) {
                      return PopupMenuItem<String>(
                        enabled: false,
                        child: StatefulBuilder(
                          builder: (context, setState) {
                            final isChecked = selectedValues.contains(item.id);

                            return CheckboxListTile(
                              dense: true,
                              value: isChecked,
                              contentPadding: EdgeInsets.zero,
                              controlAffinity: ListTileControlAffinity.leading,
                              title: MyText(item.name),
                              checkColor: Colors.white,
                              side: const BorderSide(
                                  color: Colors.black, width: 1.5),
                              fillColor:
                                  MaterialStateProperty.resolveWith<Color>(
                                (states) =>
                                    states.contains(MaterialState.selected)
                                        ? Colors.indigo
                                        : Colors.white,
                              ),
                              onChanged: (val) {
                                if (val == true) {
                                  selectedValues.add(item.id);
                                } else {
                                  selectedValues.remove(item.id);
                                }
                                setState(() {});
                              },
                            );
                          },
                        ),
                      );
                    }).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(
                          displayText,
                          style: const TextStyle(color: Colors.black87),
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      const Icon(Icons.arrow_drop_down, color: Colors.grey),
                    ],
                  ),
                ),
              );
            },
          );
        }),
        MySpacing.height(16),
      ],
    );
  }

  // DATE RANGE PICKER
  Widget _dateRangeSelector(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        MyText.labelMedium("Select Date Range"),
        MySpacing.height(8),
        DateRangePickerWidget(
          startDate: controller.startDateTaskRx,
          endDate: controller.endDateTaskRx,
          startLabel: "From Date",
          endLabel: "To Date",
          onDateRangeSelected: (start, end) {
            controller.updateDateRange(start, end);
          },
        ),
        MySpacing.height(16),
      ],
    );
  }
}
