package com.example.quiz;

import android.app.AlertDialog;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
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.anggastudio.printama.Printama;
import com.example.quiz.data.model.dtos.paris.SoldeResponse;
import com.example.quiz.databinding.FragmentSoldByCourseBinding;
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.zxing.WriterException;

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

import dagger.hilt.android.AndroidEntryPoint;

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

@AndroidEntryPoint
public class SoldByCourse extends Fragment {

    FragmentSoldByCourseBinding binding;

    LoaderDialog loader;

    LogsViewModel logsViewModel;

    PariViewModel pariViewModel;

    SharedPrefsHelper prefsHelper;


    public static SoldByCourse newInstance() {
        SoldByCourse fragment = new SoldByCourse();
        Bundle args = new Bundle();

        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        prefsHelper = SharedPrefsHelper.getInstance(getContext());
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        binding = FragmentSoldByCourseBinding.inflate(inflater, container, false);
        logsViewModel = new ViewModelProvider(this).get(LogsViewModel.class);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        loader = new LoaderDialog(getContext());
        pariViewModel = new ViewModelProvider(this).get(PariViewModel.class);

        binding.btnCheckBalance.setOnClickListener(v -> {
            if(binding.etRaceNumber.getText().toString().isEmpty()){
                binding.etRaceNumber.setError("Veuillez entrer un numéro de course");
                return;
            }
            pariViewModel.getSoldeByCourse(prefsHelper.get("id"), binding.etRaceNumber.getText().toString()).observe(getViewLifecycleOwner(), new Observer<Result<SoldeResponse>>() {
                @Override
                public void onChanged(Result<SoldeResponse> doubleResult) {
                    switch (doubleResult.status){
                        case LOADING:{
                            loader.show("Chargement du solde");
                            break;
                        }
                        case ERROR:{
                            loader.dismiss();
                            MessageDialog.showError(getContext(), doubleResult.message);
                            break;
                        }
                        case SUCCESS:{
                            loader.dismiss();
                            try {
                                _showPariDialog(doubleResult.data, binding.etRaceNumber.getText().toString());
                            } catch (WriterException e) {
                                throw new RuntimeException(e);
                            }
                            logsViewModel.insertLog(prefsHelper.get("id"), "SOLDE COURSE", "Solde de la course "+binding.etRaceNumber.getText(), System.currentTimeMillis());
                            break;
                        }
                    }
                }
            });
        });
    }

    void _showPariDialog(SoldeResponse soldeResponse, String numero) throws WriterException {
        try {
            int solde = soldeResponse.getMontantParis() - soldeResponse.getMontantAnnulations() - soldeResponse.getMontantPaiements();
            new  AlertDialog.Builder(getContext())
                    .setTitle("Solde")
                    .setMessage("Solde la course "+solde)
                    .setNeutralButton("Ok", (dialog, which) -> {
                        binding.etRaceNumber.setText("");
                        dialog.dismiss();
                    })
                    .setPositiveButton("Imprimer", (dialog, which)->{
                        Printama printama = Printama.with(getContext());
                        Bitmap logo = BitmapFactory.decodeResource(getResources(), R.drawable.pmu_logo);
                        String title = "SOLDE DE LA COURSE "+numero;
                        StringBuilder text = new StringBuilder();
                        text.append("VENTES HIPPIQUES: ").append(String.valueOf(soldeResponse.getMontantParis())).append(" XOF").append("\n");
                        text.append("NBR. PAIEMENTS: ").append(soldeResponse.getNombrePaiements()).append("\n");
                        text.append("PAIEMENTS: ").append(String.valueOf(soldeResponse.getMontantPaiements())).append(" XOF").append("\n");
                        text.append("NBR. ANNULATIONS: ").append(soldeResponse.getNombreAnnulations()).append("\n");
                        text.append("ANNULATIONS: ").append(String.valueOf(soldeResponse.getMontantAnnulations())).append(" XOF").append("\n");
                        text.append(printama.lineSeparator()).append("\n");
                        text.append("SOLDE: ").append(String.valueOf(solde)).append(" XOF").append("\n");
                        text.append(printama.lineSeparator()).append("\n");
                        text.append("AGENT     :  ").append(prefsHelper.get("code")).append("\n");
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
                        String now = formatter.format(LocalDateTime.now());
                        text.append("DATE      :  ").append(now).append("\n");
                        printama.printSold(logo, title, text);
                    })
                    .show();
        }catch (SecurityException e){
            MessageDialog.showError(getContext(), "Erreur lors de l'affichage du solde");
        }
    }
}