import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:hub/features/backend/index.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:hub/shared/utils/dialog_util.dart';
import 'package:hub/shared/utils/limited_text_size.dart';
import 'package:hub/shared/utils/log_util.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>();

  late ScrollController _scrollController;

  int _pageNumber = 1;
  final int _pageSize = 10;
  bool _hasData = false;
  bool _loading = false;

  String _destinyType = "P";

  late Future<void> _messageFuture;
  List<dynamic> _messageWrap = [];

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

    _messageFuture = fetchMessage();

    _scrollController = ScrollController()
      ..addListener(() {
        if (_scrollController.position.atEdge &&
            _scrollController.position.pixels != 0) {
          _loadMore();
        }
      });

    _model.tabBarController =
        TabController(vsync: this, length: 3, initialIndex: 0)
          ..addListener(() {
            if (_model.tabBarController?.index == 0) {
              _destinyType = "P";
            } else if (_model.tabBarController?.index == 1) {
              _destinyType = "A";
            } else {
              _destinyType = "T";
            }

            _pageNumber = 1;
            _messageWrap = [];
            _messageFuture = fetchMessage();
          });

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

  @override
  void dispose() {
    _model.dispose();
    _scrollController.dispose();
    super.dispose();
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: scaffoldKey,
      backgroundColor: FlutterFlowTheme.of(context).primaryBackground,
      appBar: _appBar(context),
      body: _body(context),
    );
  }

  Future<ApiCallResponse?> fetchMessage() async {
    try {
      setState(() => _loading = true);

      var response = await PhpGroup.getMessagesCall.call(
        pageSize: _pageSize.toString(),
        pageNumber: _pageNumber.toString(),
        tipoDestino: _destinyType,
      );

      final List<dynamic> messages = response.jsonBody['mensagens'] ?? [];

      if (messages.isNotEmpty) {
        setState(() {
          _messageWrap.addAll(messages);
          _hasData = true;
          _loading = false;
        });

        return response;
      }

      _showNoMoreDataSnackBar(context);

      setState(() {
        _hasData = false;
        _loading = false;
      });
      return null;
    } catch (e, s) {
      await DialogUtil.errorDefault(context);
      LogUtil.requestAPIFailed(
          "proccessRequest.php", "", "Consulta de Mensagems", e, s);
      setState(() {
        _hasData = false;
        _loading = false;
      });
    }
    return null;
  }

  void _loadMore() {
    if (_hasData == true) {
      _pageNumber++;
      _messageFuture = fetchMessage();
    }
  }

  PreferredSizeWidget _appBar(BuildContext context) {
    return AppBar(
      backgroundColor: FlutterFlowTheme.of(context).primaryBackground,
      automaticallyImplyLeading: false,
      leading: FlutterFlowIconButton(
        key: ValueKey<String>('BackNavigationAppBar'),
        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: 'Consultar Mensagens',
        ),
        style: FlutterFlowTheme.of(context).headlineMedium.override(
              fontFamily: FlutterFlowTheme.of(context).headlineMediumFamily,
              color: FlutterFlowTheme.of(context).primaryText,
              fontSize: 16.0,
              fontWeight: FontWeight.bold,
              letterSpacing: 0.0,
              useGoogleFonts: GoogleFonts.asMap().containsKey(
                  FlutterFlowTheme.of(context).headlineMediumFamily),
            ),
      ),
      actions: const [],
      centerTitle: true,
    );
  }

  Widget _body(BuildContext context) {
    double limitedBodyFontSize = LimitedFontSizeUtil.getBodyFontSize(context);
    double limitedSubHeaderFontSize =
        LimitedFontSizeUtil.getSubHeaderFontSize(context);
    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: limitedBodyFontSize,
                    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,
            ),
          ),
          if (_hasData == false && _pageNumber <= 1 && _loading == false)
            Expanded(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.max,
                children: [
                  Center(
                    child: Text(
                        FFLocalizations.of(context).getVariableText(
                            ptText: "Nenhuma mensagem encontrada!",
                            enText: "No message found"),
                        style: TextStyle(
                          color: FlutterFlowTheme.of(context).primaryText,
                          fontSize: limitedSubHeaderFontSize,
                        )),
                  )
                ],
              ),
            )
          else if (_hasData == true || _pageNumber >= 1)
            Expanded(
              child: FutureBuilder<void>(
                future: _messageFuture,
                builder: (context, snapshot) {
                  return ListView.builder(
                      shrinkWrap: true,
                      physics: const BouncingScrollPhysics(),
                      controller: _scrollController,
                      itemCount: _messageWrap.length,
                      itemBuilder: (context, index) {
                        final item = _messageWrap[index];
                        return _item(context, item);
                      });
                },
              ),
            ),
          if (_hasData == true && _loading == true)
            Container(
              padding: const EdgeInsets.only(top: 15, bottom: 15),
              child: Center(
                child: CircularProgressIndicator(
                  valueColor: AlwaysStoppedAnimation<Color>(
                    FlutterFlowTheme.of(context).primary,
                  ),
                ),
              ),
            )
        ].addToStart(const SizedBox(height: 0)),
      ),
    );
  }

  void _showNoMoreDataSnackBar(BuildContext context) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(
          FFLocalizations.of(context).getVariableText(
              ptText: "Não há mais dados.", enText: "No more data."),
          style: TextStyle(
            color: Colors.white,
            fontSize: LimitedFontSizeUtil.getBodyFontSize(context),
          ),
        ),
        duration: const Duration(seconds: 3),
        backgroundColor: FlutterFlowTheme.of(context).primary,
      ),
    );
  }

  Widget _item(BuildContext context, dynamic jsonBody) {
    double limitedBodyFontSize = LimitedFontSizeUtil.getBodyFontSize(context);
    double limitedSubHeaderFontSize =
        LimitedFontSizeUtil.getSubHeaderFontSize(context);
    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: [
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 15.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          mainAxisSize: MainAxisSize.max,
                          children: [
                            Icon(
                              jsonBody['MSG_DESTINO_TP'] == 'T'
                                  ? Icons.language
                                  : jsonBody['MSG_DESTINO_TP'] == 'P'
                                      ? Icons.person
                                      : Icons.home,
                              color: FlutterFlowTheme.of(context).primary,
                              size: 25,
                            ),
                            Expanded(
                              child: Text(
                                jsonBody['MSG_ORIGEM_DESC'].toString(),
                                style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: limitedSubHeaderFontSize,
                                  color: FlutterFlowTheme.of(context).primary,
                                ),
                                overflow: TextOverflow.fade,
                              ),
                            ),
                          ].divide(const SizedBox(width: 10)),
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          mainAxisSize: MainAxisSize.max,
                          children: [
                            Padding(
                              padding: const EdgeInsets.only(left: 5),
                              child: Icon(
                                Icons.history,
                                color:
                                    FlutterFlowTheme.of(context).customColor6,
                                size: 15,
                              ),
                            ),
                            Expanded(
                              child: Text(
                                jsonBody['MSG_DATE'].toString(),
                                style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: limitedBodyFontSize,
                                  color:
                                      FlutterFlowTheme.of(context).customColor6,
                                ),
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                          ].divide(const SizedBox(width: 15)),
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          mainAxisSize: MainAxisSize.max,
                          children: [
                            Padding(
                              padding: const EdgeInsets.only(left: 5),
                              child: Icon(
                                Icons.message,
                                color:
                                    FlutterFlowTheme.of(context).customColor6,
                                size: 15,
                              ),
                            ),
                            Expanded(
                              child: Text(
                                jsonBody['MSG_TEXTO'].toString(),
                                style: TextStyle(
                                  fontSize: limitedBodyFontSize,
                                  color:
                                      FlutterFlowTheme.of(context).customColor6,
                                ),
                              ),
                            ),
                          ].divide(const SizedBox(width: 15)),
                        ),
                      ].divide(const SizedBox(height: 4)),
                    ),
                  ),
                ].divide(
                  const SizedBox(height: 8),
                ),
              ),
            ),
          ),
        ));
  }
}
