package com.key.vibekeyboard.ui.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.key.vibekeyboard.MyApplication;
import com.key.vibekeyboard.R;
import com.key.vibekeyboard.databinding.DialogPermissionBinding;
import com.key.vibekeyboard.utils.InputMethodUtils;

public class PermissionRequestDialog extends DialogFragment {

    private DialogPermissionBinding binding;
    private InputMethodManager methodManager;
    private ContentObserver inputMethodObserver;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setCancelable(true);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DialogPermissionBinding.inflate(inflater, container, false);
        init();
        return binding.getRoot();
    }

    public void init() {
        methodManager = (InputMethodManager) MyApplication.instance.getSystemService(Context.INPUT_METHOD_SERVICE);

        Glide.with(requireContext())
                .load(R.mipmap.ic_launcher_foreground)
                .transform(new RoundedCorners(16))
                .into(binding.imageView);

        binding.firstIconTextLayout.setOnClickListener(v -> {
            Intent intent = new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS);
            startActivity(intent);
        });

        binding.secondIconTextLayout.setOnClickListener(v -> {
            methodManager.showInputMethodPicker();
        });

        binding.imageView.setOnClickListener(v -> dismiss());

        inputMethodObserver = new ContentObserver(new Handler(Looper.getMainLooper())) {
            @Override
            public void onChange(boolean selfChange) {
                super.onChange(selfChange);
                if (InputMethodUtils.isInputMethodEnabled() && InputMethodUtils.isCurrentInputMethodActive()) {
                    dismiss();
                }
            }
        };
    }

    @Override
    public void onStart() {
        super.onStart();
        requireContext().getContentResolver().registerContentObserver(
                Settings.Secure.getUriFor(Settings.Secure.DEFAULT_INPUT_METHOD),
                false,
                inputMethodObserver
        );
    }

    @Override
    public void onStop() {
        super.onStop();
        if (inputMethodObserver != null) {
            requireContext().getContentResolver().unregisterContentObserver(inputMethodObserver);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Dialog dialog = getDialog();
        if (dialog != null && dialog.getWindow() != null) {
            Window window = dialog.getWindow();
            window.setLayout((int) (getResources().getDisplayMetrics().widthPixels * 0.9), WindowManager.LayoutParams.WRAP_CONTENT);
        }

        update();
    }

    public void update() {
        boolean isEnabled = InputMethodUtils.isInputMethodEnabled();
        boolean isActive = InputMethodUtils.isCurrentInputMethodActive();

        if (isEnabled) {
            binding.firstIconTextLayout.setClickable(false);
            binding.firstIconTextLayout.setSelected(true);
        } else {
            binding.firstIconTextLayout.setClickable(true);
            binding.firstIconTextLayout.setSelected(false);
        }

        binding.secondIconTextLayout.setSelected(isActive);

        if (isEnabled && isActive) {
            dismiss();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        binding = null;
    }
}

