package com.paint.sweet.drawing.sweetfragment;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.navigation.NavigationView;
import com.paint.sweet.drawing.R;
import com.paint.sweet.drawing.databinding.FragmentHomeMainBinding;
import com.paint.sweet.drawing.sweetactivity.DrawingSearchActivity;
import com.paint.sweet.drawing.sweetmanager.AppConstants;

import java.util.List;

public class HomeMainFragment extends Fragment {
    private FragmentHomeMainBinding binding;
    private List<String> allDirs;
    private DrawerLayout drawerLayout;
    private NavigationView navView;
    private ImageView menuToggleIv;
    private int currentSelectedMenuId = -1;

    public HomeMainFragment() {}

    public static HomeMainFragment newInstance() {
        return new HomeMainFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        allDirs = AppConstants.getAllDir();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentHomeMainBinding.inflate(inflater, container, false);

        initViews();
        initMenuToggleIcon();
        addStatusBarPlaceholder();
        restoreBackground();
        initDrawerAndNav();
        setSearchIcon();
        setupSearchBoxAsJumpButton();
        initViewPager();
        selectFirstMenuItem();

        return binding.getRoot();
    }

    private void initViews() {
        menuToggleIv = binding.ivMenuToggle;
    }

    private void initMenuToggleIcon() {
        menuToggleIv.setOnClickListener(v -> {
            if (drawerLayout.isDrawerOpen(navView)) {
                drawerLayout.closeDrawer(navView);
            } else {
                drawerLayout.openDrawer(navView);
            }
        });
    }

    private void addStatusBarPlaceholder() {
        int statusBarHeight = getStatusBarHeight();
        ViewGroup parent = (ViewGroup) binding.etSearch.getParent();
        parent.setPadding(parent.getPaddingLeft(),
                statusBarHeight + parent.getPaddingTop(),
                parent.getPaddingRight(),
                parent.getPaddingBottom());
    }

    private int getStatusBarHeight() {
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        return resourceId > 0 ? getResources().getDimensionPixelSize(resourceId) : 0;
    }

    private void restoreBackground() {
        binding.drawerLayout.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.bg));
        View mainContent = binding.drawerLayout.getChildAt(0);
        if (mainContent != null) {
            mainContent.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.bg));
        }
    }

    private void initDrawerAndNav() {
        drawerLayout = binding.drawerLayout;
        navView = binding.navView;
        navView.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.bg));
        navView.getMenu().clear();

        // 动态添加Menu Item（适配窄导航栏+文字居中）
        for (int i = 0; i < allDirs.size(); i++) {
            String dir = allDirs.get(i);
            String title = dir.substring(dir.lastIndexOf("_") + 1);
            int itemId = dir.hashCode();

            // 加载自定义Item布局（依赖布局文件的居中配置，移除代码内的padding和textSize）
            View itemView = LayoutInflater.from(requireContext())
                    .inflate(R.layout.item_nav_menu, navView, false);
            TextView tvTitle = itemView.findViewById(R.id.tv_menu_title);
            tvTitle.setText(title);
            // 移除代码内的padding和textSize设置，完全依赖布局文件
            // 核心：布局文件已设置android:gravity="center"，无需额外调整

            // 强制设置布局可点击，并绑定点击事件（修复点击文字无响应的核心逻辑）
            itemView.setClickable(true);
            // 【关键修复】给自定义布局设置点击事件，手动触发Menu Item的选中逻辑
            itemView.setOnClickListener(v -> {
                navView.getMenu().performIdentifierAction(itemId, 0);
            });

            // 添加到Menu并绑定布局
            navView.getMenu().add(0, itemId, i, "")
                    .setActionView(itemView);
        }

        // 菜单点击事件
        navView.setNavigationItemSelectedListener(item -> {
            if (currentSelectedMenuId != -1) {
                View prevView = navView.getMenu().findItem(currentSelectedMenuId).getActionView();
                if (prevView != null) prevView.setSelected(false);
            }
            View currentView = item.getActionView();
            if (currentView != null) currentView.setSelected(true);
            currentSelectedMenuId = item.getItemId();

            TextView tvTitle = currentView.findViewById(R.id.tv_menu_title);
            String title = tvTitle.getText().toString();
            for (int i = 0; i < allDirs.size(); i++) {
                String dir = allDirs.get(i);
                String tabTitle = dir.substring(dir.lastIndexOf("_") + 1);
                if (tabTitle.equals(title)) {
                    binding.viewPager.setCurrentItem(i, false);
                    drawerLayout.closeDrawer(navView);
                    return true;
                }
            }
            return false;
        });
    }

    private void selectFirstMenuItem() {
        if (navView.getMenu().size() > 0) {
            currentSelectedMenuId = navView.getMenu().getItem(0).getItemId();
            View firstView = navView.getMenu().getItem(0).getActionView();
            if (firstView != null) firstView.setSelected(true);
        }
    }

    private void setSearchIcon() {
        EditText etSearch = binding.etSearch;
        etSearch.setBackground(ContextCompat.getDrawable(requireContext(), R.drawable.bg_search_input));
        etSearch.setTextColor(ContextCompat.getColor(requireContext(), R.color.white));
        etSearch.setHintTextColor(ContextCompat.getColor(requireContext(), R.color.gray_number));
        etSearch.setTextSize(16);
        etSearch.setPadding(dp2px(16), dp2px(12), dp2px(16), dp2px(12));

        Drawable searchIcon = ContextCompat.getDrawable(requireContext(), R.mipmap.search2);
        if (searchIcon != null) {
            int iconSize = dp2px(18);
            searchIcon.setBounds(0, 0, iconSize, iconSize);
            searchIcon.setTint(ContextCompat.getColor(requireContext(), R.color.gray_number));
            etSearch.setCompoundDrawables(searchIcon, null, null, null);
            etSearch.setCompoundDrawablePadding(dp2px(10));
        }
    }

    private void setupSearchBoxAsJumpButton() {
        EditText etSearch = binding.etSearch;
        etSearch.setFocusable(false);
        etSearch.setFocusableInTouchMode(false);
        etSearch.setClickable(true);
        etSearch.setOnClickListener(v -> {
            Intent intent = new Intent(requireContext(), DrawingSearchActivity.class);
            startActivity(intent);
        });
    }

    private int dp2px(float dp) {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    private void initViewPager() {
        ViewPager2 viewPager = binding.viewPager;
        viewPager.setAdapter(new FragmentStateAdapter(this) {
            @Override
            public int getItemCount() {
                return allDirs.size();
            }

            @NonNull
            @Override
            public Fragment createFragment(int position) {
                String dir = allDirs.get(position);
                String categoryName = dir.substring(dir.lastIndexOf("_") + 1);
                return DrawingImagePreviewFragment.newInstance(allDirs.get(position), categoryName);
            }
        });

        // ViewPager切换时，同步选中项样式
        viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                if (navView.getMenu().size() > position) {
                    if (currentSelectedMenuId != -1) {
                        View prevView = navView.getMenu().findItem(currentSelectedMenuId).getActionView();
                        if (prevView != null) prevView.setSelected(false);
                    }
                    currentSelectedMenuId = navView.getMenu().getItem(position).getItemId();
                    View currentView = navView.getMenu().getItem(position).getActionView();
                    if (currentView != null) currentView.setSelected(true);
                }
            }
        });
    }

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