import 'package:azlistview/azlistview.dart';
import 'package:flutter/material.dart';
import 'package:lpinyin/lpinyin.dart';
import 'package:prime_chat/screens/ProfileScreen.dart';
import '../basic/Common.dart';

import '../basic/Entities.dart';
import '../basic/Method.dart';
import 'NewFriendScreen.dart';
import 'components/Avatar.dart';

// 好友列表页面
class ContactsScreen extends StatefulWidget {
  const ContactsScreen({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _ContactsScreenState();
}

class _ContactsScreenState extends State<ContactsScreen> {

  List<FriendInfo> _friends = [];
  double susItemHeight = 40;

  @override
  void initState() {
    super.initState();
    _loadFriends();
  }

  void _loadFriends() {
    method.getFriends().then((value) {
      _friends = [];
      if (value != null) {
        for (var e in value) {
          _friends.add(FriendInfo(profile: e));
        }
      }
      _handleList(_friends);
    });
  }

  void _handleList(List<FriendInfo> list) {
    for (int i = 0, length = list.length; i < length; i++) {
      String pinyin = PinyinHelper.getPinyinE(list[i].name);
      String tag = pinyin.substring(0, 1).toUpperCase();
      // list[i].namePinyin = pinyin;
      if (RegExp("[A-Z]").hasMatch(tag)) {
        list[i].tagIndex = tag;
      } else {
        list[i].tagIndex = "#";
      }
    }
    // A-Z sort.
    SuspensionUtil.sortListBySuspensionTag(_friends);

    // show sus tag.
    SuspensionUtil.setShowSuspensionStatus(_friends);

    // add header.
    _friends.insert(0, FriendInfo(profile: const Profile(name: "header"), tagIndex: '↑'));

    setState(() {});
  }

  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.all(20),
      alignment: Alignment.center,
      child: Column(
        // mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[

          ListTile(
            leading: ClipRRect(
              borderRadius: BorderRadius.circular(10.0),
              child: Container(
                color: Colors.orange,
                height: 40.0,
                width: 40.0,
                child: const Icon(Icons.person_add, color: Colors.white, size: 30.0,),
              ),
            ),
            title: const Text("新的好友"),
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => const NewFriendScreen()),
              );
            },
          )
        ],
      ),
    );
  }

  Widget _buildSusWidget(String susTag) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 15.0),
      height: susItemHeight,
      width: double.infinity,
      alignment: Alignment.centerLeft,
      child: Row(
        children: <Widget>[
          Text(
            susTag,
            textScaleFactor: 1.2,
          ),
          const Expanded(
              child: Divider(
                height: .0,
                indent: 10.0,
              ))
        ],
      ),
    );
  }

  Widget _buildListItem(FriendInfo model) {
    String susTag = model.getSuspensionTag();
    return Column(
      children: <Widget>[
        Offstage(
          offstage: model.isShowSuspension != true,
          child: _buildSusWidget(susTag),
        ),
        ListTile(
          leading: Avatar(model.profile.avatar),
          title: Text(model.name),
          onTap: () {
            Navigator.push(
                context, MaterialPageRoute(
                builder: (context) => ProfileScreen(
                    profile: model.profile, isFriend: true)));
          },
        )
      ],
    );
  }

  Decoration getIndexBarDecoration(Color color) {
    return BoxDecoration(
        color: color,
        borderRadius: BorderRadius.circular(20.0),
        border: Border.all(color: Colors.grey[300]!, width: .5));
  }

  Widget _buildList(BuildContext context) {
    return AzListView(
      data: _friends,
      itemCount: _friends.length,
      itemBuilder: (BuildContext context, int index) {
        if (index == 0) return _buildHeader();
        final model = _friends[index];
        return _buildListItem(model);
      },
      physics: const BouncingScrollPhysics(),
      indexBarData: SuspensionUtil.getTagIndexList(_friends),
      indexHintBuilder: (context, hint) {
        return Container(
          alignment: Alignment.center,
          width: 60.0,
          height: 60.0,
          decoration: BoxDecoration(
            color: Colors.blue[700]!.withAlpha(200),
            shape: BoxShape.circle,
          ),
          child:
          Text(hint, style: const TextStyle(color: Colors.white, fontSize: 30.0)),
        );
      },
      indexBarMargin: const EdgeInsets.all(10),
      indexBarOptions: IndexBarOptions(
        needRebuild: true,
        decoration: getIndexBarDecoration(Colors.grey[50]!),
        downDecoration: getIndexBarDecoration(Colors.grey[200]!),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('好友'),
        actions: [
          IconButton(
            onPressed: () async {
              // Navigator.push(
              //   context,
              //   MaterialPageRoute(builder: (context) => const AddFriendScreen()),
              // );
            },
            icon: const Icon(Icons.add),
          ),
        ],
      ),
      body: RefreshIndicator(
        onRefresh: () async {
          _loadFriends();
        },
        child: _buildList(context),
      ),
    );
  }
}
