import 'package:Capsule/components/custom_circle_avatar.dart';
import 'package:Capsule/models/conversations.dart';
import 'package:Capsule/models/friends.dart';
import 'package:Capsule/utils/storage/conversations.dart';
import 'package:Capsule/utils/strings.dart';
import 'package:Capsule/views/main/conversation/detail.dart';
import 'package:flutter/material.dart';

class FriendListItem extends StatefulWidget{
  final Friend friend;
  const FriendListItem({
    Key? key,
    required this.friend,
  }) : super(key: key);

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

class _FriendListItemState extends State<FriendListItem> {

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () { findOrCreateConversation(context); },
      child: Container(
        padding: const EdgeInsets.only(left: 16,right: 16,top: 0,bottom: 20),
        child: Row(
          children: <Widget>[
            Expanded(
              child: Row(
                children: <Widget>[
                  CustomCircleAvatar(
                    initials: widget.friend.username[0].toUpperCase(),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: Container(
                        color: Colors.transparent,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text(widget.friend.username, style: const TextStyle(fontSize: 16)),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
             ),
           ),
         ],
        ),
      ),
    );
  }

  Future<void> findOrCreateConversation(BuildContext context) async {
    Conversation? conversation = await getTwoUserConversation(widget.friend.friendId);

    conversation ??= await createConversation(
      generateRandomString(32),
      [ widget.friend ],
      true,
    );

    uploadConversation(conversation, context);

    Navigator.push(context, MaterialPageRoute(builder: (context){
      return ConversationDetail(
        conversation: conversation!,
      );
    }));
  }
}
