import 'package:Capsule/components/custom_title_bar.dart';
import 'package:Capsule/components/qr_reader.dart';
import 'package:Capsule/views/main/friend/add_search.dart';
import 'package:Capsule/views/main/friend/request_list_item.dart';
import 'package:flutter/material.dart';

import '/models/friends.dart';
import '/components/custom_expandable_fab.dart';
import '/views/main/friend/list_item.dart';

class FriendList extends StatefulWidget {
  final List<Friend> friends;
  final List<Friend> friendRequests;
  final Function callback;

  const FriendList({
    Key? key,
    required this.friends,
    required this.friendRequests,
    required this.callback,
  }) : super(key: key);

  @override
  State<FriendList> createState() => _FriendListState();
}

class _FriendListState extends State<FriendList> {
  List<Friend> friends = [];
  List<Friend> friendRequests = [];

  List<Friend> friendsDuplicate = [];
  List<Friend> friendRequestsDuplicate = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: const CustomTitleBar(
        title: Text(
          'Friends',
          style: TextStyle(
            fontSize: 32,
            fontWeight: FontWeight.bold
          )
        ),
        showBack: false,
        backgroundColor: Colors.transparent,
      ),
     body: Padding(
       padding: const EdgeInsets.only(top: 16,left: 16,right: 16),
       child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
             TextField(
               decoration: const InputDecoration(
                 hintText: 'Search...',
                 prefixIcon: Icon(
                   Icons.search,
                   size: 20
                 ),
               ),
               onChanged: (value) => filterSearchResults(value.toLowerCase())
             ),
             headingOrNull('Friend Requests'),
             friendRequestList(),
             headingOrNull('Friends'),
             friendList(),
          ],
        ),
      ),
     ),
      floatingActionButton: Padding(
        padding: const EdgeInsets.only(right: 10, bottom: 10),
        child: ExpandableFab(
          icon: const Icon(Icons.add, size: 30),
          distance: 90.0,
          children: [
            ActionButton(
              onPressed: () {
                Navigator.of(context).push(
                  MaterialPageRoute(builder: (context) => const QrReader())
                );//.then(onGoBack); // TODO
              },
              icon: const Icon(Icons.qr_code_2, size: 25),
            ),
            ActionButton(
              onPressed: () {
                Navigator.of(context).push(
                  MaterialPageRoute(builder: (context) => const FriendAddSearch())
                );//.then(onGoBack); // TODO
              },
              icon: const Icon(Icons.search, size: 25),
            ),
          ],
        )
      )
    );
  }

  void filterSearchResults(String query) {
    List<Friend> dummySearchList = [];
    dummySearchList.addAll(friends);

    if(query.isNotEmpty) {
      List<Friend> dummyListData = [];
      for (Friend item in dummySearchList) {
        if(item.username.toLowerCase().contains(query)) {
          dummyListData.add(item);
        }
      }
      setState(() {
        friends.clear();
        friends.addAll(dummyListData);
      });
      return;
    }

    setState(() {
      friends.clear();
      friends.addAll(friends);
    });
  }

  @override
  void initState() {
    super.initState();
    friends.addAll(widget.friends);
    friendRequests.addAll(widget.friendRequests);
  }

  Future<void> initFriends() async {
    friends = await getFriends(accepted: true);
    friendRequests = await getFriends(accepted: false);
    setState(() {});
    widget.callback();
  }

  Widget headingOrNull(String heading) {
    if (friends.isEmpty || friendRequests.isEmpty) {
      return const SizedBox.shrink();
    }

    return Padding(
      padding: const EdgeInsets.only(top: 16),
      child: Align(
        alignment: Alignment.centerLeft,
        child: Text(
          heading,
          style: TextStyle(
            fontSize: 16,
            color: Theme.of(context).colorScheme.tertiary,
          ),
        ),
      )
    );
  }

  Widget friendRequestList() {
    if (friendRequests.isEmpty) {
      return const SizedBox.shrink();
    }

    return ListView.builder(
      itemCount: friendRequests.length,
      shrinkWrap: true,
      padding: const EdgeInsets.only(top: 16),
      physics: const NeverScrollableScrollPhysics(),
      itemBuilder: (context, i) {
        return FriendRequestListItem(
          friend: friendRequests[i],
          callback: initFriends,
        );
      },
    );
  }

  Widget friendList() {
    if (friends.isEmpty) {
      return const Center(
        child: Text('No Friends'),
      );
    }

    return ListView.builder(
      itemCount: friends.length,
      shrinkWrap: true,
      padding: const EdgeInsets.only(top: 16),
      physics: const NeverScrollableScrollPhysics(),
      itemBuilder: (context, i) {
        return FriendListItem(
          friend: friends[i],
        );
      },
    );
  }
}
