package com.example.quiz;

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.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

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 android.widget.Toolbar;

import com.anggastudio.printama.Pref;
import com.anggastudio.printama.Printama;
import com.example.quiz.data.adapter.ReunionAdapter;
import com.example.quiz.data.model.Reunion;
import com.example.quiz.databinding.FragmentListOfReunionsBinding;
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.viewModel.ReunionViewModel;
import com.example.quiz.viewModel.SharedViewModel;
import com.google.android.material.appbar.MaterialToolbar;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import dagger.hilt.android.AndroidEntryPoint;

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

    FragmentListOfReunionsBinding binding;

    SharedViewModel shared;

    ReunionAdapter adapter;

    LoaderDialog loader;

    ReunionViewModel reunionViewModel;


    public ListOfReunions() {
        // Required empty public constructor
    }

    public static ListOfReunions newInstance(String username) {
        ListOfReunions fragment = new ListOfReunions();
        Bundle args = new Bundle();
        args.putString("USER_NAME", username);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestPermission();
    }
    private void requestPermission(){
        Pref.init(getContext());
        if (BluetoothUtils.needsBluetoothPermissions()) {
            if (!BluetoothUtils.hasBluetoothPermission(getContext())) {
                // Demande la permission si non accordée
                BluetoothUtils.requestBluetoothPermission(getActivity());
                return; // arrête ici, la popup va apparaître
            }
        }

        // 2️⃣ Permission OK, on peut afficher la liste
        try {
            Printama printama = Printama.with(getContext());
            if(!printama.isConnected()){
                BluetoothUtils.showPrinterList(getContext(), getActivity());
            }
        } catch (SecurityException e) {
            Toast.makeText(getContext(),
                    "Permission Bluetooth non accordée", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentListOfReunionsBinding.inflate(inflater, container, false);
        loader = new LoaderDialog(getContext());
        adapter = new ReunionAdapter();
        binding.reunionsList.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.reunionsList.setAdapter(adapter);
        reunionViewModel = new ViewModelProvider(this).get(ReunionViewModel.class);
        shared = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
        binding.reunionsLayout.setOnRefreshListener(()->{
            observeReunions();
            binding.reunionsLayout.setRefreshing(false);
        });
        observeReunions();
        return binding.getRoot();
    }

    public void observeReunions(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        String formattedDate = sdf.format(new Date());
        reunionViewModel.getReunions(formattedDate).observe(getViewLifecycleOwner(), new Observer<Result<List<Reunion>>>() {
            @Override
            public void onChanged(Result<List<Reunion>> result) {
                switch (result.status) {
                    case LOADING:
                        loader.show("Chargement des réunions");
                        break;
                    case SUCCESS:
                        loader.dismiss();
                        adapter.setReunions(result.data);
                        adapter.setOnItemClickListener(reunion->{
                            shared.setSelectedReunion(reunion);
                            FragmentManager fragmentManager = getParentFragmentManager();
                            ListOFBets bets = ListOFBets.newInstance();
                            fragmentManager.beginTransaction()
                                    .replace(R.id.nav_host_fragment_content_main, bets)
                                    .addToBackStack(null)
                                    .commit();
                        });
                        break;
                    case ERROR:
                        loader.dismiss();
                        MessageDialog.showError(getContext(), result.message);
                        break;
                }
            }
        });
    }

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

    @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().show();
                activity.getSupportActionBar().setTitle("Liste des réunions");
            }
            toolbar.setBackgroundColor(getResources().getColor(R.color.primary_green, null));
            toolbar.setTitleTextColor(getResources().getColor(R.color.white, null));
        }
    }
}