import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:marco/controller/document/user_document_controller.dart';
import 'package:marco/helpers/utils/base_bottom_sheet.dart';
import 'package:marco/helpers/widgets/my_spacing.dart';
import 'package:marco/helpers/widgets/my_text.dart';
import 'package:marco/helpers/widgets/my_text_style.dart';
import 'package:marco/model/document/document_filter_model.dart';

class UserDocumentFilterBottomSheet extends StatelessWidget {
  final String entityId;
  final String entityTypeId;
  final DocumentController docController = Get.find<DocumentController>();

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

  @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',
      showButtons: hasFilters,
      onCancel: () => Get.back(),
      onSubmit: () {
        final combinedFilter = {
          'uploadedBy': docController.selectedUploadedBy.value,
          'category': docController.selectedCategory.value,
          'type': docController.selectedType.value,
          'tag': docController.selectedTag.value,
        };
        docController.fetchDocuments(
          entityTypeId: entityTypeId,
          entityId: entityId,
          filter: combinedFilter.toString(),
          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,
                        ),
                      ),
                    ),
                  ),
                  MySpacing.height(8),
                  _buildDynamicField(
                    label: "Uploaded By",
                    items: filterData.uploadedBy,
                    fallback: "Select Uploaded By",
                    selectedValue: docController.selectedUploadedBy,
                  ),
                  _buildDynamicField(
                    label: "Category",
                    items: filterData.documentCategory,
                    fallback: "Select Category",
                    selectedValue: docController.selectedCategory,
                  ),
                  _buildDynamicField(
                    label: "Type",
                    items: filterData.documentType,
                    fallback: "Select Type",
                    selectedValue: docController.selectedType,
                  ),
                  _buildDynamicField(
                    label: "Tag",
                    items: filterData.documentTag,
                    fallback: "Select Tag",
                    selectedValue: docController.selectedTag,
                  ),
                ].where((w) => w != null).cast<Widget>().toList(),
              )
            : Center(
                child: Padding(
                  padding: const EdgeInsets.all(24.0),
                  child: MyText(
                    "No filters are available",
                    style: MyTextStyle.bodyMedium(
                      color: Colors.grey,
                      fontWeight: 500,
                    ),
                  ),
                ),
              ),
      ),
    );
  }

  Widget? _buildDynamicField({
    required String label,
    required List<FilterItem> items,
    required String fallback,
    required RxString selectedValue,
  }) {
    if (items.isEmpty) return null;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        MyText.labelMedium(label),
        MySpacing.height(8),
        _popupSelector(items, fallback, selectedValue: selectedValue),
        MySpacing.height(16),
      ],
    );
  }

  Widget _popupSelector(
    List<FilterItem> items,
    String fallback, {
    required RxString selectedValue,
  }) {
    return Obx(() {
      final currentValue = _getCurrentName(selectedValue.value, items, fallback);
      return PopupMenuButton<String>(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        onSelected: (val) => selectedValue.value = val,
        itemBuilder: (context) => items
            .map(
              (f) => PopupMenuItem<String>(
                value: f.id,
                child: MyText(f.name),
              ),
            )
            .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),
            ],
          ),
        ),
      );
    });
  }

  String _getCurrentName(String selectedId, List<FilterItem> list, String fallback) {
    if (selectedId.isEmpty) return fallback;
    final match = list.firstWhereOrNull((f) => f.id == selectedId);
    return match?.name ?? fallback;
  }
}
