// import 'dart:js_interop';

import 'dart:developer';

import 'package:hub/app_state.dart';
import 'package:hub/backend/api_requests/api_calls.dart';
import 'package:hub/backend/api_requests/api_manager.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:hub/pages/message_history_page/message_history_page_model.dart';

import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart';

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

  @override
  State<MessageHistoryPageWidget> createState() =>
      _MessageHistoryPageWidgetState();
}

class _MessageHistoryPageWidgetState extends State<MessageHistoryPageWidget>
    with TickerProviderStateMixin {
  late MessageHistoryPageModel _model;

  final scaffoldKey = GlobalKey<ScaffoldState>();

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

    _model.tabBarController = TabController(
      vsync: this,
      length: 3,
      initialIndex: 1,
    )..addListener(() => setState(() {}));

    _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 Scaffold(
      key: scaffoldKey,
      backgroundColor: FlutterFlowTheme.of(context).primaryBackground,
      appBar: appBarMessage(context),
      body: bodyMessage(context, _model),
    );
  }
}

PreferredSizeWidget appBarMessage(BuildContext context) {
  return AppBar(
    backgroundColor: FlutterFlowTheme.of(context).primaryBackground,
    automaticallyImplyLeading: false,
    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).getVariableText(
        enText: 'Message History',
        ptText: 'Histórico de Mensagens',
      ),
      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,
  );
}

Widget bodyMessage(BuildContext context, MessageHistoryPageModel _model) {
  return SafeArea(
    top: true,
    child: Column(
      mainAxisSize: MainAxisSize.max,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Align(
          alignment: const Alignment(0.0, 0),
          child: TabBar(
            labelColor: FlutterFlowTheme.of(context).primaryText,
            unselectedLabelColor: FlutterFlowTheme.of(context).primaryText,
            labelStyle: FlutterFlowTheme.of(context).titleMedium.override(
                  fontFamily: FlutterFlowTheme.of(context).titleMediumFamily,
                  fontSize: 13.0,
                  letterSpacing: 0.0,
                  useGoogleFonts: GoogleFonts.asMap().containsKey(
                      FlutterFlowTheme.of(context).titleMediumFamily),
                ),
            unselectedLabelStyle: const TextStyle(),
            indicatorColor: FlutterFlowTheme.of(context).primary,
            padding: const EdgeInsets.all(4.0),
            tabs: [
              Tab(
                text: FFLocalizations.of(context).getVariableText(
                  ptText: 'Pessoal',
                  enText: 'Personal',
                ),
              ),
              Tab(
                text: FFLocalizations.of(context).getVariableText(
                  enText: 'All',
                  ptText: 'Todos',
                ),
              ),
              Tab(
                text: FFLocalizations.of(context).getVariableText(
                  ptText: 'Global',
                  enText: 'Global',
                ),
              ),
            ],
            controller: _model.tabBarController,
            onTap: (i) async {
              [() async {}, () async {}][i]();
            },
          ),
        ),
        Expanded(
            child: TabBarView(controller: _model.tabBarController, children: [
          liberationDynamicListView(context, _model, 'P'),
          liberationDynamicListView(context, _model, 'A'),
          liberationDynamicListView(context, _model, 'T'),
        ])),
      ].addToStart(const SizedBox(height: 0)),
    ),
  );
}

Widget liberationDynamicListView(
    BuildContext context, MessageHistoryPageModel _model, String DestIndex) {
  return Container(
    width: double.infinity,
    height: double.infinity,
    decoration: const BoxDecoration(),
    child: FutureBuilder<dynamic>(
      future: Future(() async {
        try {
          var response = await PhpGroup.getMessagesCall.call(
            devUUID: FFAppState().devUUID.toString(),
            userUUID: FFAppState().userUUID.toString(),
            cliID: FFAppState().cliUUID.toString(),
            atividade: 'getMensagens',
            pageSize: '100',
            pageNumber: '1',
            tipoDestino: DestIndex,
          );
          return response.jsonBody;
        } catch (error) {
          log('Error: ${error.toString()}');
          return {'mensagens': [], 'total_rows': 0};
        }
      }),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Center(
            child: SizedBox(
              width: 50.0,
              height: 50.0,
              child: SpinKitCircle(
                color: FlutterFlowTheme.of(context).primary,
                size: 50.0,
              ),
            ),
          );
        }
        if (snapshot.hasError == true ||
            snapshot.data == null ||
            !snapshot.hasData ||
            snapshot.hasError) {
          log('Error: ${snapshot.error.toString()}');
          // log('Error: ${snapshot.data!.jsonBody['mensagens']}');
          return const Center(
            child: Text('Erro ao carregar mensagens'),
          );
        }
        final mensagens = snapshot.data!['mensagens'];
        final totalRows = snapshot.data!['total_rows'];
        if (totalRows == 0 || mensagens == null || mensagens.isEmpty) {
          return const Center(
            child: Text('Nenhuma mensagem encontrada'),
          );
        }
        return ListView.builder(
          itemCount: totalRows,
          addAutomaticKeepAlives: false,
          addRepaintBoundaries: true,
          cacheExtent: 1000.0,
          itemBuilder: (BuildContext context, int index) {
            return messageHistoryItem(
              context,
              snapshot.data!['mensagens'][index],
            );
          },
        );
      },
    ),
  );
}

Widget messageHistoryItem(BuildContext context, dynamic jsonBody) {
  log(jsonBody.toString());
  return Padding(
    padding: const EdgeInsets.symmetric(horizontal: 15),
    child: Card(
      color: FlutterFlowTheme.of(context).primaryBackground,
      child: Container(
        // height: 100,
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Column(
                    children: [
                      Icon(
                        jsonBody['MSG_DESTINO_TP'] == 'T'
                            ? Icons.group
                            : Icons.person,
                        color: FlutterFlowTheme.of(context).primary,
                        size: 25,
                      ),
                      Icon(
                        Icons.history,
                        color: FlutterFlowTheme.of(context).customColor6,
                        size: 15,
                      ),
                    ],
                  ),
                  Expanded(
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 15.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            jsonBody['MSG_ORIGEM_DESC'].toString(),
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 15,
                              color: FlutterFlowTheme.of(context).primary,
                            ),
                            overflow: TextOverflow.fade,
                          ),
                          SizedBox(height: 4),
                          Text(
                            jsonBody['MSG_DATE'].toString(),
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: 10,
                              color: FlutterFlowTheme.of(context).customColor6,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
              SizedBox(height: 8),
              Row(
                children: [
                  Expanded(
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Text(
                        jsonBody['MSG_TEXTO'].toString(),
                      ),
                    ),
                  ),
                ],
              ),
              SizedBox(height: 8),
            ],
          ),
        ),
      ),
    ),
  );
}
