package com.colorful.keyboard.theme;

import static com.colorful.keyboard.theme.myutil.AppUtilKt.isMyInputMethodDefault;
import static com.colorful.keyboard.theme.myutil.AppUtilKt.isMyInputMethodEnabled;
import static com.colorful.keyboard.theme.net.BaseInitApiRequest.getNetData;
import static com.colorful.keyboard.theme.net.BaseInitApiRequest.initHHYApiStores;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.Settings;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;


import com.anythink.core.api.ATSDK;
import com.colorful.keyboard.theme.ad.AdsInsUtil;
import com.colorful.keyboard.theme.adapter.ViewPager2Adapter;
import com.colorful.keyboard.theme.fragment.KeyboardListFragment;
import com.colorful.keyboard.theme.model.ThemeListBean;
import com.colorful.keyboard.theme.myutil.AppUtilKt;
import com.colorful.keyboard.theme.myutil.ConfigBitmapUtils;
import com.colorful.keyboard.theme.myutil.ImmUtils;
import com.colorful.keyboard.theme.myutil.SPUtils;
import com.colorful.keyboard.theme.net.ApiCallbackCommon;
import com.colorful.keyboard.theme.net.ApiException;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;


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

public class MainActivity extends AppCompatActivity {

    private TabLayout tabLayout;
    private ViewPager2 viewPager;
    private List<Fragment> fragmentList = new ArrayList<>();

    private LinearLayout loadingLayout;

    private DrawerLayout drawerLayout;
    private LinearLayout navLayout;
    private TextView tvVersion;

    private RelativeLayout keyboardSettingLayout;
    private TextView keyboardNumber;

    private RelativeLayout dialog_step_layout;
    private TextView step1Btn;
    private TextView step2Btn;
    private LinearLayout no_data_layout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        registerReceiver();
        // AppLovinSdk.getInstance( this ).showMediationDebugger();
        ImmUtils.setStatusBar(this, false, false);
        tabLayout = findViewById(R.id.tabLayout);
        viewPager = findViewById(R.id.viewPager);
        no_data_layout = findViewById(R.id.no_data_layout);
        loadingLayout = findViewById(R.id.loadingLayout);
        drawerLayout = findViewById(R.id.drawerLayout);
        navLayout = findViewById(R.id.nav_view);
        ImageView ivSetting = findViewById(R.id.iv_setting);
        backToast = Toast.makeText(getBaseContext(), "Press again to exit", Toast.LENGTH_SHORT);
        tvVersion = findViewById(R.id.tv_version);
        keyboardSettingLayout = findViewById(R.id.keyboard_setting);
        dialog_step_layout = findViewById(R.id.dialog_step_layout);
        keyboardSettingLayout.setOnClickListener(v -> {
            dialog_step_layout.setVisibility(View.VISIBLE);
        });
        dialog_step_layout.setOnClickListener(v -> {
            dialog_step_layout.setVisibility(View.GONE);
        });
        step1Btn = findViewById(R.id.step_1_btn);
        step2Btn = findViewById(R.id.step_2_btn);
        keyboardNumber = findViewById(R.id.keyboardNumber);
        try {
            PackageManager packageManager = getPackageManager();
            String packageName = getPackageName();
            PackageInfo packageInfo = packageManager.getPackageInfo(packageName, 0);
            tvVersion.setText("v" + packageInfo.versionName);
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException(e);
        }
        if (SPUtils.getInstance().getString("bg").isEmpty()) {
            ConfigBitmapUtils.saveConfigImgToLocal(this, "https://cdn.kikakeyboard.com/terminal/online/20200331/Us21R82MAD-1585651198.jpg.webp");
        }

        findViewById(R.id.nav_view).setOnClickListener(v -> {
        });
        ivSetting.setOnClickListener(view -> {
            if (!drawerLayout.isDrawerOpen(findViewById(R.id.nav_view))) {
                drawerLayout.openDrawer(findViewById(R.id.nav_view));
            }
        });
        LinearLayout llYinsi = findViewById(R.id.ll_yinsi);
        llYinsi.setOnClickListener(view -> {
            startActivity(new Intent(MainActivity.this, LocalPrivacyAct.class));
            drawerLayout.close();
        });
        LinearLayout llDownload = findViewById(R.id.ll_download);
        llDownload.setOnClickListener(v -> {
            drawerLayout.close();
            startActivity(new Intent(MainActivity.this, DownloadsActivity.class));
        });
        LinearLayout ll_share = findViewById(R.id.ll_share);
        ll_share.setOnClickListener(v -> {
            drawerLayout.close();
            AppUtilKt.shareAppInfo(this);
        });
        step1Btn.setOnClickListener(v -> {
            Intent intent = new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS);
            startActivity(intent);

        });

        step2Btn.setOnClickListener(v -> {
            InputMethodManager imeManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            imeManager.showInputMethodPicker();
        });

        TextView textView = findViewById(R.id.try_again); // 你的TextView的ID
        String text = "Load error, try again!";
        // 创建一个SpannableString并应用下划线
        SpannableString spannableString = new SpannableString(text);
        spannableString.setSpan(new UnderlineSpan(), 0, text.length(), 0);
        // 将带有下划线的文本设置给TextView
        textView.setText(spannableString);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initData();
            }
        });
        initData();
    }

    private void initData(){
        loadingLayout.setVisibility(View.VISIBLE);
        no_data_layout.setVisibility(View.GONE);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("offset", 0);
        hashMap.put("fetch_size", 100);
        hashMap.put("sign", "a28aadc61c76c754944f6ddb48962c9c");
        getNetData(initHHYApiStores().getCategories(hashMap), new ApiCallbackCommon<ThemeListBean>(this, false) {
            @Override
            public void onSuccess(ThemeListBean model) {
                loadingLayout.setVisibility(View.GONE);
                no_data_layout.setVisibility(View.GONE);
                fragmentList.clear();
                for (int i = 0; i < model.getData().getSections().size(); i++) {
                    tabLayout.addTab(tabLayout.newTab());
                    KeyboardListFragment photoFragment = new KeyboardListFragment();
                    Bundle bundle = new Bundle();
                    bundle.putString("id", model.getData().getSections().get(i).getKey());
                    photoFragment.setArguments(bundle);
                    fragmentList.add(photoFragment);
                }

                ViewPager2Adapter homeTalentViewPager2Adapter = new ViewPager2Adapter(MainActivity.this, fragmentList);
                viewPager.setAdapter(homeTalentViewPager2Adapter);
                viewPager.setCurrentItem(0);
                viewPager.setOffscreenPageLimit(2);

                TabLayoutMediator mediator = new TabLayoutMediator(tabLayout, viewPager, new TabLayoutMediator.TabConfigurationStrategy() {
                    @Override
                    public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                        String title = model.getData().getSections().get(position).getTitle().trim().toLowerCase();
                        tab.setText(title);
                    }
                });

                mediator.attach();

            }

            @Override
            public void onFailure(ApiException ex) {
                loadingLayout.setVisibility(View.GONE);
                no_data_layout.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateKeyboardSettingLayout();
        AdsInsUtil.INSTANCE.loadAllAdIsNotCached(this);
    }

    @SuppressLint("SetTextI18n")
    private void updateKeyboardSettingLayout() {
        boolean enabledSet = isMyInputMethodEnabled(this);
        boolean defaultSet = isMyInputMethodDefault(this);

        if (enabledSet) {
            step1Btn.setBackground(getDrawable(R.drawable.drw_gray_select_bg));
            step1Btn.setText("Step 1:Enabled");
            step1Btn.setTextColor(Color.parseColor("#999999"));
        } else {
            step1Btn.setBackground(getDrawable(R.drawable.drw_80_btn));
            step1Btn.setText("Step 1:Select");
            step1Btn.setTextColor(Color.parseColor("#000000"));
        }
        if (defaultSet) {
            step2Btn.setBackground(getDrawable(R.drawable.drw_gray_select_bg));
            step2Btn.setText("Step 2:Enabled");
            step1Btn.setTextColor(Color.parseColor("#999999"));
        } else {
            step2Btn.setBackground(getDrawable(R.drawable.drw_80_btn));
            step2Btn.setText("Step 2:Select");
            step1Btn.setTextColor(Color.parseColor("#000000"));
        }

        int number = 0;
        if (!enabledSet) {
            number += 1;
        }
        if (!defaultSet) {
            number += 1;
        }

        keyboardNumber.setText("" + number);

        if (enabledSet && defaultSet) {
            keyboardSettingLayout.setVisibility(View.GONE);
        } else {
            keyboardSettingLayout.setVisibility(View.VISIBLE);
        }
    }

    private BroadcastReceiver receiver;

    private void registerReceiver() {
        IntentFilter filter = new IntentFilter(Intent.ACTION_INPUT_METHOD_CHANGED);
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                updateKeyboardSettingLayout();
                boolean enabledSet = isMyInputMethodEnabled(MainActivity.this);
                boolean defaultSet = isMyInputMethodDefault(MainActivity.this);
                if (enabledSet && defaultSet) {
                    dialog_step_layout.setVisibility(View.GONE);
                } else {
                    dialog_step_layout.setVisibility(View.VISIBLE);
                }
            }
        };
        registerReceiver(receiver, filter);
    }

    private void unregisterReceiver() {
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver();
    }


    private long backPressedTime = 0;
    private Toast backToast;

    @Override
    public void onBackPressed() {
        if (backPressedTime + 2000 > System.currentTimeMillis()) {
            super.onBackPressed();
            backToast.cancel();
        } else {
            backToast.show();
        }
        backPressedTime = System.currentTimeMillis();
    }
}