package com.project.ilsaenterprise;

import android.os.AsyncTask;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.tabs.TabLayout;
import com.google.firebase.auth.FirebaseAuth;
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.fragment.ContactFragment;
import com.project.ilsaenterprise.fragment.GroupFragment;
import com.project.ilsaenterprise.models.Employees;
import com.project.ilsaenterprise.models.ListGroup;

import java.util.ArrayList;
import java.util.List;

public class Chat extends Fragment {
    private ViewPager viewPager;
    private ViewPagerAdapter viewPagerAdapter;
    private TabLayout tabLayout;
    private ImageView ivAddGroup;
    private BottomSheetDialog bottomSheetDialog;
    private List<String> listKey = new ArrayList<>();
    private DatabaseReference GroupRef = FirebaseDatabase.getInstance().getReference().child("Chats");
    private Toast toast;
    private boolean isAccepted;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        ((AppCompatActivity) getActivity()).getSupportActionBar().hide();
        View root = inflater.inflate(R.layout.fragment_chat, container, false);

        tabLayout = root.findViewById(R.id.tabLayout);
        viewPager = root.findViewById(R.id.viewPager);
        bottomSheetDialog = new BottomSheetDialog(
                getContext(), R.style.BottomSheetDialogTheme
        );

        viewPagerAdapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());

//        viewPagerAdapter.addFragments(new com.typroject.perkebunan_nusantara.fragment.ChatFragment(), "Pribadi");
        viewPagerAdapter.addFragments(new GroupFragment(), "Grup");
        viewPagerAdapter.addFragments(new ContactFragment(), "Kontak");

        viewPager.setAdapter(viewPagerAdapter);
        new setAdapterTask().execute();
        tabLayout.setupWithViewPager(viewPager);

        initialView(root);

        ivAddGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkPermission(root);
            }
        });

        return root;
    }

    private void checkPermission(View root){
        FirebaseAuth userAuth = FirebaseAuth.getInstance();
        DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference("users");
        String uid = userAuth.getUid();
        isAccepted = false;
        Log.d("TEST", uid);

        try{
            dbRef.child(uid).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    Employees userData = snapshot.getValue(Employees.class);

                    if(userData.getJabatan().equals("Kepala Bagian")){
                        newChatroomDialog(root);
                    }
                    else
                        Toast.makeText(Chat.this.getContext(), "Akses untuk Kepala Bagian", Toast.LENGTH_LONG).show();
                }

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

                }
            });
        }catch (Exception ex){
            Toast.makeText(Chat.this.getContext(), ex.getMessage(), Toast.LENGTH_LONG).show();
        }

    }

    private void initialView(View fragment){
        ivAddGroup = fragment.findViewById(R.id.ivAddGroup);
    }

    private void newChatroomDialog(View fragment){

        View bottomSheetView = LayoutInflater.from(getContext())
                .inflate(
                        R.layout.layout_popup_add_group_chat,
                        (LinearLayout) fragment.findViewById(R.id.bottomSheetContainer)
                );

        EditText addGroupEdt = bottomSheetView.findViewById(R.id.group_txt);
        RelativeLayout addGroupBtn = bottomSheetView.findViewById(R.id.btnAddGroup);

        addGroupBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(addGroupEdt.getText().toString().matches("")){
                    Toast.makeText(getContext(), "Masukkan nama grup.", Toast.LENGTH_LONG).show();
                }
                else{
                    buildNewChatroom(addGroupEdt.getText().toString());
                }
            }
        });

        bottomSheetDialog.setContentView(bottomSheetView);
        bottomSheetDialog.show();
    }

    private void buildNewChatroom(String chatroomName){
        if(listKey.size() == 0){
            GroupRef.child(chatroomName).setValue("")
                    .addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            if(task.isSuccessful())
                                toast = Toast.makeText(getActivity(), "Grup telah ditambahkan", Toast.LENGTH_SHORT);
                            View toastView = toast.getView();
                            toastView.setBackgroundResource(R.drawable.toast_drawable);
                            toast.show();
                        }
                    });
            bottomSheetDialog.cancel();
        }
        else
        {
            for(int i = 0; i < listKey.size(); i++){
                if(listKey.get(i).equals(chatroomName)){
                    toast = Toast.makeText(getActivity(), "Nama grup sudah ada", Toast.LENGTH_LONG);
                    View toastView = toast.getView();
                    toastView.setBackgroundResource(R.drawable.toast_drawable);
                    toast.show();
                    return;
                }
                if(i == listKey.size()-1 && !(listKey.get(i).equals(chatroomName))){
                    GroupRef.child(chatroomName).setValue("")
                            .addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    if(task.isSuccessful())
                                        toast = Toast.makeText(getActivity(), "Grup telah ditambahkan", Toast.LENGTH_SHORT);
                                    View toastView = toast.getView();
                                    toastView.setBackgroundResource(R.drawable.toast_drawable);
                                    toast.show();
                                }
                            });
                    bottomSheetDialog.cancel();
                }
            }
        }

    }

    private class setAdapterTask extends AsyncTask<Void,Void,Void> {
        protected Void doInBackground(Void... params) {
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            viewPager.setAdapter(viewPagerAdapter);
        }
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {

        private ArrayList<Fragment> fragments;
        private ArrayList<String> titles;

        ViewPagerAdapter(FragmentManager fm){
            super(fm);
            this.fragments = new ArrayList<>();
            this.titles = new ArrayList<>();
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            switch (position)
            {
                case 0:
                    return new GroupFragment(); //ChildFragment1 at position 0
                case 1:
                    return new ContactFragment(); //ChildFragment2 at position 1
            }
            return null;
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        public void addFragments(Fragment fragment, String title){
            fragments.add(fragment);
            titles.add(title);
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return titles.get(position);
        }

    }
}