import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:hub/components/molecular_components/order_filter_modal/order_filter_modal_model.dart';
import 'package:hub/flutter_flow/flutter_flow_theme.dart';
import 'package:hub/flutter_flow/flutter_flow_util.dart';
import 'package:hub/flutter_flow/nav/nav.dart';
// ignore: unused_import

import 'package:hub/shared/utils/limited_text_size.dart';

class OrderFilterModalWidget extends StatefulWidget {
  final String defaultAdresseeType;
  final String defaultStatus;

  const OrderFilterModalWidget({
    super.key,
    this.defaultAdresseeType = '.*',
    this.defaultStatus = '.*',
  });

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

class _OrderFilterModalWidgetState extends State<OrderFilterModalWidget> {
  late OrderFilterModalModel _model;

  late Map<String, dynamic> selected;
  final List<Map<String, String>> adresseeTypeOptions = [
    {
      'title': FFLocalizations.of(navigatorKey.currentContext!)
          .getVariableText(enText: 'Resident', ptText: 'Morador'),
      'value': 'MOR'
    },
    {
      'title': FFLocalizations.of(navigatorKey.currentContext!)
          .getVariableText(enText: 'Property', ptText: 'Propriedade'),
      'value': 'PRO'
    },
  ];
  final List<Map<String, String>> statusOptions = [
    {
      'title': FFLocalizations.of(navigatorKey.currentContext!).getVariableText(
          ptText: 'Aguardando Retirada', enText: 'Waiting for Pickup'),
      'value': 'notPickedUp'
    },
    {
      'title': FFLocalizations.of(navigatorKey.currentContext!)
          .getVariableText(ptText: 'Retirado', enText: 'Picked Up'),
      'value': 'pickedUp'
    },
  ];

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

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

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

    selected = {
      'adresseeType': widget.defaultAdresseeType == '.*'
          ? ['MOR', 'PRO']
          : [widget.defaultAdresseeType],
      'status': widget.defaultStatus == '.*'
          ? ['notPickedUp', 'pickedUp']
          : [widget.defaultStatus],
    };
  }

  void _applyFilter() {
    Map<String, String> filterResult = {
      'adresseeType': '',
      'status': '',
    };

    if (selected['adresseeType']!.isEmpty) {
      filterResult['adresseeType'] = '.*';
    } else if (selected['adresseeType']!.length > 1) {
      filterResult['adresseeType'] = '.*';
    } else {
      filterResult['adresseeType'] = selected['adresseeType']!.first;
    }

    if (selected['status']!.isEmpty) {
      filterResult['status'] = '.*';
    } else if (selected['status']!.length > 1) {
      filterResult['status'] = '.*';
    } else {
      filterResult['status'] = selected['status']!.first;
    }

    // Navigator.pop(context, filterResult);
    context.pop(filterResult);
  }

  Widget _buildCheckboxListTile(
      String key, List<Map<String, String>> options, double fontsize) {
    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(
                key == 'status' ? 'Status' : 'Destinátario',
                textAlign: TextAlign.left,
                style: FlutterFlowTheme.of(context).bodyMedium.override(
                      fontFamily: FlutterFlowTheme.of(context).bodyMediumFamily,
                      fontSize: fontsize,
                      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: fontsize,
                      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]!.add(option['value']);
                    }
                  } else {
                    selected[key]!.remove(option['value']);
                  }
                });
              },
              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, // Adiciona esta linha
            );
          },
        ),
      ],
    );
  }

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

    return Center(
      child: Container(
        width: screenWidth - (screenWidth * 0.35),
        height: 420,
        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)
                          .getText('yfj9pd6k'), // Filtros
                      style:
                          FlutterFlowTheme.of(context).headlineMedium.override(
                                fontFamily: FlutterFlowTheme.of(context)
                                    .headlineMediumFamily,
                                color: FlutterFlowTheme.of(context).primaryText,
                                fontSize: 18.0,
                                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: [
                        _buildCheckboxListTile('adresseeType',
                            adresseeTypeOptions, limitedBodyFontSize),
                        _buildCheckboxListTile(
                            'status', statusOptions, limitedBodyFontSize),
                      ],
                    ),
                  ),
                ),
              ),
              ElevatedButton(
                onPressed: _applyFilter,
                style: ElevatedButton.styleFrom(
                  foregroundColor: FlutterFlowTheme.of(context).info,
                  backgroundColor: FlutterFlowTheme.of(context).primary,
                ),
                child: Text(FFLocalizations.of(context).getText('88kshkph'),
                    style: TextStyle(fontSize: limitedBodyFontSize)),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
