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.util.Log;
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.anggastudio.printama.Pref;
import com.anggastudio.printama.Printama;
import com.example.quiz.data.adapter.BetsAdapter;
import com.example.quiz.data.model.Course;
import com.example.quiz.data.model.PagedModel;
import com.example.quiz.data.remote.StompManager;
import com.example.quiz.databinding.FragmentListOFBettingBinding;
import com.example.quiz.utils.AuthNavigator;
import com.example.quiz.utils.BluetoothUtils;
import com.example.quiz.utils.LoaderDialog;
import com.example.quiz.utils.MessageDialog;
import com.example.quiz.utils.Result;
import com.example.quiz.utils.SessionManager;
import com.example.quiz.viewModel.CourseViewModel;
import com.example.quiz.viewModel.LoginViewModel;
import com.example.quiz.viewModel.LogsViewModel;
import com.example.quiz.viewModel.SharedViewModel;
import com.google.android.material.appbar.MaterialToolbar;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import javax.inject.Inject;

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;
    LoaderDialog loader;
    private SharedViewModel shared;

    private CourseViewModel viewModel;

    @Inject
    StompManager stompManager;

    AuthNavigator authNavigator;

    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);
        SessionManager sessionManager = SessionManager.newInstance(getContext());
        FragmentManager fragmentManager = getParentFragmentManager();
    }


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentListOFBettingBinding.inflate(inflater, container, false);
        loader = new LoaderDialog(getContext());
        shared = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
        adapter = new BetsAdapter();
        binding.recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
        binding.recyclerView.setAdapter(adapter);
        viewModel = new ViewModelProvider(this).get(CourseViewModel.class);
        authNavigator = new AuthNavigator(getContext(), getParentFragmentManager(), SessionManager.newInstance(getContext()),new ViewModelProvider(this).get(LoginViewModel.class),new ViewModelProvider(this).get(LogsViewModel.class), this);


        /*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(){
        String day = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDateTime.now());
        viewModel.getCourses(day).observe(getViewLifecycleOwner(), new Observer<Result<PagedModel<Course>>>() {
            @Override
            public void onChanged(Result<PagedModel<Course>> result) {
                switch (result.status){
                    case LOADING:
                        loader.show("Chargement des courses");
                        break;
                    case SUCCESS:
                        loader.dismiss();
                        adapter.setBets(result.data.getContent());
                        adapter.setOnItemClickListener(course ->{
                            shared.setSelectedCourse(course);
                            ListOfTypeOfBets typeOfBets = ListOfTypeOfBets.newInstance();
                            authNavigator.navigate(typeOfBets);
                        });
                        break;
                    case ERROR:
                        loader.dismiss();
                        MessageDialog.showError(getContext(), result.message);
                        break;
                }
            }
        });
    }

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

        stompManager.subscribe("courses", json->{
            requireActivity().runOnUiThread(this::observe);
            Log.d("STOMP", json);
        });

        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.getSupportActionBar().show();
            toolbar.setBackgroundColor( getResources().getColor(R.color.primary_green));
            toolbar.setTitleTextColor(getResources().getColor(R.color.white, null));
            activity.setSupportActionBar(toolbar);
            if(activity.getSupportActionBar() != null){
                activity.getSupportActionBar().setTitle("Liste des courses");
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stompManager.disconnect();
    }
}