// import 'dart:js_interop';

import 'dart:developer';

import 'package:hub/actions/actions.dart';
import 'package:hub/backend/api_requests/api_calls.dart';
import 'package:hub/backend/push_notification/pushNotificationService.dart';

import 'package:hub/components/templates_components/card_item_template_component/card_item_template_component_widget.dart';
import 'package:hub/components/templates_components/visit_request_template_component/visit_request_template_component_widget.dart';
import 'package:hub/flutter_flow/custom_functions.dart';
import 'package:hub/flutter_flow/flutter_flow_icon_button.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';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:hub/pages/liberation_history/liberation_history_model.dart';
import 'package:provider/provider.dart';

class LiberationHistoryWidget extends StatefulWidget {
  const LiberationHistoryWidget({super.key});

  @override
  State<LiberationHistoryWidget> createState() =>
      _LiberationHistoryWidgetState();
}

class _LiberationHistoryWidgetState extends State<LiberationHistoryWidget> {
  late LiberationHistoryModel _model;

  final scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  void initState() {
    super.initState();
    _model = createModel(context, () => LiberationHistoryModel());

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

  @override
  void dispose() {
    _model.dispose();

    super.dispose();
  }

  void onUpdate(BuildContext context) {
    _model.clearGetLiberationsCache();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    context.watch<FFAppState>();
    return GestureDetector(
      onTap: () => _model.unfocusNode.canRequestFocus
          ? FocusScope.of(context).requestFocus(_model.unfocusNode)
          : FocusScope.of(context).unfocus(),
      child: Scaffold(
        key: scaffoldKey,
        backgroundColor: FlutterFlowTheme.of(context).primaryBackground,
        appBar: appBarLiberationHistoryPage(context),
        body: bodyLiberationHistoryPage(context, _model),
      ),
    );
  }
}

PreferredSizeWidget appBarLiberationHistoryPage(BuildContext context) {
  return AppBar(
    backgroundColor: FlutterFlowTheme.of(context).primaryBackground,
    automaticallyImplyLeading: false,
    forceMaterialTransparency: true,
    leading: FlutterFlowIconButton(
      borderColor: Colors.transparent,
      borderRadius: 30.0,
      borderWidth: 1.0,
      buttonSize: 60.0,
      icon: Icon(
        Icons.keyboard_arrow_left,
        color: FlutterFlowTheme.of(context).primaryText,
        size: 30.0,
      ),
      onPressed: () async {
        context.pop();
      },
    ),
    title: Text(
      FFLocalizations.of(context).getText(
        '784f83pc' /* Histórico de Liberação */,
      ),
      style: FlutterFlowTheme.of(context).headlineMedium.override(
            fontFamily: 'Nunito',
            color: FlutterFlowTheme.of(context).primaryText,
            fontSize: 17.0,
            letterSpacing: 0.0,
            useGoogleFonts: GoogleFonts.asMap().containsKey('Nunito'),
          ),
    ),
    actions: const [],
    centerTitle: true,
    elevation: 0.0,
  );
}

Widget bodyLiberationHistoryPage(
    BuildContext context, LiberationHistoryModel _model) {
  return SafeArea(
    top: true,
    child: Column(
      mainAxisSize: MainAxisSize.max,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        searchBarContainer(context, _model),
        Expanded(child: liberationDynamicListView(context, _model)),
      ].addToStart(const SizedBox(height: 0)),
    ),
  );
}

Widget searchBarContainer(BuildContext context, LiberationHistoryModel _model) {
  return Column(
    mainAxisSize: MainAxisSize.max,
    mainAxisAlignment: MainAxisAlignment.start,
    children: [
      Row(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Padding(
            padding: const EdgeInsetsDirectional.fromSTEB(8.0, 8.0, 8.0, 8.0),
            child: SizedBox(
              width: 300.0,
              height: 40.0,
              child: TextFormField(
                controller: _model.textController,
                focusNode: _model.textFieldFocusNode,
                autofocus: false,
                obscureText: false,
                decoration: InputDecoration(
                  isDense: true,
                  labelText: FFLocalizations.of(context).getText(
                    'dy0mx15f' /* Pesquise aqui */,
                  ),
                  labelStyle: FlutterFlowTheme.of(context).labelMedium.override(
                        fontFamily:
                            FlutterFlowTheme.of(context).labelMediumFamily,
                        color: FlutterFlowTheme.of(context).primaryText,
                        letterSpacing: 0.0,
                        useGoogleFonts: GoogleFonts.asMap().containsKey(
                            FlutterFlowTheme.of(context).labelMediumFamily),
                      ),
                  hintStyle: FlutterFlowTheme.of(context).labelMedium.override(
                        fontFamily:
                            FlutterFlowTheme.of(context).labelMediumFamily,
                        color: FlutterFlowTheme.of(context).primaryText,
                        letterSpacing: 0.0,
                        useGoogleFonts: GoogleFonts.asMap().containsKey(
                            FlutterFlowTheme.of(context).labelMediumFamily),
                      ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: FlutterFlowTheme.of(context).alternate,
                      width: 2.0,
                    ),
                    borderRadius: BorderRadius.circular(8.0),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: FlutterFlowTheme.of(context).primary,
                      width: 2.0,
                    ),
                    borderRadius: BorderRadius.circular(8.0),
                  ),
                  errorBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: FlutterFlowTheme.of(context).error,
                      width: 2.0,
                    ),
                    borderRadius: BorderRadius.circular(8.0),
                  ),
                  focusedErrorBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: FlutterFlowTheme.of(context).error,
                      width: 2.0,
                    ),
                    borderRadius: BorderRadius.circular(8.0),
                  ),
                  filled: true,
                  fillColor: FlutterFlowTheme.of(context).alternate,
                  prefixIcon: Icon(
                    Icons.search_sharp,
                    color: FlutterFlowTheme.of(context).primaryText,
                  ),
                ),
                style: FlutterFlowTheme.of(context).bodyMedium.override(
                      fontFamily: FlutterFlowTheme.of(context).bodyMediumFamily,
                      letterSpacing: 0.0,
                      useGoogleFonts: GoogleFonts.asMap().containsKey(
                          FlutterFlowTheme.of(context).bodyMediumFamily),
                    ),
                validator: _model.textControllerValidator.asValidator(context),
              ),
            ),
          ),
        ],
      ),
    ].addToStart(const SizedBox(height: 0)),
  );
}

Widget liberationDynamicListView(
  BuildContext context,
  LiberationHistoryModel _model,
) {
  return Container(
    width: double.infinity,
    height: double.infinity,
    decoration: const BoxDecoration(),
    child: StreamBuilder<ApiCallResponse>(
      stream: _model.getLiberations(
        requestFn: () => PhpGroup.getLiberationsCall.call(
          devUUID: FFAppState().devUUID,
          userUUID: FFAppState().userUUID,
          cliID: FFAppState().cliUUID,
          atividade: 'getSolicitacoes',
        ),
      ),
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return Center(
            child: SizedBox(
              width: 50.0,
              height: 50.0,
              child: SpinKitCircle(
                color: FlutterFlowTheme.of(context).primary,
                size: 50.0,
              ),
            ),
          );
        }
        final columnGetLiberationsResponse = snapshot.data!;
        final liberationHistory = PhpGroup.getLiberationsCall
                .rqList(
                  columnGetLiberationsResponse.jsonBody,
                )
                ?.toList() ??
            [];
        final filteredLiberationHistory = _model.textController.text.isNotEmpty
            ? liberationHistory
                .where((item) => jsonToStr(getJsonField(
                      item,
                      r'''$.VTE_NOME''',
                    )).toLowerCase().contains(
                          _model.textController.text.toLowerCase(),
                        ))
                .toList()
            : liberationHistory;

        return ListView.builder(
          itemCount: filteredLiberationHistory.length,
          addAutomaticKeepAlives: false,
          addRepaintBoundaries: true,
          cacheExtent: 1000.0,
          itemBuilder: (BuildContext context, int index) {
            final liberationHistoryItem = filteredLiberationHistory[index];
            return Padding(
              padding: EdgeInsets.only(
                top: index == 0
                    ? MediaQuery.of(context).size.height * 0.075
                    : 8.0,
                left: 8.0,
                right: 8.0,
                bottom: 8.0,
              ),
              child: Align(
                alignment: AlignmentDirectional(0.0, 0.0),
                child: liberationHistoryItemCard(
                  context,
                  liberationHistoryItem,
                ),
              ),
            );
          },
        );
      },
    ),
  );
}

Widget liberationHistoryItemCard(
    BuildContext context, dynamic liberationHistoryItem) {
  return CardItemTemplateComponentWidget(
    imageHashMap: Map<String, String>.from({
      'key': liberationHistoryItem['VTE_ID'],
      'value': 'E',
    }),
    labelsHashMap: Map<String, String>.from({
      'Nome:': liberationHistoryItem['VTE_NOME'],
      'Data:': liberationHistoryItem['NOT_DTENVIO'],
      'Motivo:': liberationHistoryItem['NOT_MOTIVO'],
    }),
    statusHashMap: [
      liberationHistoryItem['NOT_STATUS'] == 'L'
          ? Map<String, Color>.from({
              FFLocalizations.of(context).getVariableText(
                ptText: 'Ativo',
                enText: 'Active',
              ): FlutterFlowTheme.of(context).success,
            })
          : liberationHistoryItem['NOT_STATUS'] == 'B'
              ? Map<String, Color>.from({
                  FFLocalizations.of(context).getVariableText(
                    ptText: 'Bloqueado',
                    enText: 'Blocked',
                  ): FlutterFlowTheme.of(context).error,
                })
              : Map<String, Color>.from({
                  FFLocalizations.of(context).getVariableText(
                    ptText: 'Pendente',
                    enText: 'Pending',
                  ): FlutterFlowTheme.of(context).warning,
                })
    ],
    onTapCardItemAction: () async {
      showModalBottomSheet(
        isScrollControlled: true,
        isDismissible: true,
        backgroundColor: Colors.transparent,
        useSafeArea: true,
        context: context,
        builder: (context) {
          return VisitRequestTemplateComponentWidget(
            vteName: liberationHistoryItem['VTE_NOME'],
            vteReason: liberationHistoryItem['NOT_MOTIVO'],
            vawDate: liberationHistoryItem['NOT_STATUS'] == 'S'
                ? liberationHistoryItem['NOT_DTENVIO']
                : liberationHistoryItem['NOT_DTRESPOSTA'],
            vawStatus: liberationHistoryItem['NOT_STATUS'],
            vteMsg: liberationHistoryItem['NOT_MSGENVIO'],
            vteUUID: liberationHistoryItem['VTE_ID'],
            cliUUID: FFAppState().cliUUID,
            msgUUID: liberationHistoryItem['NOT_ID'],
            vawDestino: liberationHistoryItem['NOT_DESTINO'],
            vawUUID: liberationHistoryItem['NOT_ID'],
            vawName: liberationHistoryItem['NOT_NOME'],
            vawRef: liberationHistoryItem['NOT_ID'],
            labelsHashMap: Map<String, String>.from({
              'Nome:': liberationHistoryItem['VTE_NOME'],
              'Data:': liberationHistoryItem['NOT_DTENVIO'],
              'Motivo:': liberationHistoryItem['NOT_MOTIVO'],
              'Mensagem:': liberationHistoryItem['NOT_MSGENVIO'],
              // 'Resposta:': liberationHistoryItem['NOT_MSGRESPOSTA'],
            }),
            statusHashMap: [
              liberationHistoryItem['NOT_STATUS'] == 'L'
                  ? Map<String, Color>.from({
                      FFLocalizations.of(context).getVariableText(
                        ptText: 'Ativo',
                        enText: 'Active',
                      ): FlutterFlowTheme.of(context).success,
                    })
                  : liberationHistoryItem['NOT_STATUS'] == 'B'
                      ? Map<String, Color>.from({
                          FFLocalizations.of(context).getVariableText(
                            ptText: 'Bloqueado',
                            enText: 'Blocked',
                          ): FlutterFlowTheme.of(context).error,
                        })
                      : Map<String, Color>.from({
                          FFLocalizations.of(context).getVariableText(
                            ptText: 'Pendente',
                            enText: 'Pending',
                          ): FlutterFlowTheme.of(context).warning,
                        })
            ],
            imageHashMap: Map<String, String>.from({
              'key': liberationHistoryItem['VTE_ID'],
              'value': 'E',
            }),
            changeStatusAction: changeStatusAction,
            // vteDocument: liberationHistoryItem['VTE_DOCUMENTO'],
          );
        },
      ).then((_) {
        PushNotificationManager _pushNotificationService =
            PushNotificationManager();

        _pushNotificationService.onMessageReceived.listen((received) {
          if (received.data['click_action'] == 'cancel_request') {
            log('Aprovado');
            _pushNotificationService.dispose();
            snackbar(context, opt: true);
            context.pushReplacementNamed(
              'liberationHistory',
              extra: <String, dynamic>{
                kTransitionInfoKey: const TransitionInfo(
                  hasTransition: true,
                  transitionType: PageTransitionType.scale,
                  alignment: Alignment.bottomCenter,
                ),
              },
            );
          }
        });
      });
    },
  );
}
