package com.example.wallpapermagazine.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.example.wallpapermagazine.PvPoActivity;
import com.example.wallpapermagazine.R;
import com.example.wallpapermagazine.ReadFile;
import com.example.wallpapermagazine.Recycle_view;
import com.example.wallpapermagazine.ViewActivity;
import com.example.wallpapermagazine.WallPaperSelect;
import com.example.wallpapermagazine.action.InfoListWallPaperListener;
import com.example.wallpapermagazine.recylcle.RecommonedAdapter;
import com.google.android.material.navigation.NavigationView;

import java.util.Random;

public class FragmentHome extends Fragment implements InfoListWallPaperListener {
    private TextView textView1, textView2, textView3, textView4;
    private ImageView imageView1, imageView2, imageView3, imageView_trop;
    private DrawerLayout mdrawerLayout;
    private ImageView imageView;
    private Context mContext;
    private DrawerLayout drawerLayout;
    private RecyclerView recyclerView;
    private NavigationView navigationView;
    private TextView tv_seeAll;
    private int opp;
    private int rand;
    private String my_package_name, versionName;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        this.mContext = context;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.fragment_home, container, false);
        recyclerView = view.findViewById(R.id.recycler_view_home);
        imageView = view.findViewById(R.id.home_more);
        my_package_name = requireActivity().getPackageName();
        versionName = getVersionName();
        navigationView = requireActivity().findViewById(R.id.cata_navigation_view);
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                if (item.getItemId() == R.id.menu_pv) {
                    Intent intent = new Intent(requireContext(), PvPoActivity.class);
                    startActivity(intent);
                } else if (item.getItemId() == R.id.menu_rate) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse("https://play.google.com/store/apps/details?id=" + my_package_name));
                    if (intent.resolveActivity(requireActivity().getPackageManager()) != null) {
                        startActivity(intent);
                    } else {
                        // 如果没有应用可以处理，使用浏览器打开
                        intent.setData(Uri.parse("https://play.google.com/store/apps/details?id=" + my_package_name));
                        startActivity(intent);
                    }
                } else if (item.getItemId() == R.id.menu_share) {
                    Intent sendIntent = new Intent();
                    sendIntent.setAction(Intent.ACTION_SEND);
                    sendIntent.putExtra(Intent.EXTRA_TEXT, "https://play.google.com/store/apps/details?id=" + my_package_name);
                    sendIntent.setType("text/plain");
                    startActivity(sendIntent);
                } else {
                    showDialog();
                }

                return false;
            }
        });
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                drawerLayout = requireActivity().findViewById(R.id.dlt_main);
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });
        findByIf(view);
        Random randomRec = new Random();
        rand = randomRec.nextInt(WallPaperSelect.getCataName().size());
//        tv_seeAll.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Intent intent =new Intent(requireContext(), SeeAllActivity.class);
//                intent.putExtra("nameop",rand);
//                startActivity(intent);
//            }
//        });
        defRecom();
        setRecyclerviewWallpaper();

        return view;
    }

    private void defRecom() {
        textView1.setText(WallPaperSelect.getCataName().get(5).getName());
        textView2.setText(WallPaperSelect.getCataName().get(7).getName());
        textView3.setText(WallPaperSelect.getCataName().get(10).getName());
        textView4.setText(WallPaperSelect.getCataName().get(15).getName());
        setHimg(imageView1, 5);
        setHimg(imageView2, 7);
        setHimg(imageView3, 10);
        setVimg(imageView_trop, 15);

        imageView1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(), ViewActivity.class);
                intent.putExtra("naop", 5);
                intent.putExtra("dataop", opp);
                startActivity(intent);
            }
        });
        imageView2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(), ViewActivity.class);
                intent.putExtra("naop", 7);
                intent.putExtra("dataop", opp);
                startActivity(intent);
            }
        });
        imageView3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(), ViewActivity.class);
                intent.putExtra("naop", 10);
                intent.putExtra("dataop", opp);
                startActivity(intent);
            }
        });
        imageView_trop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(), ViewActivity.class);
                intent.putExtra("naop", 15);
                intent.putExtra("dataop", opp);
                startActivity(intent);
            }
        });
    }

    private void setRecyclerviewWallpaper() {

        Recycle_view recycle_View = new Recycle_view(10, 10, 15);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 1);
        gridLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.addItemDecoration(recycle_View);
        RecommonedAdapter recommonedAdapter = new RecommonedAdapter(WallPaperSelect.getCataName(), requireContext(), rand);
        recommonedAdapter.setInfoWallPaperListener((InfoListWallPaperListener) this);
        recyclerView.setAdapter(recommonedAdapter);
    }

    private void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.alterdialog, null);
        builder.setCustomTitle(dialogView);
        builder.setMessage("The current version is " + versionName)
                .setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private String getVersionName() {
        try {
            PackageInfo packageInfo = requireActivity().getPackageManager().getPackageInfo(requireActivity().getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "unknown"; // 或其他默认值
        }
    }

    private void findByIf(@NonNull View view) {
        imageView1 = view.findViewById(R.id.img_big);
        imageView2 = view.findViewById(R.id.img_nature);
        imageView3 = view.findViewById(R.id.img_super);
        imageView_trop = view.findViewById(R.id.img_Trop);
        textView1 = view.findViewById(R.id.tv_big);
        textView2 = view.findViewById(R.id.tv_nature);
        textView3 = view.findViewById(R.id.tv_suoer);
        textView4 = view.findViewById(R.id.tv_Trop);
        tv_seeAll = view.findViewById(R.id.tv_see_more);
    }

    private int getDataOp(int data) {
        int a;
        a = data;
        return a;
    }

    private void setHimg(ImageView imageView, int rand) {
        Random random = new Random();
        int randomnum = random.nextInt(124);
        while (WallPaperSelect.getCataName().get(rand).getDatas().get(randomnum).getBanner() == null) {
            randomnum = randomnum + 1;
            opp = getDataOp(randomnum);
        }
        Glide.with(mContext)
                .load(WallPaperSelect.getCataName().get(rand).getDatas().get(randomnum).getBanner())
                .transform(new RoundedCorners(ReadFile.dp2Px(7)))
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(imageView);
    }

    private void setVimg(ImageView imageView, int rand) {
        Random random = new Random();
        int randomnum = random.nextInt(124);
        while (WallPaperSelect.getCataName().get(rand).getDatas().get(randomnum).getPreviewThumb() == null) {
            randomnum = randomnum + 1;
            opp = getDataOp(randomnum);
        }
        Glide.with(mContext)
                .load(WallPaperSelect.getCataName().get(rand).getDatas().get(randomnum).getPreviewThumb())
                .transform(new RoundedCorners(ReadFile.dp2Px(7)))
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(imageView);
    }

    @Override
    public void onItemClickAction(int nameop, int recop) {
        Intent intent = new Intent(getActivity(), ViewActivity.class);
        intent.putExtra("naop", nameop);
        intent.putExtra("dataop", recop);
        startActivity(intent);
    }
}
