import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:tangheem/api/tangheem_user_api_client.dart';
import 'package:tangheem/app_state/app_state.dart';
import 'package:tangheem/classes/colors.dart';
import 'package:tangheem/classes/utils.dart';
import 'package:tangheem/extensions/int_extensions.dart';
import 'package:tangheem/extensions/string_extensions.dart';
import 'package:tangheem/extensions/widget_extensions.dart';
import 'package:tangheem/models/member_model.dart';
import 'package:tangheem/ui/misc/no_data_ui.dart';
import 'package:tangheem/widgets/new/CommonHeader.dart';

class MemberScreen extends StatefulWidget {
  static const String routeName = "/members";

  MemberScreen({Key key}) : super(key: key);

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

class _MemberScreenState extends State<MemberScreen> {
  List<MemberDataModel> membersList;

  @override
  void initState() {
    super.initState();
    membersList = AppState().membersList;
    getMembers();
  }

  void getMembers() async {
    if (membersList == null) {
      Utils.showLoading(context);
      try {
        var membersData = await TangheemUserApiClient().getMembers();
        membersList = membersData?.data ?? [];
        membersList.sort((a, b) => a.orderNo.compareTo(b.orderNo));
        AppState().membersList = membersList;
      } catch (ex) {
        membersList = [];
        if (mounted) Utils.handleException(ex, null);
      } finally {
        Utils.hideLoading(context);
      }
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    bool isPortrait = MediaQuery.of(context).orientation == Orientation.portrait;

    Widget _header = SizedBox(height: isPortrait ? null : double.infinity, width: double.infinity, child: CommonHeader("اللجنة الإشرافية", "assets/icons/new/commette_bg.jpg", Color(0xff416A6C)));
    Widget _dataListView = membersList?.isEmpty ?? true
        ? NoDataUI()
        : ListView.separated(
            physics: const NeverScrollableScrollPhysics(),
            shrinkWrap: true,
            itemCount: membersList.length,
            padding: EdgeInsets.only(left: 25, right: 25, top: isPortrait ? 25 : 50, bottom: isPortrait ? 125 : 25),
            separatorBuilder: (context, index) {
              return Divider(color: Color(0xffC7C7C7), height: 1, thickness: 1);
            },
            itemBuilder: (context, index) {
              String encodedImage = membersList.elementAt(index).picture;
              if (encodedImage.contains("data:image/png;base64,")) {
                encodedImage = encodedImage.replaceAll("data:image/png;base64,", "");
              }
              if (encodedImage.contains("data:image/jpeg;base64,")) {
                encodedImage = encodedImage.replaceAll("data:image/jpeg;base64,", "");
              }
              var temp = base64Decode(encodedImage);

              return Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      (membersList[index].firstName + " " + membersList[index].lastName).toText(13, color: ColorConsts.darkText, textAlign: TextAlign.end),
                      membersList[index].description.trim().toText(13, color: ColorConsts.grey9FColor, textAlign: TextAlign.end),
                    ],
                  ).expanded,
                  21.width,
                  Container(
                    width: 82.0,
                    height: 82.0,
                    decoration: BoxDecoration(
                      image: membersList.length < 1
                          ? null
                          : DecorationImage(
                              fit: BoxFit.cover,
                              image: MemoryImage(temp),
                            ),
                      borderRadius: BorderRadius.all(
                        Radius.circular(10.0),
                      ),
                    ),
                    child: membersList.length < 1
                        ? ClipRRect(
                            borderRadius: BorderRadius.all(
                              Radius.circular(10.0),
                            ),
                            child: SvgPicture.asset(
                              "assets/icons/chat_user.svg",
                              clipBehavior: Clip.antiAlias,
                            ),
                          )
                        : null,
                  ),
                ],
              ).paddingOnly(top: 25, bottom: 25);
            },
          );
    return SizedBox(
      height: double.infinity,
      child: isPortrait
          ? SingleChildScrollView(
              physics: const AlwaysScrollableScrollPhysics(),
              child: Column(
                children: [_header, membersList == null ? SizedBox() : _dataListView],
              ),
            )
          : Row(
              children: [
                Expanded(child: SingleChildScrollView(physics: const BouncingScrollPhysics(), child: _dataListView), flex: 6),
                Expanded(child: _header, flex: 4),
              ],
            ),
    );
  }
}
