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/utils/date_time_utils.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';
import 'dart:convert';

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',
      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: entityTypeId,
          entityId: 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 Filter (Uploaded On / Updated On) ---
                  _buildField(
                    "Choose Date",
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // Segmented Buttons
                        Obx(() {
                          return Container(
                            decoration: BoxDecoration(
                              border: Border.all(color: Colors.grey.shade300),
                              borderRadius: BorderRadius.circular(24),
                            ),
                            child: Row(
                              children: [
                                Expanded(
                                  child: GestureDetector(
                                    onTap: () =>
                                        docController.isUploadedAt.value = true,
                                    child: Container(
                                      padding: const EdgeInsets.symmetric(
                                          vertical: 10),
                                      decoration: BoxDecoration(
                                        color: docController.isUploadedAt.value
                                            ? Colors.indigo.shade400
                                            : Colors.transparent,
                                        borderRadius:
                                            const BorderRadius.horizontal(
                                          left: Radius.circular(24),
                                        ),
                                      ),
                                      child: Center(
                                        child: MyText(
                                          "Upload Date",
                                          style: MyTextStyle.bodyMedium(
                                            color:
                                                docController.isUploadedAt.value
                                                    ? Colors.white
                                                    : Colors.black87,
                                            fontWeight: 600,
                                          ),
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                                Expanded(
                                  child: GestureDetector(
                                    onTap: () => docController
                                        .isUploadedAt.value = false,
                                    child: Container(
                                      padding: const EdgeInsets.symmetric(
                                          vertical: 10),
                                      decoration: BoxDecoration(
                                        color: !docController.isUploadedAt.value
                                            ? Colors.indigo.shade400
                                            : Colors.transparent,
                                        borderRadius:
                                            const BorderRadius.horizontal(
                                          right: Radius.circular(24),
                                        ),
                                      ),
                                      child: Center(
                                        child: MyText(
                                          "Update Date",
                                          style: MyTextStyle.bodyMedium(
                                            color: !docController
                                                    .isUploadedAt.value
                                                ? Colors.white
                                                : Colors.black87,
                                            fontWeight: 600,
                                          ),
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          );
                        }),
                        MySpacing.height(12),

                        // Date Range
                        Row(
                          children: [
                            Expanded(
                              child: Obx(() {
                                return _dateButton(
                                  label: docController.startDate.value == null
                                      ? 'From Date'
                                      : DateTimeUtils.formatDate(
                                          DateTime.parse(
                                              docController.startDate.value!),
                                          'dd MMM yyyy',
                                        ),
                                  onTap: () async {
                                    final picked = await showDatePicker(
                                      context: context,
                                      initialDate: DateTime.now(),
                                      firstDate: DateTime(2000),
                                      lastDate: DateTime.now(),
                                    );
                                    if (picked != null) {
                                      docController.startDate.value =
                                          picked.toIso8601String();
                                    }
                                  },
                                );
                              }),
                            ),
                            MySpacing.width(12),
                            Expanded(
                              child: Obx(() {
                                return _dateButton(
                                  label: docController.endDate.value == null
                                      ? 'To Date'
                                      : DateTimeUtils.formatDate(
                                          DateTime.parse(
                                              docController.endDate.value!),
                                          'dd MMM yyyy',
                                        ),
                                  onTap: () async {
                                    final picked = await showDatePicker(
                                      context: context,
                                      initialDate: DateTime.now(),
                                      firstDate: DateTime(2000),
                                      lastDate: DateTime.now(),
                                    );
                                    if (picked != null) {
                                      docController.endDate.value =
                                          picked.toIso8601String();
                                    }
                                  },
                                );
                              }),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),

                  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:
                                      Colors.indigo,
                                  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: Colors.indigo,
                                  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: Colors.indigo,
                                  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 Colors.indigo; // checked → Indigo
                                    }
                                    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),
      ],
    );
  }

  Widget _dateButton({required String label, required VoidCallback onTap}) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: MySpacing.xy(16, 12),
        decoration: BoxDecoration(
          color: Colors.grey.shade100,
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: Colors.grey.shade300),
        ),
        child: Row(
          children: [
            const Icon(Icons.calendar_today, size: 16, color: Colors.grey),
            MySpacing.width(8),
            Expanded(
              child: MyText(
                label,
                style: MyTextStyle.bodyMedium(),
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
