package com.app.simplitend.caregiverdashboard.activities;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.app.simplitend.R;
import com.app.simplitend.apputils.CaregiverDataCache;
import com.app.simplitend.apputils.RetrofitHelper;
import com.app.simplitend.articles.ArticlesActivity;
import com.app.simplitend.caregiverdashboard.fragments.CgDashBoardFragment;
import com.app.simplitend.caregiverdashboard.fragments.MyPatientFragment;
import com.app.simplitend.caregiverdashboard.mvvm.CaregiverMainViewModel;
import com.app.simplitend.cg_subscription.CgSubscriptionActivity;
import com.app.simplitend.chats.ChatFragment;
import com.app.simplitend.chats.SocketHelper;
import com.app.simplitend.customsviews.HomeBottomNav;
import com.app.simplitend.customsviews.MenuItem;
import com.app.simplitend.databinding.CaregiverDashboardActivityBinding;
import com.app.simplitend.databinding.CaregiverDashboardMenuBinding;
import com.app.simplitend.faqs.FAQ_Activity;
import com.app.simplitend.welcome.welcomecg.mvvm.CareGiverData;
import com.bumptech.glide.Glide;
import com.yarolegovich.slidingrootnav.SlidingRootNavBuilder;
import com.yarolegovich.slidingrootnav.callback.DragStateListener;

public class CaregiverDashActivity extends AppCompatActivity implements
        DragStateListener,
        HomeBottomNav.OnBottomNavItemSelectListener {

    // view binding
    protected CaregiverDashboardActivityBinding binding;
    private CaregiverDashboardMenuBinding menuBinding;
    protected CaregiverMainViewModel viewModel;
    private CareGiverData careGiverData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = CaregiverDashboardActivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        initViews();

        clickEvents();

        CaregiverDataCache.getCaregiverData(this, (careGiverData) -> {
            this.careGiverData = careGiverData;

            watchSubscription();
        }, true);
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        final Configuration configuration = new Configuration(newBase.getResources().getConfiguration());
        configuration.fontScale = Math.min(configuration.fontScale, 1.1f);
        applyOverrideConfiguration(configuration);
        super.attachBaseContext(newBase);
    }

    @Override
    protected void onResume() {
        super.onResume();
        CaregiverDataCache.getCaregiverData(this, (careGiverData) -> {
            this.careGiverData = careGiverData;

            setLayoutDetails();
        }, true);
    }

    @Override
    public void onBackPressed() {
        Fragment fragment = getSupportFragmentManager().findFragmentByTag("chat");
        if (fragment != null) {
            if (fragment instanceof ChatFragment) {
                binding.bottomNav.selectMenuItem(MenuItem.DASHBOARD);
                onBottomNavItemSelected(MenuItem.DASHBOARD);
            } else {
                super.onBackPressed();
            }
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SocketHelper.getInstance().closeConnection();
    }

    private void initViews() {

        // viewmodel
        viewModel = new ViewModelProvider(this).get(CaregiverMainViewModel.class);

        // inflating menu view
        menuBinding = CaregiverDashboardMenuBinding.inflate(getLayoutInflater());

        // sliding navigation bar
        viewModel.slidingRootNav = null;
        viewModel.slidingRootNav = new SlidingRootNavBuilder(this)
                .withMenuView(menuBinding.getRoot())
                .addDragStateListener(this)
                .withToolbarMenuToggle(binding.toolbar)
                .withRootViewScale(0.8f)
                .withDragDistance(250)
                .inject();

        binding.bottomNav.setItemSelectListener(this);

    }

    private void clickEvents() {

        // menu click events
        menuBinding.close.setOnClickListener(v -> {
            if (viewModel.slidingRootNav.isMenuOpened()) {
                viewModel.slidingRootNav.closeMenu(true);
            }
        });

        // content click events
        binding.tint.setOnClickListener(v -> {
            if (viewModel.slidingRootNav.isMenuOpened()) {
                viewModel.slidingRootNav.closeMenu(true);
                binding.tint.setVisibility(View.GONE);
            }
        });

        menuBinding.articles.setOnClickListener(v -> {
            Intent intent = new Intent(this, ArticlesActivity.class);
            startActivity(intent);
        });

        menuBinding.faqs.setOnClickListener(v -> {
            Intent intent = new Intent(this, FAQ_Activity.class);
            startActivity(intent);
        });

        menuBinding.cgProfile.setOnClickListener(v -> {
            Intent intent = new Intent(this, CaregiverProfileActivity.class);
            startActivity(intent);
        });

        menuBinding.contactAdmin.setOnClickListener(v -> {
            Intent intent = new Intent(this, ContactAdminActivity.class);
            startActivity(intent);
        });

        menuBinding.settings.setOnClickListener(v -> {
            Intent intent = new Intent(this, CaregiverSettingsActivity.class);
            startActivity(intent);
        });

    }

    private void watchSubscription() {
        if (careGiverData != null) {
            if (careGiverData.isCaregiverTakeSubscription != 1) {
                // user has not subscribed yet
                Intent intent = new Intent(this, CgSubscriptionActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                finish();
                return;
            }
        }

        // initializing dashboard fragment
        replaceFragment(CgDashBoardFragment.getInstance(), "dashboard");
    }

    private void setLayoutDetails() {
        if (careGiverData == null || careGiverData.patientDetails == null) {
            return;
        }

        menuBinding.name.setText(careGiverData.first_name);

        if (careGiverData.profile_photo != null) {
            Glide.with(this)
                    .load(RetrofitHelper.IMAGE_BASE_URL + careGiverData.profile_photo)
                    .placeholder(android.R.color.darker_gray)
                    .error(R.drawable.caregiver_img)
                    .into(menuBinding.cgImage);
        }

        // changing title if current fragment is
        Fragment fragment = getSupportFragmentManager().findFragmentByTag("dashboard");
        if (fragment != null) {
            if (fragment instanceof CgDashBoardFragment) {
                String first_name = "";
                if (careGiverData != null && careGiverData.first_name != null) {
                    String[] name = careGiverData.first_name.split(" ");
                    if (name.length > 0) {
                        first_name = name[0];
                    }
                }

                binding.toolbar.setTitle("Welcome " + first_name);
            }
        }

        String patient_name;
        try {
            patient_name = careGiverData.patientDetails.first_name.split(" ")[0];
        } catch (Exception e) {
            patient_name = careGiverData.patientDetails.first_name;
        }

        binding.bottomNav.setChatWithTxt("Chat with " + patient_name);
        binding.bottomNav.setMyPatient(patient_name);
    }

    private void replaceFragment(Fragment fragment, String tag) {
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fcv_cg_home, fragment, tag)
                .commitAllowingStateLoss();
    }

    // slide bar drag callbacks
    @Override
    public void onDragStart() {
        binding.getRoot().setRadius(30);
    }

    @Override
    public void onDragEnd(boolean isMenuOpened) {
        if (isMenuOpened) {
            binding.getRoot().setRadius(30);
            binding.tint.setVisibility(View.VISIBLE);
        } else {
            binding.getRoot().setRadius(0);
            binding.tint.setVisibility(View.GONE);
        }
    }

    @Override
    public void onBottomNavItemSelected(MenuItem selectedItem) {
        if (selectedItem == MenuItem.DASHBOARD) {
            replaceFragment(CgDashBoardFragment.getInstance(), "dashboard");

            // setting up toolbar accordingly
            binding.toolbar.setVisibility(View.VISIBLE);
            binding.bottomNav.setVisibility(View.VISIBLE);

            binding.toolbar.setNavigationIcon(AppCompatResources.getDrawable(this, R.drawable.ic_menu));
            binding.toolbar.setNavigationIconTint(getResources().getColor(R.color.black));

            String first_name = "";
            if (careGiverData != null && careGiverData.first_name != null) {
                String[] name = careGiverData.first_name.split(" ");
                if (name.length > 0) {
                    first_name = name[0];
                }
            }

            binding.toolbar.setTitle("Welcome " + first_name);

        } else if (selectedItem == MenuItem.MY_PATIENT) {
            replaceFragment(MyPatientFragment.getInstance(), "my_patient");

            // setting up toolbar accordingly
            binding.toolbar.setVisibility(View.VISIBLE);
            binding.bottomNav.setVisibility(View.VISIBLE);

            binding.toolbar.setTitle(null);
            binding.toolbar.setNavigationIcon(AppCompatResources.getDrawable(this, R.drawable.ic_menu));
            binding.toolbar.setNavigationIconTint(getResources().getColor(R.color.white));
        } else if (selectedItem == MenuItem.CHATS) {
            if (careGiverData.link_id == null){
                CaregiverDataCache.setCareGiverData(null); // to fetch new data with link id
            }

            CaregiverDataCache.getCaregiverData(this, (careGiverData1 -> {
                if (careGiverData1 != null && careGiverData1.patientDetails != null){
                    this.careGiverData = careGiverData1;

                    String sender_image;
                    if (careGiverData1.profile_photo == null){
                        sender_image = String.valueOf(R.drawable.caregiver_img);
                    }else{
                        sender_image = RetrofitHelper.IMAGE_BASE_URL + careGiverData1.profile_photo;
                    }

                    String receiver_image;
                    if (careGiverData1.patientDetails.profile_photo == null){
                        receiver_image = String.valueOf(R.drawable.senior_img);
                    }else{
                        receiver_image = RetrofitHelper.IMAGE_BASE_URL + careGiverData1.patientDetails.profile_photo;
                    }

                    replaceFragment(new ChatFragment(
                            careGiverData1.caregiver_xid + "",
                            careGiverData1.patientId + "",
                            careGiverData1.link_id,
                            careGiverData1.patientDetails.id + "",
                            careGiverData1.first_name,
                            careGiverData1.patientDetails.first_name,
                            sender_image,
                            receiver_image), "chat");
                }
            }), true);

            binding.toolbar.setVisibility(View.GONE);
            binding.bottomNav.setVisibility(View.GONE);
        }
    }
}