package com.app.simplitend.patient_dashboard.fragments;

import android.Manifest;
import android.app.role.RoleManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Bundle;
import android.telecom.TelecomManager;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TableLayout;
import android.widget.Toast;

import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.app.simplitend.R;
import com.app.simplitend.apputils.AppUtil;
import com.app.simplitend.databinding.ActivityCallsBinding;
import com.app.simplitend.databinding.CallListDialogBinding;
import com.app.simplitend.databinding.CreateContactViewHolderBinding;
import com.app.simplitend.welcome.welcomepatient.fragments.contacts.mvvm.AddContactAdapter;
import com.app.simplitend.welcome.welcomepatient.fragments.contacts.mvvm.models.ContactData;
import com.google.android.material.bottomsheet.BottomSheetDialog;

import java.util.ArrayList;

public class CallsActivity extends AppCompatActivity implements AddContactAdapter.ContactClickListener {

    protected ActivityCallsBinding binding;

    public static final String CALL_CONTACT_LIST_KEY = "contact_list_key";

    protected AddContactAdapter contactAdapter;
    protected ArrayList<ContactData> contactList;

    private String select_phone_number;

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

        contactList = (ArrayList<ContactData>) getIntent().getSerializableExtra(CALL_CONTACT_LIST_KEY);

        initViews();

        clickEvents();
        
    }

    @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);
    }

    private void clickEvents() {
        binding.backBtn.setOnClickListener(view -> onBackPressed());
    }

    private void initViews() {
        binding.contactRv.setLayoutManager(new GridLayoutManager(this, 2, LinearLayoutManager.VERTICAL, false));
        contactAdapter = new AddContactAdapter();
        binding.contactRv.setAdapter(contactAdapter);
        contactAdapter.setContactClickListener(this);

        if (contactList != null){
            contactAdapter.submitList(contactList);
        }else{
            Toast.makeText(this, "Couldn't load contact list", Toast.LENGTH_SHORT).show();
        }
    }

    private void showContactDialog(ContactData contactData) {
        CallListDialogBinding dialogBinding = CallListDialogBinding.inflate(getLayoutInflater());
        BottomSheetDialog bsd = new BottomSheetDialog(this, R.style.BottomSheetDialog);
        bsd.setContentView(dialogBinding.getRoot());

        boolean default_contact_set = false;
        if (contactData.phone_number != null) {
            addContactView(contactData.phone_number, default_contact_set = true, dialogBinding.contactTable, contactData);
            select_phone_number = contactData.phone_number;
        }

        // adding contacts to Contact_rv
        if (contactData.extra_phone_numbers != null && !contactData.extra_phone_numbers.isEmpty()) {
            String[] phone_numbers = contactData.extra_phone_numbers.split(",");

            for (String phone_number : phone_numbers) {
                addContactView(phone_number, phone_numbers.length == 1 && !default_contact_set, dialogBinding.contactTable, contactData);
            }
        }

        dialogBinding.callBtn.setOnClickListener(v -> {
            if (select_phone_number == null){
                Toast.makeText(this, "Select a contact", Toast.LENGTH_SHORT).show();
                return;
            }

            AppUtil.dialPhone(this, select_phone_number);
        });

        dialogBinding.messageBtn.setOnClickListener(v -> {
            if (select_phone_number == null){
                Toast.makeText(this, "Select a contact", Toast.LENGTH_SHORT).show();
                return;
            }

            AppUtil.messageNumber(this, select_phone_number);
        });

        bsd.show();
    }

    private void addContactView(String contact_number, boolean id_default,
                                TableLayout tableLayout, ContactData contactData) {
        CreateContactViewHolderBinding contact_binding = CreateContactViewHolderBinding.inflate(getLayoutInflater());

        contact_binding.createCountryCodes.setVisibility(View.GONE);
        contact_binding.createCountryCodes.setEnabled(false);

        contact_binding.createPhoneNumber.setText(contact_number);
        contact_binding.createPhoneNumber.setEnabled(false);

        contact_binding.defaultCheck.setOnClickListener(v -> {
            if (!contact_binding.defaultCheck.isSelected()) {
                selectDefaultContact(tableLayout.indexOfChild(contact_binding.getRoot()), tableLayout);
                select_phone_number = contact_number;
            }
        });

        contact_binding.delete.setOnClickListener(v -> {
            if (tableLayout.getChildCount() == 1) {
                Toast.makeText(this, "Cannot be deleted", Toast.LENGTH_SHORT).show();
                return;
            }

            try {
                tableLayout.removeView(contact_binding.getRoot());
            } catch (Exception e) {
                Toast.makeText(this, "Couldn't delete contact.", Toast.LENGTH_SHORT).show();
            }
        });

        contact_binding.defaultCheck.setSelected(id_default);

        // if contact is a doctor we wont allow the contact to be changes
        if (contactData != null && contactData.is_doctor != null && contactData.is_doctor.equals("1")){
            contact_binding.createPhoneNumber.setEnabled(false);
            contact_binding.createCountryCodes.setEnabled(false);
            contact_binding.defaultCheck.setEnabled(false);
        }

        tableLayout.addView(contact_binding.getRoot());
    }

    private void selectDefaultContact(int index, TableLayout tableLayout) {
        int count = tableLayout.getChildCount();
        if (index >= 0 && index < count) {
            // unselecting all other editBoxes
            for (int i = 0; i < count; i++) {
                View view = tableLayout.getChildAt(i);
                if (view != null) {
                    ImageButton default_check = view.findViewById(R.id.default_check);
                    if (default_check != null) {

                        if (i == index) {
                            default_check.setSelected(true);
                        } else {
                            default_check.setSelected(false);
                        }

                    }
                }
            }
        }
    }

    @Override
    public void onContactClick(ContactData contactData, int position) {
        showContactDialog(contactData);
    }
}