package com.example.quiz;

import android.app.AlertDialog;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.quiz.data.model.ParisResponse;
import com.example.quiz.databinding.FragmentAnnulationTicketBinding;
import com.example.quiz.utils.LoaderDialog;
import com.example.quiz.utils.MessageDialog;
import com.example.quiz.utils.Result;
import com.example.quiz.utils.SharedPrefsHelper;
import com.example.quiz.viewModel.LogsViewModel;
import com.example.quiz.viewModel.PariViewModel;

import dagger.hilt.android.AndroidEntryPoint;

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

    FragmentAnnulationTicketBinding binding;

    SharedPrefsHelper prefsHelper;

    LogsViewModel logsViewModel;

    PariViewModel viewModel;


    LoaderDialog dialog;

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


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

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentAnnulationTicketBinding.inflate(inflater, container, false);
        prefsHelper = SharedPrefsHelper.getInstance(getContext());
        logsViewModel = new ViewModelProvider(this).get(LogsViewModel.class);
        dialog = new LoaderDialog(getContext());
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        viewModel = new ViewModelProvider(this).get(PariViewModel.class);
        binding.annuleTicketBtnBack.setOnClickListener(v->{
            getActivity().onBackPressed();
        });

        binding.scanTicketBtn.setOnClickListener(v -> {
            ScannerDialog scannerDialog = new ScannerDialog();
            scannerDialog.setOnBarcodeScannedListener(code -> {
               binding.referenceTicket.setText(code);
            });
            scannerDialog.show(getParentFragmentManager(), "scanner");
        });

        binding.annuleTicketBtn.setOnClickListener(v->{
            String reference = binding.referenceTicket.getText().toString();
           if(reference.isEmpty()){
               MessageDialog.showError(getContext(), "Veuillez donner la reference du ticket");
               return;
           }
           viewModel.getPariByNumero(reference).observe(getViewLifecycleOwner(), new Observer<Result<ParisResponse>>() {
               @Override
               public void onChanged(Result<ParisResponse> parisResponseResult) {
                   switch (parisResponseResult.status){
                       case LOADING:{
                          dialog.show("Recherche du ticket");
                          break;
                       }
                       case ERROR:{
                           MessageDialog.showError(getContext(), parisResponseResult.message);
                           dialog.dismiss();
                           break;
                       }
                       case SUCCESS:{
                           if(parisResponseResult.data.getNumeroTicket().equals(reference)){
                               dialog.dismiss();
                               if(parisResponseResult.data.getStatutPari() == ParisResponse.StatutPari.ANNULE){
                                   MessageDialog.showError(getContext(), "Le ticket est déjà annulé");
                                   return;
                               }
                               _showPariDialog(reference);
                           }else{
                               MessageDialog.showError(getContext(), "Le ticket n'existe pas");
                           }
                       }
                   }
               }
           });
        });
    }

    void _showPariDialog(String ticketReference){
        new AlertDialog.Builder(getContext())
                .setTitle("Annulation du ticket")
                .setMessage("Etes-vous sûr de vouloir annuler le ticket "+ticketReference+" ?")
                .setCancelable(true)
                .setNegativeButton("Annuler", (dialog, which) -> {
                    dialog.dismiss();
                })
                .setPositiveButton("Confirmer", (annulationDialog, which) -> {
                    String agentId = prefsHelper.get("id");
                    viewModel.annulerPari(ticketReference, agentId).observe(getViewLifecycleOwner(), new Observer<Result<ParisResponse>>() {
                        @Override
                        public void onChanged(Result<ParisResponse> pariResult) {
                            switch (pariResult.status){
                                case LOADING:{
                                    dialog.show("Annulation du ticket");
                                    break;
                                }
                                case ERROR:{
                                    dialog.dismiss();
                                    MessageDialog.showError(getContext(), pariResult.message);
                                    break;
                                }
                                case SUCCESS:{
                                    dialog.dismiss();
                                    MessageDialog.showSuccess(getContext(), "Ticket annulé avec succès");
                                    logsViewModel.insertLog(prefsHelper.get("id"), "ANNULATION TICKET", "Annulation du ticket "+pariResult.data.getNumeroTicket(), System.currentTimeMillis());
                                    binding.referenceTicket.setText("");
                                }
                            }
                        }
                    });
                }).show();
    }

    @Override
    public void onResume() {
        super.onResume();
        AppCompatActivity activity = (AppCompatActivity) getActivity();
        if(activity != null){
            activity.getSupportActionBar().setTitle("Annulation Ticket");
        }
    }
}

