package com.example.quiz;

import android.annotation.SuppressLint;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.MenuHost;
import androidx.core.view.MenuProvider;
import androidx.fragment.app.Fragment;

import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.quiz.data.adapter.BetsAdapter;
import com.example.quiz.data.model.Course;
import com.example.quiz.databinding.FragmentListOFBettingBinding;
import com.example.quiz.utils.Result;
import com.example.quiz.viewModel.CourseViewModel;
import com.example.quiz.viewModel.SharedViewModel;
import com.google.android.material.appbar.MaterialToolbar;

import java.util.List;

import dagger.hilt.android.AndroidEntryPoint;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ListOFBets#newInstance} factory method to
 * create an instance of this fragment.
 */

@AndroidEntryPoint
public class ListOFBets extends Fragment {

    FragmentListOFBettingBinding binding;

    private SharedViewModel shared;

    private CourseViewModel viewModel;

    private BetsAdapter adapter;

    private AppCompatActivity activity;


    public static ListOFBets newInstance() {
        ListOFBets fragment = new ListOFBets();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

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

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

        shared = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
        adapter = new BetsAdapter(shared);
        binding.recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
        binding.recyclerView.setAdapter(adapter);
        viewModel = new ViewModelProvider(this).get(CourseViewModel.class);



        /*viewModel.bets.observe(getViewLifecycleOwner(), bets -> {
            adapter.setBets(bets);
            adapter.setOnItemClickListener(position -> {
                shared.setBetId(position);
                FragmentManager fragmentManager = getParentFragmentManager();
                ListOfTypeOfBets typeOfBets = ListOfTypeOfBets.newInstance();
                fragmentManager.beginTransaction()
                        .replace(R.id.nav_host_fragment_content_main, typeOfBets)
                        .addToBackStack(null)
                        .commit();
            });
        });*/

        //viewModel.loadBets();
        observe();
        return binding.getRoot();
    }

    public void observe(){
        viewModel.getCourses(String.valueOf(shared.selectedReunion.getValue().getId())).observe(getViewLifecycleOwner(), new Observer<Result<List<Course>>>() {
            @Override
            public void onChanged(Result<List<Course>> result) {
                switch (result.status){
                    case LOADING:
                        Toast.makeText(getContext(), "Loading", Toast.LENGTH_SHORT).show();
                        break;
                    case SUCCESS:
                        adapter.setBets(result.data);
                        adapter.setOnItemClickListener(course ->{
                            shared.setSelectedCourse(course);
                            FragmentManager fragmentManager = getParentFragmentManager();
                            ListOfTypeOfBets typeOfBets = ListOfTypeOfBets.newInstance();
                            fragmentManager.beginTransaction()
                                    .replace(R.id.nav_host_fragment_content_main, typeOfBets)
                                    .addToBackStack(null)
                                    .commit();
                        });
                    case ERROR:
                        break;
                }
            }
        });
    }

    @SuppressLint("UseSupportActionBar")
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        MenuHost menuHost = requireActivity();

        // 🔹 On enlève d'abord les anciens menu providers si ce fragment est recréé
        menuHost.invalidateMenu();

        // 🔹 Ajout du menu spécifique à ce fragment
        menuHost.addMenuProvider(new MenuProvider() {
            @Override
            public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater menuInflater) {
                // Nettoyer avant d'inflater
                menu.clear();
                menuInflater.inflate(R.menu.menu_main, menu);
            }

            @Override
            public boolean onMenuItemSelected(@NonNull MenuItem menuItem) {
                int id = menuItem.getItemId();

                if (id == R.id.action_sold) {
                    FragmentManager fragmentManager = getParentFragmentManager();
                    Sold sold = Sold.newInstance();

                    fragmentManager.beginTransaction()
                            .replace(R.id.nav_host_fragment_content_main, sold)
                            .addToBackStack(null)
                            .commit();
                    return true;
                }

                return false;
            }
        }, getViewLifecycleOwner(), Lifecycle.State.RESUMED);
    }

    @Override
    public void onResume() {
        super.onResume();
        AppCompatActivity activity = (AppCompatActivity) getActivity();
        if(activity != null){
            MaterialToolbar toolbar = activity.findViewById(R.id.toolbar);
            activity.setSupportActionBar(toolbar);
            if(activity.getSupportActionBar() != null){
                activity.getSupportActionBar().setTitle("Liste des courses");
            }
        }
    }
}