import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:on_field_work/controller/document/user_document_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/document/document_filter_model.dart';
import 'dart:convert';
import 'package:on_field_work/helpers/utils/mixins/ui_mixin.dart';
import 'package:on_field_work/helpers/widgets/date_range_picker.dart';

class UserDocumentFilterBottomSheet extends StatefulWidget {
  final String entityId;
  final String entityTypeId;

  const UserDocumentFilterBottomSheet({
    super.key,
    required this.entityId,
    required this.entityTypeId,
  });

  @override
  State<UserDocumentFilterBottomSheet> createState() =>
      _UserDocumentFilterBottomSheetState();
}

class _UserDocumentFilterBottomSheetState
    extends State<UserDocumentFilterBottomSheet> with UIMixin {
  final DocumentController docController = Get.find<DocumentController>();

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

    final hasFilters = [
      filterData.uploadedBy,
      filterData.documentCategory,
      filterData.documentType,
      filterData.documentTag,
    ].any((list) => list.isNotEmpty);

    return BaseBottomSheet(
      title: 'Filter Documents',
      submitText: 'Apply',
      showButtons: hasFilters,
      onCancel: () => Get.back(),
      onSubmit: () {
        final combinedFilter = {
          'uploadedByIds': docController.selectedUploadedBy.toList(),
          'documentCategoryIds': docController.selectedCategory.toList(),
          'documentTypeIds': docController.selectedType.toList(),
          'documentTagIds': docController.selectedTag.toList(),
          'isUploadedAt': docController.isUploadedAt.value,
          'startDate': docController.startDate.value,
          'endDate': docController.endDate.value,
          if (docController.isVerified.value != null)
            'isVerified': docController.isVerified.value,
        };

        docController.fetchDocuments(
          entityTypeId: widget.entityTypeId,
          entityId: widget.entityId,
          filter: jsonEncode(combinedFilter),
          reset: true,
        );
        Get.back();
      },
      child: SingleChildScrollView(
        child: hasFilters
            ? Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Align(
                    alignment: Alignment.centerRight,
                    child: TextButton(
                      onPressed: docController.clearFilters,
                      child: MyText(
                        "Reset Filter",
                        style: MyTextStyle.labelMedium(
                          color: Colors.red,
                          fontWeight: 600,
                        ),
                      ),
                    ),
                  ),
                  // --- Date Range using Radio Buttons on Same Row ---
                  _buildField(
                    "Choose Date",
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Obx(() {
                          return Row(
                            children: [
                              // --- Upload Date ---
                              Expanded(
                                child: Row(
                                  children: [
                                    Radio<bool>(
                                      value: true,
                                      groupValue:
                                          docController.isUploadedAt.value,
                                      onChanged: (val) => docController
                                          .isUploadedAt.value = val!,
                                      activeColor: contentTheme.primary,
                                    ),
                                    MyText("Upload Date"),
                                  ],
                                ),
                              ),
                              // --- Update Date ---
                              Expanded(
                                child: Row(
                                  children: [
                                    Radio<bool>(
                                      value: false,
                                      groupValue:
                                          docController.isUploadedAt.value,
                                      onChanged: (val) => docController
                                          .isUploadedAt.value = val!,
                                      activeColor: contentTheme.primary,
                                    ),
                                    MyText("Update Date"),
                                  ],
                                ),
                              ),
                            ],
                          );
                        }),
                        MySpacing.height(12),

                        // --- Date Range Picker ---
                        DateRangePickerWidget(
                          startDate: docController.startDate,
                          endDate: docController.endDate,
                          startLabel: "From Date",
                          endLabel: "To Date",
                          onDateRangeSelected: (start, end) {
                            if (start != null && end != null) {
                              docController.startDate.value = start;
                              docController.endDate.value = end;
                            }
                          },
                        ),
                      ],
                    ),
                  ),

                  MySpacing.height(8),
                  _multiSelectField(
                    label: "Uploaded By",
                    items: filterData.uploadedBy,
                    fallback: "Choose Uploaded By",
                    selectedValues: docController.selectedUploadedBy,
                  ),
                  _multiSelectField(
                    label: "Category",
                    items: filterData.documentCategory,
                    fallback: "Choose Category",
                    selectedValues: docController.selectedCategory,
                  ),
                  _multiSelectField(
                    label: "Type",
                    items: filterData.documentType,
                    fallback: "Choose Type",
                    selectedValues: docController.selectedType,
                  ),
                  _multiSelectField(
                    label: "Tag",
                    items: filterData.documentTag,
                    fallback: "Choose Tag",
                    selectedValues: docController.selectedTag,
                  ),

                  // --- Document Status ---
                  _buildField(
                    " Document Status",
                    Obx(() {
                      return Container(
                        padding: MySpacing.all(12),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Radio<bool?>(
                                  value: null,
                                  groupValue: docController.isVerified.value,
                                  onChanged: (val) =>
                                      docController.isVerified.value = val,
                                  activeColor: contentTheme.primary,
                                  materialTapTargetSize:
                                      MaterialTapTargetSize.shrinkWrap,
                                ),
                                MyText("All"),
                              ],
                            ),
                            Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Radio<bool?>(
                                  value: true,
                                  groupValue: docController.isVerified.value,
                                  onChanged: (val) =>
                                      docController.isVerified.value = val,
                                  activeColor: contentTheme.primary,
                                  materialTapTargetSize:
                                      MaterialTapTargetSize.shrinkWrap,
                                ),
                                MyText("Verified"),
                              ],
                            ),
                            Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Radio<bool?>(
                                  value: false,
                                  groupValue: docController.isVerified.value,
                                  onChanged: (val) =>
                                      docController.isVerified.value = val,
                                  activeColor: contentTheme.primary,
                                  materialTapTargetSize:
                                      MaterialTapTargetSize.shrinkWrap,
                                ),
                                MyText("Rejected"),
                              ],
                            ),
                          ],
                        ),
                      );
                    }),
                  ),
                ],
              )
            : Center(
                child: Padding(
                  padding: const EdgeInsets.all(24.0),
                  child: MyText(
                    "No filters are available",
                    style: MyTextStyle.bodyMedium(
                      color: Colors.grey,
                      fontWeight: 500,
                    ),
                  ),
                ),
              ),
      ),
    );
  }

  Widget _multiSelectField({
    required String label,
    required List<FilterItem> items,
    required String fallback,
    required RxList<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((f) => selectedValues.contains(f.id))
              .map((f) => f.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(
                      (f) {
                        return PopupMenuItem<String>(
                          enabled: false, // prevent auto-close
                          child: StatefulBuilder(
                            builder: (context, setState) {
                              final isChecked = selectedValues.contains(f.id);
                              return CheckboxListTile(
                                dense: true,
                                value: isChecked,
                                contentPadding: EdgeInsets.zero,
                                controlAffinity:
                                    ListTileControlAffinity.leading,
                                title: MyText(f.name),

                                // --- Styles ---
                                checkColor: Colors.white, // tick color
                                side: const BorderSide(
                                    color: Colors.black,
                                    width: 1.5), // border when unchecked

                                fillColor:
                                    MaterialStateProperty.resolveWith<Color>(
                                  (states) {
                                    if (states
                                        .contains(MaterialState.selected)) {
                                      return contentTheme.primary;
                                    }
                                    return Colors.white; // unchecked → White
                                  },
                                ),

                                onChanged: (val) {
                                  if (val == true) {
                                    selectedValues.add(f.id);
                                  } else {
                                    selectedValues.remove(f.id);
                                  }
                                  setState(() {}); // refresh UI
                                },
                              );
                            },
                          ),
                        );
                      },
                    ).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),
      ],
    );
  }

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