import 'dart:convert';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:mohem_flutter_app/api/pending_transactions_api_client.dart';
import 'package:mohem_flutter_app/app_state/app_state.dart';
import 'package:mohem_flutter_app/classes/colors.dart';
import 'package:mohem_flutter_app/classes/utils.dart';
import 'package:mohem_flutter_app/config/routes.dart';
import 'package:mohem_flutter_app/extensions/int_extensions.dart';
import 'package:mohem_flutter_app/extensions/string_extensions.dart';
import 'package:mohem_flutter_app/extensions/widget_extensions.dart';
import 'package:mohem_flutter_app/generated/locale_keys.g.dart';
import 'package:mohem_flutter_app/models/get_announcements.dart';
import 'package:mohem_flutter_app/widgets/app_bar_widget.dart';
import 'package:mohem_flutter_app/widgets/dynamic_forms/dynamic_textfield_widget.dart';

class Announcements extends StatefulWidget {
  const Announcements({Key? key}) : super(key: key);

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

class _AnnouncementsState extends State<Announcements> {
  String jsonResponse = "";
  int currentPageNo = 1;
  int currentOpenIndex = -1;

  List<GetAnnouncementsObject> getAnnouncementsObject = [];
  List<GetAnnouncementsObject> _foundAnnouncements = [];
  TextEditingController searchController = TextEditingController();

  @override
  void initState() {
    getAnnouncements(0, 0);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBarWidget(
        context,
        title: LocaleKeys.announcements.tr(),
      ),
      body: jsonResponse.isEmpty
          ? const SizedBox()
          : getAnnouncementsObject.isNotEmpty
              ? Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    DynamicTextFieldWidget(
                      LocaleKeys.search.tr(),
                      LocaleKeys.searchAnnouncements.tr(),
                      isEnable: true,
                      suffixIconData: Icons.search,
                      isPopup: false,
                      lines: 1,
                      isInputTypeNum: false,
                      isReadOnly: false,
                      onChange: (String value) {
                        _runFilter(value);
                      },
                    ).paddingOnly(left: 21, right: 21),
                    ListView.separated(
                      physics: const BouncingScrollPhysics(),
                      shrinkWrap: true,
                      padding: EdgeInsets.all(21),
                      itemBuilder: (BuildContext context, int index) {
                        return InkWell(
                          onTap: () {
                            openAnnouncementsDetails(int.parse(_foundAnnouncements[index].rowID!));
                          },
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              SizedBox(
                                width: 80.0,
                                child: AspectRatio(
                                  aspectRatio: 1 / 1,
                                  child: ClipRRect(
                                    borderRadius: BorderRadius.circular(10),
                                    child: Image.memory(
                                      base64Decode(Utils.getBase64FromJpeg(_foundAnnouncements[index].bannerImage)),
                                      fit: BoxFit.cover,
                                    ),
                                  ),
                                ),
                              ),
                              12.width,
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  (AppState().isArabic(context) ? _foundAnnouncements[index].titleAR! : _foundAnnouncements[index].titleEN!).toText13(),
                                  8.height,
                                  _foundAnnouncements[index].created!.toText10(color: MyColors.grey98Color)
                                ],
                              ).expanded,
                            ],
                          ).objectContainerView(),
                        );
                      },
                      separatorBuilder: (BuildContext context, int index) => 12.height,
                      itemCount: _foundAnnouncements.length,
                    ).expanded
                  ],
                )
              : Utils.getNoDataWidget(context),
    );
  }

  void _runFilter(String enteredKeyword) {
    List<GetAnnouncementsObject> results = [];
    if (enteredKeyword.isEmpty) {
      results = getAnnouncementsObject;
    } else {
      results = getAnnouncementsObject.where((user) => user.titleEN!.toLowerCase().contains(enteredKeyword.toLowerCase())).toList();
    }
    setState(() {
      _foundAnnouncements = results;
    });
  }

  void getAnnouncements(int itgAwarenessID, int itgRowID) async {
    try {
      Utils.showLoading(context);
      jsonResponse = await PendingTransactionsApiClient().getAnnouncements(itgAwarenessID, currentPageNo, itgRowID);
      var jsonDecodedData = jsonDecode(jsonDecode(jsonResponse)['result']['data']);
      for (int i = 0; i < jsonDecodedData.length; i++) {
        getAnnouncementsObject.add(GetAnnouncementsObject.fromJson(jsonDecodedData[i]));
      }
      _foundAnnouncements = getAnnouncementsObject;
      Utils.hideLoading(context);
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void openAnnouncementsDetails(int rowID) async {
    await Navigator.pushNamed(context, AppRoutes.announcementsDetails, arguments: {"currentPageNo": currentPageNo, "rowID": rowID});
  }
}
