package com.ttiglobal.inttilectgpchat.blog;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.FirebaseFirestore;
import com.ttiglobal.inttilectgpchat.R;
import com.ttiglobal.inttilectgpchat.blog.Helper.CommentRecyclerAdapter;
import com.ttiglobal.inttilectgpchat.blog.Modal.Comment;
import com.ttiglobal.inttilectgpchat.util.GlobalData;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class CommentActivity extends AppCompatActivity {

    ImageView send_comment;
    EditText comment_input;
    TextView txtName;
    RelativeLayout error;
    RecyclerView comment_list;
    CommentRecyclerAdapter adapter;
    String ref_id, file_url;
    private FirebaseAuth mAuth;
    ArrayList<HashMap<String, String>> childHashMap = new ArrayList<>();

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

        txtName = findViewById(R.id.txtName);

        setupWindowAnimations();
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setContentInsetStartWithNavigation(0);

        txtName.setText("COMMENT");
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("");
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
//        setSupportActionBar(toolbar);
//        toolbar.setTitle("");
//        Objects.requireNonNull(getSupportActionBar()).setTitle("");
//        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//        getSupportActionBar().setDisplayShowHomeEnabled(true);
        @SuppressLint("PrivateResource")
        Drawable backArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_material);
        backArrow.setColorFilter(getResources().getColor(R.color.txt_color), PorterDuff.Mode.SRC_ATOP);
        getSupportActionBar().setHomeAsUpIndicator(backArrow);

        mAuth = FirebaseAuth.getInstance();
        send_comment = findViewById(R.id.send_comment);
        comment_input = findViewById(R.id.comment_input);
        comment_input.setImeOptions(EditorInfo.IME_ACTION_DONE);
        comment_list = findViewById(R.id.comment_list);
        error = findViewById(R.id.error);

        comment_list.setHasFixedSize(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
        comment_list.setLayoutManager(linearLayoutManager);
        error.setVisibility(View.VISIBLE);
        ref_id = Objects.requireNonNull(getIntent().getExtras()).getString("ref_id");
        file_url = Objects.requireNonNull(getIntent().getExtras()).getString("file_url");

        send_comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(comment_input.getText().toString())) {
                    insertComment(comment_input.getText().toString(), comment_input);
                    hideKeyboard(CommentActivity.this);

                }
            }
        });
        populateComment();
    }

    @Override
    public void onBackPressed() {
        Intent result = new Intent();
        setResult(Activity.RESULT_CANCELED, result);
        finish();
        this.overridePendingTransition(R.anim.animation_f_enter,
                R.anim.animation_f_leave);
    }

    private void setupWindowAnimations() {
        this.overridePendingTransition(R.anim.animation_enter,
                R.anim.animation_leave);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            overridePendingTransition(R.anim.animation_f_enter,
                    R.anim.animation_f_leave);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (GlobalData.canLogout) {
            finish();
        }
    }

    private void populateComment() {
        DocumentReference ref = FirebaseFirestore.getInstance().collection("forum_datas").document(ref_id);
        ref.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot document = task.getResult();
                    assert document != null;
                    if (document.exists()) {

                        Map<String, Object> map = document.getData();
                        assert map != null;

                        childHashMap = (ArrayList<HashMap<String, String>>) map.get("message");


                        adapter = new CommentRecyclerAdapter(CommentActivity.this, childHashMap);
                        comment_list.setAdapter(adapter);
                    }

                } else {
                    adapter = new CommentRecyclerAdapter(CommentActivity.this, childHashMap);
                    comment_list.setAdapter(adapter);
                }
                if (adapter == null || adapter.getItemCount() == 0) {
                    comment_input.setHint("Be the first to comment...");
                    error.setVisibility(View.VISIBLE);
                } else {
                    comment_input.setHint("Say something...");
                    error.setVisibility(View.GONE);
                }

            }

        });
    }

    public static void hideKeyboard(Activity activity) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(INPUT_METHOD_SERVICE);
        assert imm != null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            imm.hideSoftInputFromWindow(Objects.requireNonNull(activity.getCurrentFocus()).getWindowToken(), 0);
        }
    }

    private void insertComment(String message, final EditText comment_input) {
        comment_input.setText("");
        MediaPlayer sound = MediaPlayer.create(getApplicationContext(), R.raw.comment_sound);
        sound.start();
        long datetime = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date resultdate = new Date(datetime);
        String time = (sdf.format(resultdate));
        String sender_id = Objects.requireNonNull(mAuth.getCurrentUser()).getUid();
        String sender_name = "";
        if (GlobalData.user.getData().getFname() != null && GlobalData.user.getData().getLname() != null)
            sender_name = GlobalData.user.getData().getFname() + " " + GlobalData.user.getData().getLname();
        Comment msgData = new Comment(message, sender_id, sender_name, time/*, file_url*/);

        DocumentReference msgpost = FirebaseFirestore.getInstance().collection("forum_datas").document(ref_id);

        msgpost.update("message", FieldValue.arrayUnion(msgData));

        populateComment();

        /*FirebaseFirestore.getInstance().collection("blog_datas").document(ref_id).collection("Comments")
                .update("message", FieldValue.arrayUnion(msgData));
*/

    }
}

