import 'dart:developer';

import 'package:flutter/material.dart';

import '/flutter_flow/flutter_flow_util.dart';
import '/flutter_flow/form_field_controller.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:hub/flutter_flow/flutter_flow_theme.dart';
import 'package:hub/flutter_flow/nav/nav.dart';
import 'package:hub/shared/utils/limited_text_size.dart';

class FilterModel extends FlutterFlowModel<FilterWidget> {
  FocusNode? textFieldFocusNode;
  TextEditingController? textController;
  String? Function(BuildContext, String?)? textControllerValidator;
  bool? checkboxValue1;
  bool? checkboxValue2;
  FormFieldController<List<String>>? checkboxGroupValueController;
  List<String>? get checkboxGroupValues => checkboxGroupValueController?.value;
  set checkboxGroupValues(List<String>? v) =>
      checkboxGroupValueController?.value = v;

  @override
  void initState(BuildContext context) {}

  @override
  void dispose() {
    textFieldFocusNode?.dispose();
    textController?.dispose();
  }
}

class FilterWidget extends StatefulWidget {
  final Map<String, dynamic> defaultSelections;
  final Map<String, List<Map<String, String>>> filterOptions;
  final Map<String, String> filterTitles;

  const FilterWidget({
    super.key,
    required this.defaultSelections,
    required this.filterOptions,
    required this.filterTitles,
  });

  @override
  _FilterWidgetState createState() => _FilterWidgetState();
}

class _FilterWidgetState extends State<FilterWidget> {
  late FilterModel _model;
  late Map<String, dynamic> selected;

  @override
  void setState(VoidCallback callback) {
    super.setState(callback);
    _model.onUpdate();
  }

  @override
  void initState() {
    super.initState();

    _model = createModel(context, () => FilterModel());

    _model.textController ??= TextEditingController();
    _model.textFieldFocusNode ??= FocusNode();

    selected = Map<String, dynamic>.from(widget.defaultSelections);
  }

  void _applyFilter() {
    Map<String, String> filterResult = {
      'search': _model.textController?.text == ''
          ? '.*'
          : _model.textController!.text.toLowerCase(),
    };

    widget.filterOptions.forEach((key, options) {
      filterResult[key] = selected[key]!.isEmpty || selected[key]!.length < 1
          ? '.*'
          : selected[key]!;
    });
    setState(() {
      // Update the state with the new filter result
      selected = filterResult;
    });
    context.pop(filterResult);
  }

  Widget _buildCheckboxListTile(
      String key, List<Map<String, String>> options, double fontsize) {
    double limitedInputFontSize = LimitedFontSizeUtil.getInputFontSize(context);
    return Column(
      children: [
        Row(
          mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Padding(
              padding: const EdgeInsetsDirectional.fromSTEB(0.0, 3.0, 0.0, 0.0),
              child: Text(
                widget.filterTitles[key]!,
                textAlign: TextAlign.left,
                style: FlutterFlowTheme.of(context).bodyMedium.override(
                      fontFamily: FlutterFlowTheme.of(context).bodyMediumFamily,
                      fontSize: limitedInputFontSize,
                      letterSpacing: 0.0,
                      useGoogleFonts: GoogleFonts.asMap().containsKey(
                          FlutterFlowTheme.of(context).bodyMediumFamily),
                      color: FlutterFlowTheme.of(context).primaryText,
                    ),
              ),
            ),
          ],
        ),
        ListView.builder(
          physics: const NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          itemCount: options.length,
          itemBuilder: (context, index) {
            final option = options[index];
            return CheckboxListTile(
              title: Text(
                option['title']!,
                style: FlutterFlowTheme.of(context).bodyMedium.override(
                      fontFamily: FlutterFlowTheme.of(context).bodyMediumFamily,
                      letterSpacing: 0.0,
                      fontSize: limitedInputFontSize,
                      useGoogleFonts: GoogleFonts.asMap().containsKey(
                          FlutterFlowTheme.of(context).bodyMediumFamily),
                      color: FlutterFlowTheme.of(context).primaryText,
                    ),
              ),
              dense: true,
              value: selected[key]!.contains(option['value']),
              onChanged: (bool? value) {
                setState(() {
                  if (value == true) {
                    if (!selected[key]!.contains(option['value'])) {
                      selected[key] = option['value'];
                    }
                  } else {
                    selected[key] = '';
                  }
                });
              },
              activeColor: FlutterFlowTheme.of(context).primary,
              checkColor: FlutterFlowTheme.of(context).info,
              checkboxShape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(100),
              ),
              enableFeedback: true,
              side: BorderSide(
                width: 5,
                color: FlutterFlowTheme.of(context).secondaryText,
              ),
              controlAffinity: ListTileControlAffinity.leading,
            );
          },
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    double screenWidth = MediaQuery.of(context).size.width;

    return Center(
      child: Container(
        width: screenWidth - (screenWidth * 0.35),
        height: screenWidth,
        decoration: BoxDecoration(
          color: FlutterFlowTheme.of(context).primaryBackground,
          borderRadius: BorderRadius.circular(24.0),
        ),
        child: Padding(
          padding: const EdgeInsets.all(4.0),
          child: Column(
            children: [
              Row(
                mainAxisSize: MainAxisSize.max,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsetsDirectional.fromSTEB(
                        10.0, 10.0, 0.0, 10.0),
                    child: Text(
                      FFLocalizations.of(context).getVariableText(
                        ptText: 'Filtros',
                        enText: 'Filters',
                      ),
                      style: FlutterFlowTheme.of(context)
                          .headlineMedium
                          .override(
                            fontFamily: FlutterFlowTheme.of(context)
                                .headlineMediumFamily,
                            color: FlutterFlowTheme.of(context).primaryText,
                            fontSize:
                                LimitedFontSizeUtil.getHeaderFontSize(context),
                            letterSpacing: 0.0,
                            fontWeight: FontWeight.bold,
                            useGoogleFonts: GoogleFonts.asMap().containsKey(
                                FlutterFlowTheme.of(context)
                                    .headlineMediumFamily),
                          ),
                    ),
                  ),
                ],
              ),
              Expanded(
                child: SingleChildScrollView(
                  child: Container(
                    padding: const EdgeInsets.all(10),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: widget.filterOptions.keys.map((key) {
                        return _buildCheckboxListTile(
                            key, widget.filterOptions[key]!, 14);
                      }).toList(),
                    ),
                  ),
                ),
              ),
              ElevatedButton(
                onPressed: _applyFilter,
                style: ElevatedButton.styleFrom(
                  foregroundColor: FlutterFlowTheme.of(context).info,
                  backgroundColor: FlutterFlowTheme.of(context).primary,
                ),
                child: Text(
                    FFLocalizations.of(context).getVariableText(
                      ptText: 'Aplicar',
                      enText: 'Apply',
                    ),
                    style: FlutterFlowTheme.of(context).bodyMedium.override(
                          fontFamily:
                              FlutterFlowTheme.of(context).bodyMediumFamily,
                          color: FlutterFlowTheme.of(context).info,
                          fontSize:
                              LimitedFontSizeUtil.getInputFontSize(context),
                          letterSpacing: 0.0,
                          fontWeight: FontWeight.bold,
                          useGoogleFonts: GoogleFonts.asMap().containsKey(
                              FlutterFlowTheme.of(context).bodyMediumFamily),
                        )),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
