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/features/storage/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/pets_page/pets_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 PetsHistoryScreen extends StatefulWidget {
  const PetsHistoryScreen({super.key, this.model, required this.isApp});
  final bool isApp;
  final PetsPageModel? model;

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

class _PetsHistoryScreenState extends State<PetsHistoryScreen>
    with TickerProviderStateMixin {
  late ScrollController _scrollController;

  int _pageNumber = 1;
  final int _pageSize = 10;
  bool _hasData = false;
  bool _loading = false;
  int count = 0;
  late final PetsPageModel model;
  late Future<void> _petsFuture;
  List<dynamic> _petsWrap = [];

  @override
  void initState() {
    super.initState();
    model = widget.model ??
        createModel(context, () => PetsPageModel(isInteractive: false));
    _petsFuture = _fetch();
    _scrollController = ScrollController()
      ..addListener(() {
        if (_scrollController.position.atEdge &&
            _scrollController.position.pixels != 0) {
          _loadMore();
        }
      });
  }

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

  PreferredSizeWidget _appBar(BuildContext context) {
    return AppBar(
      backgroundColor: FlutterFlowTheme.of(context).primaryBackground,
      automaticallyImplyLeading: false,
      title: Text(
        FFLocalizations.of(context).getVariableText(
          ptText: 'Pets',
          enText: 'Pets',
        ),
        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.getPets.call(
        pageSize: _pageSize,
        page: _pageNumber,
      );

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

      if (pets.isNotEmpty) {
        setState(() {
          _petsWrap.addAll(pets);
          _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 Pets", e, s);
      setState(() {
        _hasData = false;
        _loading = false;
      });
    }
    return null;
  }

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

      _petsFuture = _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,
      ),
    );
  }

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

    return Scaffold(
      appBar: widget.isApp ? _appBar(context) : null,
      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 Pet encontrado!",
                            enText: "No pets found"),
                        style: TextStyle(
                          fontFamily: 'Nunito',
                          fontSize: limitedHeaderTextSize,
                        )),
                  )
                ],
              ),
            )
          else if (_hasData == true || _pageNumber >= 1)
            Expanded(
                child: FutureBuilder<void>(
              future: _petsFuture,
              builder: (context, snapshot) {
                return ListView.builder(
                    shrinkWrap: true,
                    physics: const BouncingScrollPhysics(),
                    controller: _scrollController,
                    itemCount: _petsWrap.length + 1,
                    itemBuilder: (context, index) {
                      if (index == 0) {
                        // Add your item here
                        return Padding(
                          padding: const EdgeInsets.only(right: 30, top: 10),
                          child: Text(
                            model.petAmountRegister == '0'
                                ? FFLocalizations.of(context).getVariableText(
                                    ptText: "Ilimitado", enText: "Unlimited")
                                : "${FFLocalizations.of(context).getVariableText(ptText: "Quantidade de Pets: ", enText: "Amount of Pets: ")}$count/${model.petAmountRegister}",
                            textAlign: TextAlign.right,
                            style: TextStyle(
                              fontFamily: 'Nunito',
                              fontSize: limitedBodyTextSize,
                            ),
                          ),
                        );
                      } else {
                        final item = _petsWrap[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)),
      ),
    );
  }

  Widget _item(BuildContext context, dynamic uItem) {
    return CardItemTemplateComponentWidget(
      imagePath:
          'https://freaccess.com.br/freaccess/getImage.php?devUUID=${model.devUUID}&userUUID=${model.userUUID}&cliID=${model.cliUUID}&atividade=consultaFotoPet&petId=${uItem['id'] ?? ''}',
      labelsHashMap: {
        '${FFLocalizations.of(context).getVariableText(ptText: "Nome", enText: "Name")}:':
            uItem['name'] ?? '',
        '${FFLocalizations.of(context).getVariableText(ptText: "Espécie", enText: "Species")}:':
            uItem['species'] ?? '',
        '${FFLocalizations.of(context).getVariableText(ptText: "Raça", enText: "Breed")}:':
            uItem['breed'] ?? '',
      },
      statusHashMap: [
        if (uItem['size'] == "MIN")
          {
            FFLocalizations.of(context).getVariableText(
              ptText: 'Mini',
              enText: 'Mini',
            ): FlutterFlowTheme.of(context).accent4,
          },
        if (uItem['size'] == "PEQ")
          {
            FFLocalizations.of(context).getVariableText(
              ptText: 'Pequeno',
              enText: 'Small',
            ): FlutterFlowTheme.of(context).accent4,
          },
        if (uItem['size'] == "MED")
          {
            FFLocalizations.of(context).getVariableText(
              ptText: 'Medio',
              enText: 'Medium',
            ): FlutterFlowTheme.of(context).accent4,
          },
        if (uItem['size'] == "GRA")
          {
            FFLocalizations.of(context).getVariableText(
              ptText: 'Grande',
              enText: 'Big',
            ): FlutterFlowTheme.of(context).accent4,
          },
        if (uItem['size'] == "GIG")
          {
            FFLocalizations.of(context).getVariableText(
              ptText: 'Gigante',
              enText: 'Giant',
            ): FlutterFlowTheme.of(context).accent4,
          },
        if (uItem['gender'] == "MAC")
          {
            FFLocalizations.of(context).getVariableText(
                ptText: 'Macho', enText: 'Male'): const Color(0xFF094CB0),
          },
        if (uItem['gender'] == "FEM")
          {
            FFLocalizations.of(context).getVariableText(
              ptText: 'Femêa',
              enText: 'Female',
            ): const Color(0xFFE463E7),
          }
      ],
      onTapCardItemAction: () async {
        final devUUID =
            (await StorageHelper().get(ProfileStorageKey.devUUID.key)) ?? '';
        final userUUID =
            (await StorageHelper().get(ProfileStorageKey.userUUID.key)) ?? '';
        final cliUUID =
            (await StorageHelper().get(ProfileStorageKey.clientUUID.key)) ?? '';
        final cliName =
            (await StorageHelper().get(ProfileStorageKey.clientName.key)) ?? '';
        await showDialog(
          useSafeArea: true,
          context: context,
          builder: (context) {
            return Dialog(
              alignment: Alignment.center,
              child: model.buildPetDetails(
                item: uItem,
                context: context,
                devUUID: devUUID,
                userUUID: userUUID,
                cliUUID: cliUUID,
                cliName: cliName,
                model: model,
              ),
            );
          },
        ).whenComplete(() {
          safeSetState(() {
            _pageNumber = 1;
            _petsWrap = [];
            _petsFuture =
                _fetch().then((value) => value!.jsonBody['pets'] ?? []);
          });
        }).catchError((e, s) async {
          await DialogUtil.errorDefault(context);
          LogUtil.requestAPIFailed(
              "proccessRequest.php", "", "Consulta de Pets", e, s);
          safeSetState(() {
            _hasData = false;
            _loading = false;
          });
        });
      },
    );
  }
}
