import 'package:comunic/helpers/conversations_helper.dart';
import 'package:comunic/lists/users_list.dart';
import 'package:comunic/models/conversation.dart';
import 'package:comunic/ui/routes/conversation_route.dart';
import 'package:comunic/ui/tiles/simple_user_tile.dart';
import 'package:comunic/ui/widgets/pick_user_widget.dart';
import 'package:comunic/utils/intl_utils.dart';
import 'package:flutter/material.dart';

/// Create / Update conversation screen
///
/// @author Pierre HUBERT

enum _MembersMenuChoices { REMOVE }

class UpdateConversationScreen extends StatefulWidget {
  final Conversation initialSettings;
  final UsersList initialUsers;

  const UpdateConversationScreen({
    Key key,
    this.initialSettings,
    this.initialUsers,
  }) : super(key: key);

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

class _UpdateConversationScreen extends State<UpdateConversationScreen> {
  TextEditingController _nameController = TextEditingController();
  UsersList _members = UsersList();
  bool _followConversation = true;

  get isUpdating => widget.initialSettings != null;

  get isOwner => !isUpdating || widget.initialSettings.isOwner;

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

    // Check if we are updating an existing conversation
    if (widget.initialSettings != null) {
      _nameController.text = widget.initialSettings.name;
      _members = widget.initialUsers;
      _followConversation = widget.initialSettings.following;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(8.0),
      child: Column(
        children: <Widget>[
          // Conversation name
          TextField(
            controller: _nameController,
            decoration: InputDecoration(
              labelText: tr("Conversation name (optionnal)"),
              alignLabelWithHint: true,
              enabled: isOwner,
            ),
          ),

          // Add a member to the conversation
          PickUserWidget(
            resetOnChoose: true,
            keepFocusOnChoose: true,
            label: tr("Add member"),
            enabled: isOwner,
            onSelectUser: (user) => setState(() {
                  if (!_members.contains(user)) _members.add(user);
                }),
          ),

          //Conversation members
          Container(
            child: _members.length == 0
                ? null
                : Flexible(
                    child: ListView.builder(
                      itemCount: _members.length,
                      itemBuilder: (b, i) {
                        return SimpleUserTile(
                          user: _members[i],
                          trailing: isOwner
                              ? PopupMenuButton<_MembersMenuChoices>(
                                  onSelected: (choice) =>
                                      _membersMenuItemSelected(i, choice),
                                  itemBuilder: (c) =>
                                      <PopupMenuEntry<_MembersMenuChoices>>[
                                        PopupMenuItem(
                                          child: Text(tr("Remove")),
                                          value: _MembersMenuChoices.REMOVE,
                                        )
                                      ],
                                )
                              : null,
                        );
                      },
                    ),
                  ),
          ),

          // Follow conversation ?
          Row(
            children: <Widget>[
              Switch(
                value: _followConversation,
                onChanged: (b) => setState(() {
                      _followConversation = b;
                    }),
              ),
              Text(tr("Follow conversation"))
            ],
          ),

          // Submit button
          RaisedButton(
            onPressed: _members.length < 1 ? null : _submitForm,
            child: Text(isUpdating
                ? tr("Update the conversation")
                : tr("Create the conversation")),
          )
        ],
      ),
    );
  }

  /// An option of the members menu has been selected
  void _membersMenuItemSelected(int index, _MembersMenuChoices choice) {
    if (choice == null) return;

    if (choice == _MembersMenuChoices.REMOVE)
      return setState(() {
        _members.removeAt(index);
      });
  }

  /// Submit the conversation
  Future<void> _submitForm() async {
    final settings = Conversation(
        id: isUpdating ? widget.initialSettings.id : 0,
        ownerID: isUpdating ? widget.initialSettings.ownerID : 0,
        name: _nameController.text,
        following: _followConversation,
        members: _members.usersID,

        // Give random value to these fields as they are ignored here
        lastActive: 0,
        sawLastMessage: true);

    // Create the conversation
    var conversationID = settings.id;
    bool error = false;
    if (isUpdating)
      error = !(await ConversationsHelper().updateConversation(settings));
    else {
      conversationID = await ConversationsHelper().createConversation(settings);
      if (conversationID < 1) error = true;
    }

    // Check for errors
    if (error)
      return Scaffold.of(context).showSnackBar(SnackBar(
        content: Text(isUpdating
            ? tr("Could not update the conversation!")
            : tr("Could not create the conversation!")),
        duration: Duration(seconds: 1),
      ));

    // Open the conversation
    Navigator.of(context).pushReplacement(MaterialPageRoute(
        builder: (c) => ConversationRoute(
              conversationID: conversationID,
            )));
  }
}