package com.example.quiz;

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

import androidx.appcompat.app.AlertDialog;
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.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.quiz.data.model.ParisResponse;
import com.example.quiz.data.model.enums.PariStatut;
import com.example.quiz.databinding.FragmentWinTicketBinding;
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 com.google.android.material.appbar.MaterialToolbar;

import org.w3c.dom.Text;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;

import dagger.hilt.android.AndroidEntryPoint;

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

    FragmentWinTicketBinding binding;

    PariViewModel pariViewModel;

    LogsViewModel logsViewModel;

    SharedPrefsHelper sharedPrefsHelper;

    LoaderDialog loader;


    public WinTicket() {
        // Required empty public constructor
    }
    public static WinTicket newInstance() {
        WinTicket fragment = new WinTicket();
        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 = FragmentWinTicketBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        pariViewModel = new ViewModelProvider(this).get(PariViewModel.class);
        logsViewModel = new ViewModelProvider(this).get(LogsViewModel.class);
        sharedPrefsHelper = SharedPrefsHelper.getInstance(getContext());
        loader = new LoaderDialog(getContext());
        binding.winTicketBtnBack.setOnClickListener(v -> {
            getActivity().onBackPressed();
        });
        binding.scanTicketBtn.setOnClickListener(v ->{
            ScannerDialog scannerDialog = new ScannerDialog();
            scannerDialog.setOnBarcodeScannedListener(code -> {
                binding.referenceTicket.setText(code);
            });
            scannerDialog.show(getParentFragmentManager(), "scanner");
        });
        binding.winTicketVerificationBtn.setOnClickListener(v -> {
            String reference = binding.referenceTicket.getText().toString();
            if(reference.isEmpty()){
                MessageDialog.showError(getContext(), "Veuillez donner la reference du ticket");
                return;
            }
            pariViewModel.getPariByNumero(reference).observe(getViewLifecycleOwner(), new Observer<Result<ParisResponse>>() {
                @Override
                public void onChanged(Result<ParisResponse> parisResponseResult) {
                    switch (parisResponseResult.status){
                        case LOADING:{
                            loader.show("Recherche du ticket");
                            break;
                        }
                        case ERROR:{
                            MessageDialog.showError(getContext(), parisResponseResult.message);
                            break;
                        }
                        case SUCCESS:{
                            if(parisResponseResult.data.getNumeroTicket().equals(reference)){
                                loader.dismiss();
                                _showDialog(parisResponseResult.data);
                            }else{
                                MessageDialog.showError(getContext(), "Le ticket n'existe pas");
                            }
                            break;
                        }
                    }
                }
            });
        });
    }

    @SuppressLint("SetTextI18n")
    void _showDialog(ParisResponse pari){
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.pay_confirmation_layout, null);
        TextView statut = (TextView) view.findViewById(R.id.tv_statut);
        statut.setText("Statut: "+String.valueOf(pari.getStatutPari()));
        TextView dateHeure = (TextView) view.findViewById(R.id.tv_date_heure);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
        dateHeure.setText(formatter.format(LocalDateTime.now()));
        TextView numeroCourse = (TextView) view.findViewById(R.id.tv_numero_course);
        numeroCourse.setText(String.valueOf(pari.getCourseNumero()));
        TextView nomCourse = (TextView) view.findViewById(R.id.tv_nom_course);
        nomCourse.setText(pari.getCourseNom());
        TextView numeroTicket = (TextView) view.findViewById(R.id.tv_numero_ticket);
        numeroTicket.setText(pari.getNumeroTicket());
        TextView datePrise = (TextView) view.findViewById(R.id.tv_date_prise);
        datePrise.setText(formatter.format(OffsetDateTime.parse(pari.getDateHeurePrise())));
        TextView combinaison = (TextView) view.findViewById(R.id.tv_combinaison);
        combinaison.setText(pari.getCombinaison());
        TextView montant = (TextView) view.findViewById(R.id.tv_montant);
        LinearLayout montantLayout = (LinearLayout) view.findViewById(R.id.tv_montant_layout);
        Button confirmer = (Button) view.findViewById(R.id.btn_confirmer);
        LinearLayout notesLayout = (LinearLayout) view.findViewById(R.id.notes_layout);
        TextView notes = (TextView) view.findViewById(R.id.notes);

        TextView messageStatut = (TextView) view.findViewById(R.id.tv_message_statut);
        switch (pari.getStatutPari()){
            case GAGNANT:{
                messageStatut.setText("Veuillez confirmer le paiement de ce pari");
                montant.setText(pari.getGainCalcule()+" CFA");
                break;
            }
            case A_REMBOURSER:{
                messageStatut.setText("Veuillez confirmer le remboursement de ce pari");
                montant.setText(pari.getMiseTotale()+" CFA");
                break;
            }
            case PAYE:{
                messageStatut.setText("Ce pari a déjà été payé");
                montant.setText(pari.getGainCalcule()+" CFA");
                notesLayout.setVisibility(View.VISIBLE);
                notes.setText(pari.getNotes());
                confirmer.setVisibility(View.GONE);
                break;
            }
            default:{
                montantLayout.setVisibility(View.GONE);
                statut.setTextColor(Color.parseColor("#cf1c08"));
                messageStatut.setVisibility(View.GONE);
                confirmer.setVisibility(View.GONE);
                break;
            }
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setView(view);
        AlertDialog dialog = builder.create();
        Button annuler = (Button) view.findViewById(R.id.btn_annuler);
        annuler.setOnClickListener(v -> {
            dialog.dismiss();
        });
        confirmer.setOnClickListener(v -> {
            switch (pari.getStatutPari()){
                case A_REMBOURSER:{
                    pariViewModel.rembourserPari(pari.getNumeroTicket()).observe(getViewLifecycleOwner(), new Observer<Result<ParisResponse>>() {
                        @Override
                        public void onChanged(Result<ParisResponse> pariResponseResult) {
                            switch (pariResponseResult.status){
                                case LOADING: {
                                    loader.show("Remboursement en cours");
                                    break;
                                }
                                case ERROR: {
                                    loader.dismiss();
                                    MessageDialog.showError(getContext(), pariResponseResult.message);
                                    break;
                                }
                                case SUCCESS: {
                                    loader.dismiss();
                                    if(sharedPrefsHelper.get("id") == null){
                                        MessageDialog.showError(getContext(), "Erreur de connexion");
                                        return;
                                    }
                                    logsViewModel.insertLog(sharedPrefsHelper.get("id"), "REMBOURSEMENT TICKET", "Remboursement du ticket numéro "+ pari.getNumeroTicket()+" montant "+pari.getMiseTotale(), System.currentTimeMillis());
                                    MessageDialog.showSuccess(getContext(), "Remboursement effectué avec succès");
                                    binding.referenceTicket.setText("");
                                    dialog.dismiss();
                                    break;
                                }
                            }
                        }
                    });
                    break;
                }
                case GAGNANT:{
                    pariViewModel.payerPari(pari.getNumeroTicket()).observe(getViewLifecycleOwner(), new Observer<Result<ParisResponse>>() {
                        @Override
                        public void onChanged(Result<ParisResponse> pariResponseResult) {
                            switch (pariResponseResult.status){
                                case LOADING: {
                                    loader.show("Paiement en cours");
                                    break;
                                }
                                case ERROR: {
                                    loader.dismiss();
                                    MessageDialog.showError(getContext(), pariResponseResult.message);
                                    break;
                                }
                                case SUCCESS: {
                                    loader.dismiss();
                                    if(sharedPrefsHelper.get("id") == null){
                                        MessageDialog.showError(getContext(), "Erreur de connexion");
                                        return;
                                    }
                                    logsViewModel.insertLog(sharedPrefsHelper.get("id"), "PAIEMENT TICKET", "Paiement du ticket numéro "+ pari.getNumeroTicket()+" montant "+pari.getGainCalcule(), System.currentTimeMillis());
                                    binding.referenceTicket.setText("");
                                    MessageDialog.showSuccess(getContext(), "Paiement effectué avec succès");
                                    dialog.dismiss();
                                    break;
                                }
                            }
                        }
                    });
                    break;
                }
                default:{
                    dialog.dismiss();
                    MessageDialog.showError(getContext(), "Action non comprise pour ce ticket");
                    binding.referenceTicket.setText("");
                    break;
                }
            }
        });
        dialog.show();
    }

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

    }
}