package com.wall.photography.picture.fragment;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import com.wall.photography.picture.R;
import com.wall.photography.picture.Activity.Search;
import com.wall.photography.picture.Activity.Wallpaper;
import com.wall.photography.picture.databinding.FragmentMainBinding;
import com.wall.photography.picture.Data.Data;
import com.wall.photography.picture.tool.CommonUtils;
import com.wall.photography.picture.tool.GridItemDecoration;
import com.wall.photography.picture.Connect.ItemClick;
import com.wall.photography.picture.Project.List;
import com.wall.photography.picture.tool.ObjectBoxManager;

import java.util.ArrayList;


public class MainFragment extends Fragment implements ItemClick {
    private FragmentMainBinding vb;
    private ArrayList<String> tabTexts;
    private String currentTag = "Feature"; // 默认选中Feature
    private List itemList;

    public MainFragment() {
    }

    public static MainFragment newInstance(int type) {
        Bundle bundle = new Bundle();
        bundle.putInt(CommonUtils.key_index, type);
        MainFragment fragment = new MainFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        vb = FragmentMainBinding.inflate(inflater, container, false);
       tabTexts = new ArrayList<>();
        tabTexts.add(getString(R.string.Feature));
        tabTexts.add(getString(R.string.Animal));
        tabTexts.add(getString(R.string.Film));
        initTabVp();
        return vb.getRoot();
    }


    private void initTabVp() {
        vb.loadingPb.setVisibility(View.GONE);
        initList();
        initTags();

    }

    private void initTags() {
        // 默认选中Feature，设置初始状态
        vb.btnTag4d.setSelected(true);
        vb.btnTagLive.setSelected(false);
        vb.btnTag4k.setSelected(false);

        // 去掉所有阴影和边框效果
        vb.btnTag4d.setElevation(0f);
        vb.btnTagLive.setElevation(0f);
        vb.btnTag4k.setElevation(0f);
        vb.btnTag4d.setBackground(null);
        vb.btnTagLive.setBackground(null);
        vb.btnTag4k.setBackground(null);

        // 字体大小保持布局文件中的设置不变（25sp）
        // 设置浅绿色和下划线
        setupTextStyle(vb.btnTag4d, true);
        setupTextStyle(vb.btnTagLive, false);
        setupTextStyle(vb.btnTag4k, false);

        // 更新下划线显示状态和宽度
        updateUnderlineVisibility(R.id.underline_4d, true); // 默认选中Feature，显示下划线
        updateUnderlineVisibility(R.id.underline_live, false);
        updateUnderlineVisibility(R.id.underline_4k, false);

        // 更新下划线颜色
        updateUnderlineColor(R.id.underline_4d, true);
        updateUnderlineColor(R.id.underline_live, false);
        updateUnderlineColor(R.id.underline_4k, false);

        updateUnderlineWidth(vb.btnTag4d, R.id.underline_4d);

        // 设置点击监听器到包含TextView的RelativeLayout
        View layout4d = vb.getRoot().findViewById(R.id.layout_tag_4d);
        View layoutLive = vb.getRoot().findViewById(R.id.layout_tag_live);
        View layout4k = vb.getRoot().findViewById(R.id.layout_tag_4k);
        initVp();
        if (layout4d != null) {
            layout4d.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switchTag(tabTexts.get(0));
                }
            });
        }

        if (layoutLive != null) {
            layoutLive.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switchTag(tabTexts.get(1));
                }
            });
        }

        if (layout4k != null) {
            layout4k.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switchTag(tabTexts.get(2));
                }
            });
        }

        // 设置搜索图标点击事件
        if (vb.btnSearch != null) {
            vb.btnSearch.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 跳转到搜索页面
                    Intent intent = new Intent(requireContext(), Search.class);
                    startActivity(intent);
                }
            });
        }
    }

    private void initVp() {
        java.util.List<Fragment> list = new ArrayList<>();
        list.add(MainChildFragment.newInstance(tabTexts.get(0)));
        list.add(MainChildFragment.newInstance(tabTexts.get(1)));
        list.add(MainChildFragment.newInstance(tabTexts.get(2)));
        vb.vp2.setOffscreenPageLimit(2);
        vb.vp2.setUserInputEnabled(false);

        vb.vp2.setAdapter(new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                return list.get(position);
            }

            @Override
            public int getItemCount() {
                return list.size();
            }
        });
    }

    private void switchTag(String tag) {
        if (currentTag.equals(tag)) {
            return; // 如果已经是当前标签，不重复切换
        }

        currentTag = tag;

        // 更新标签选中状态和文字颜色
        boolean is4D = tag.equals("Feature");
        boolean isLIVE = tag.equals("Animal");
        boolean is4K = tag.equals("Film");

        vb.btnTag4d.setSelected(is4D);
        vb.btnTagLive.setSelected(isLIVE);
        vb.btnTag4k.setSelected(is4K);

        // 动态更新文字颜色和下划线（浅绿色，带下划线）
        setupTextStyle(vb.btnTag4d, is4D);
        setupTextStyle(vb.btnTagLive, isLIVE);
        setupTextStyle(vb.btnTag4k, is4K);

        // 更新下划线显示状态和宽度
        updateUnderlineVisibility(R.id.underline_4d, is4D);
        updateUnderlineVisibility(R.id.underline_live, isLIVE);
        updateUnderlineVisibility(R.id.underline_4k, is4K);

        // 更新下划线颜色
        updateUnderlineColor(R.id.underline_4d, is4D);
        updateUnderlineColor(R.id.underline_live, isLIVE);
        updateUnderlineColor(R.id.underline_4k, is4K);

        if (is4D) {
            updateUnderlineWidth(vb.btnTag4d, R.id.underline_4d);
        }
        if (isLIVE) {
            updateUnderlineWidth(vb.btnTagLive, R.id.underline_live);
        }
        if (is4K) {
            updateUnderlineWidth(vb.btnTag4k, R.id.underline_4k);
        }

        // 字体大小保持布局文件中的设置不变，不进行任何变化

        // 刷新列表数据
//        refreshListData();
        if (tag.equals(tabTexts.get(0))) {
            vb.vp2.setCurrentItem(0);
        } else if (tag.equals(tabTexts.get(1))) {
            vb.vp2.setCurrentItem(1);
        } else {
            vb.vp2.setCurrentItem(2);
        }

    }

    /**
     * 设置文字样式：选中时深绿色，未选中时浅绿色
     */
    private void setupTextStyle(TextView textView, boolean isSelected) {
        // 颜色值
        int lightGreenColor = 0xFF90EE90; // 浅绿色（未选中）
        int darkGreenColor = 0xFF228B22; // 深绿色（选中）- ForestGreen

        // 根据选中状态设置文字颜色
        int textColor = isSelected ? darkGreenColor : lightGreenColor;
        textView.setTextColor(textColor);

        // 移除默认的PaintFlags下划线
        textView.setPaintFlags(textView.getPaintFlags() & ~Paint.UNDERLINE_TEXT_FLAG);
    }

    /**
     * 更新下划线显示/隐藏状态
     */
    private void updateUnderlineVisibility(int underlineViewId, boolean isVisible) {
        View underlineView = vb.getRoot().findViewById(underlineViewId);
        if (underlineView != null) {
            underlineView.setVisibility(isVisible ? View.VISIBLE : View.INVISIBLE);
        }
    }

    /**
     * 更新下划线颜色：选中时深绿色，未选中时浅绿色
     */
    private void updateUnderlineColor(int underlineViewId, boolean isSelected) {
        View underlineView = vb.getRoot().findViewById(underlineViewId);
        if (underlineView != null) {
            int lightGreenColor = 0xFF90EE90; // 浅绿色（未选中）
            int darkGreenColor = 0xFF228B22; // 深绿色（选中）- ForestGreen
            int underlineColor = isSelected ? darkGreenColor : lightGreenColor;
            underlineView.setBackgroundColor(underlineColor);
        }
    }

    /**
     * 更新下划线宽度以匹配文字宽度
     */
    private void updateUnderlineWidth(TextView textView, int underlineViewId) {
        View underlineView = vb.getRoot().findViewById(underlineViewId);
        if (underlineView != null && textView != null) {
            // 使用post确保TextView已经完成测量
            textView.post(new Runnable() {
                @Override
                public void run() {
                    // 计算文字的实际宽度（不包括padding）
                    Paint paint = textView.getPaint();
                    String text = textView.getText().toString();
                    float textWidth = paint.measureText(text);

                    // 设置下划线的宽度为文字宽度
                    ViewGroup.LayoutParams params = underlineView.getLayoutParams();
                    params.width = (int) textWidth;
                    underlineView.setLayoutParams(params);
                }
            });
        }
    }

    private void refreshListData() {
        java.util.List<Data> data = ObjectBoxManager.queryWallpapersByTag(currentTag, 500);
        if (itemList != null) {
            itemList.setDataInfo(data);
        } else {
            initList();
        }
    }


    private void initList() {
//        java.util.List<Data> data = ObjectBoxManager.queryWallpapersByTag(currentTag, 500);
//        android.util.Log.d("FragmentMain", "已載入 " + data.size() + " 張圖片，標籤: " + currentTag);
//
//        if (data.isEmpty()) {
//            android.util.Log.e("FragmentMain", "數據庫中沒有找到數據！請檢查數據是否正確加載。");
//            // 顯示錯誤提示給用戶
//            if (getActivity() != null) {
//                getActivity().runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        android.widget.Toast.makeText(requireContext(),
//                                "正在載入圖片數據，請稍候...",
//                                android.widget.Toast.LENGTH_LONG).show();
//                    }
//                });
//            }
//        }
//
//        GridItemDecoration itemHelper = new GridItemDecoration(10, 10, 0);
//        GridLayoutManager gridLayoutManager = new GridLayoutManager(requireContext(), 3);
//        vb.classRecycler.addItemDecoration(itemHelper);
//        vb.classRecycler.setLayoutManager(gridLayoutManager);
//        int height = CommonUtils.dp2Px(180);
//        itemList = new List(requireContext(), height, false);
//        itemList.setDataInfo(data);
//        itemList.setInfoWallpaperListener(this);
//        vb.classRecycler.setAdapter(itemList);

    }

    @Override
    public void onItemClickAction(Data info) {
        Intent intent = new Intent(requireContext(), Wallpaper.class);
        intent.putExtra(CommonUtils.key_info, info);
        startActivity(intent);
    }

    @Override
    public void onClickMore(String name) {
        Intent intent = new Intent(requireContext(), com.wall.photography.picture.Activity.List.class);
        intent.putExtra(com.wall.photography.picture.Activity.List.key_index, name);
        startActivity(intent);
    }

    @Override
    public void onTagClick(String tagType, Data info) {
        // 点击标签后，跳转到列表页面，显示所有壁纸（标签用于筛选）
        Intent intent = new Intent(requireContext(), com.wall.photography.picture.Activity.List.class);
        intent.putExtra(com.wall.photography.picture.Activity.List.key_index, tagType);
        startActivity(intent);
    }
}
