import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:hub/components/templates_components/card_item_template_component/card_item_template_component_widget.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/pages/residents_on_the_property/residents_on_the_property_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 ResidentsOnTheProperty extends StatefulWidget {
  const ResidentsOnTheProperty({super.key});

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

class _ResidentsOnThePropertyState extends State<ResidentsOnTheProperty>
    with TickerProviderStateMixin {
  late ScrollController _scrollController;

  int _pageNumber = 1;
  bool _hasData = false;
  bool _loading = false;
  int count = 0;

  late final ResidentsOnThePropertyModel model;

  late Future<void> _future;
  List<dynamic> _wrap = [];

  @override
  void initState() {
    super.initState();
    model = createModel(
        context,
        () =>
            ResidentsOnThePropertyModel(onRefresh: () => safeSetState(() {})));
    _future = _fetch();

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

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

  @override
  Widget build(BuildContext context) {
    late final limitedHeaderTextSize =
        LimitedFontSizeUtil.getHeaderFontSize(context);

    return Scaffold(
      appBar: _appBar(context),
      backgroundColor: FlutterFlowTheme.of(context).primaryBackground,
      body: Column(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          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: "Nenhum morador encontrado!",
                        enText: "No residents found!",
                      ),
                      style: TextStyle(
                        fontFamily: 'Nunito',
                        fontSize: limitedHeaderTextSize,
                      ),
                    ),
                  )
                ],
              ),
            )
          else if (_hasData == true || _pageNumber >= 1)
            Expanded(
                child: FutureBuilder<void>(
              future: _future,
              builder: (context, snapshot) {
                return ListView.builder(
                    shrinkWrap: true,
                    physics: const BouncingScrollPhysics(),
                    controller: _scrollController,
                    itemCount: _wrap.length + 1,
                    itemBuilder: (context, index) {
                      if (index == 0) {
                        // Add your item here
                        return Padding(
                          padding: const EdgeInsets.only(right: 30, top: 10),
                          child: Text(
                            '',
                            textAlign: TextAlign.right,
                          ),
                        );
                      } else {
                        final item = _wrap[index - 1];
                        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)),
      ),
    );
  }

  PreferredSizeWidget _appBar(BuildContext context) {
    return AppBar(
      backgroundColor: FlutterFlowTheme.of(context).primaryBackground,
      automaticallyImplyLeading: false,
      title: Text(
        FFLocalizations.of(context)
            .getVariableText(ptText: 'Moradores', enText: 'Residents'),
        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),
            ),
      ),
      leading: _backButton(context, FlutterFlowTheme.of(context)),
      centerTitle: true,
      elevation: 0.0,
      actions: [],
    );
  }

  Widget _backButton(BuildContext context, FlutterFlowTheme theme) {
    return FlutterFlowIconButton(
      key: ValueKey<String>('BackNavigationAppBar'),
      borderColor: Colors.transparent,
      borderRadius: 30.0,
      borderWidth: 1.0,
      buttonSize: 60.0,
      icon: Icon(
        Icons.keyboard_arrow_left,
        color: theme.primaryText,
        size: 30.0,
      ),
      onPressed: () => Navigator.of(context).pop(),
    );
  }

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

      var response =
          await PhpGroup.getResidentsByProperty.call(_pageNumber.toString());

      final List<dynamic> residents = response.jsonBody['residents'] ?? [];
      safeSetState(() => count = response.jsonBody['total_rows'] ?? 0);

      if (residents.isNotEmpty) {
        setState(() {
          _wrap.addAll(residents);
          _hasData = true;
          _loading = false;
        });

        return response;
      }

      _showNoMoreDataSnackBar(context);

      setState(() {
        _hasData = false;
        _loading = false;
      });

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

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

      _future = _fetch();
    }
  }

  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 uItem) {
    return CardItemTemplateComponentWidget(
      imagePath:
          'https://freaccess.com.br/freaccess/getImage.php?devUUID=${model.devUUID}&cliID=${model.cliUUID}&atividade=getFoto&Documento=${uItem['documento']}&tipo=Z',
      labelsHashMap: {
        '${FFLocalizations.of(context).getVariableText(ptText: "Nome", enText: "Name")}:':
            uItem['nome'] ?? '',
        //statusweb
        '${FFLocalizations.of(context).getVariableText(ptText: "Possui App", enText: "Has App")}:':
            uItem['statusweb'] == "A"
                ? FFLocalizations.of(context).getVariableText(
                    ptText: 'Sim',
                    enText: 'Yes',
                  )
                : FFLocalizations.of(context).getVariableText(
                    ptText: 'Não',
                    enText: 'No',
                  ),
      },
      statusHashMap: [],
      onTapCardItemAction: () async {},
    );
  }
}
