package com.project.ilsaenterprise;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.project.ilsaenterprise.adapter.MessageGroupListAdapter;
import com.project.ilsaenterprise.models.GroupMessageModel;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

public class GroupChatActivity extends AppCompatActivity {
    private RelativeLayout sendMessageBtn;
    private EditText userMessage;
    private ScrollView mScrollView;
    private TextView displayTextChat;
    private RecyclerView mMessageRecycler;
    private MessageGroupListAdapter mMessageAdapter;
    private List<GroupMessageModel> messageList;

    //private FirebaseAuth mAuth;
    private TextView groupNameSupportBar;
    private DatabaseReference userRef, GroupNameRef, GroupKeyRef;
    private String currentGroupName, currentUID, currentUsername, currentDate, currentTime, senderID;
    private String imageUrl;
    private GoogleSignInAccount googleLogin;
    private FirebaseAuth mAuth;
    private FirebaseUser userFirebase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_chat);
        getSupportActionBar().hide();

        googleLogin = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
        mAuth = FirebaseAuth.getInstance();
        userFirebase = mAuth.getCurrentUser();

        groupNameSupportBar = findViewById(R.id.groupName);
        currentGroupName = getIntent().getExtras().get("groupName").toString();
        groupNameSupportBar.setText(currentGroupName);
        messageList = new ArrayList<>();

        sendMessageBtn = findViewById(R.id.relSend);
        userMessage = findViewById(R.id.groupMessages);
        currentUID = userFirebase.getUid();
        userRef = FirebaseDatabase.getInstance().getReference().child("users");
        GroupNameRef = FirebaseDatabase.getInstance().getReference().child("Chats").child(currentGroupName);
        mMessageRecycler = (RecyclerView) findViewById(R.id.recyclerView_message_list);
//        mMessageRecycler.setNestedScrollingEnabled(false);

        getUserInfo();
        loadMessage();

        sendMessageBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SaveMessageInfo();
                userMessage.setText("");
                mMessageRecycler.post(new Runnable() {
                    @Override
                    public void run() {
                        // Call smooth scroll
                        mMessageRecycler.scrollToPosition(mMessageAdapter.getItemCount() - 1);
                    }
                });
            }
        });
    }

    private void loadMessage() {

        GroupNameRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                messageList.clear();
                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                    GroupMessageModel modelPost = ds.getValue(GroupMessageModel.class);
                    messageList.add(modelPost);
                }
                mMessageAdapter = new MessageGroupListAdapter(getApplicationContext(), messageList, currentUID);
                mMessageRecycler.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
                mMessageRecycler.setAdapter(mMessageAdapter);

                mMessageRecycler.post(new Runnable() {
                    @Override
                    public void run() {
                        // Call smooth scroll
                        mMessageRecycler.scrollToPosition(mMessageAdapter.getItemCount() - 1);
                    }
                });
//                progressBar.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(GroupChatActivity.this, "Data Error" + databaseError.getMessage(), Toast.LENGTH_LONG).show();
            }
        });


    }

    private void SaveMessageInfo() {
        String Message = userMessage.getText().toString();

        if(TextUtils.isEmpty(Message)){
            Toast.makeText(this, "Masukkan pesan anda", Toast.LENGTH_SHORT).show();
        }
        else {
            Calendar calDate = Calendar.getInstance();
            @SuppressLint("SimpleDateFormat") SimpleDateFormat currentDateFormat = new SimpleDateFormat("dd MMM, yyyy");
            currentDate = currentDateFormat.format(calDate.getTime());
            String timeStamp = String.valueOf(System.currentTimeMillis());
            Calendar calTime = Calendar.getInstance();
            @SuppressLint("SimpleDateFormat") SimpleDateFormat currentTimeFormat = new SimpleDateFormat("kk:mm");
            currentTime = currentTimeFormat.format(calTime.getTime());

            HashMap<String, Object> groupMessageKey = new HashMap<>();
            GroupNameRef.updateChildren(groupMessageKey);

            GroupKeyRef = GroupNameRef.child(timeStamp);
            HashMap<String, Object> messageInfoMap = new HashMap<>();
            messageInfoMap.put("senderID", currentUID);
            messageInfoMap.put("name", currentUsername);
            messageInfoMap.put("message", Message);
            messageInfoMap.put("date", currentDate);
            messageInfoMap.put("time", currentTime);
            GroupKeyRef.updateChildren(messageInfoMap);

        }
    }

    private void getUserInfo(){
        userRef.child(currentUID).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if(snapshot.exists())
                {
                    currentUsername = snapshot.child("namaLengkap").getValue().toString();
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
    }

}