package com.kaviz.heal.Activities;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.os.Bundle;
import android.util.ArrayMap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.kaviz.heal.Adapters.PharmacyAdapter;
import com.kaviz.heal.Interfaces.ClickEvents;
import com.kaviz.heal.Model.Pharmacy;
import com.kaviz.heal.Model.User;
import com.kaviz.heal.R;
import com.kaviz.heal.databinding.ActivityShowPharmaciesBinding;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ShowPharmaciesActivity extends AppCompatActivity implements ClickEvents {

    private ActivityShowPharmaciesBinding binding;
    private ArrayList<Pharmacy>pharmacyList;
    private Dialog addNumberDialog;
    private Pharmacy pharmacy;
    private String medicines;

    private FirebaseAuth auth;
    private FirebaseDatabase database;
    String userName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityShowPharmaciesBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        if (getSupportActionBar() != null) {

            getSupportActionBar().setTitle("Pharmacy List");

        }

        database = FirebaseDatabase.getInstance();
        auth = FirebaseAuth.getInstance();

        pharmacyList = (ArrayList<Pharmacy>) getIntent().getSerializableExtra("PharmacyList");
        medicines = getIntent().getStringExtra("Medicines");
        final PharmacyAdapter adapter = new PharmacyAdapter(this, pharmacyList, this);

        binding.pharmacyRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.pharmacyRecyclerView.setHasFixedSize(true);
        binding.pharmacyRecyclerView.setAdapter(adapter);

        initializeAddCategoryDialog();


    }

    @Override
    public void onClick(int position) {

        pharmacy = pharmacyList.get(position);
        System.out.println(pharmacy.getName());

        addNumberDialog.show();

    }

    private void initializeAddCategoryDialog() {

        addNumberDialog = new Dialog(this);
        addNumberDialog.setContentView(R.layout.add_number_layout);
        addNumberDialog.setCancelable(true);
        addNumberDialog.getWindow().setBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.progress_background));
        addNumberDialog.getWindow().setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        EditText numberNameText = addNumberDialog.findViewById(R.id.numberNameText);
        AppCompatButton addNumberButton = addNumberDialog.findViewById(R.id.addNumberButton);
        numberNameText.getText().clear();

        addNumberButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                binding.progressBar.setVisibility(View.VISIBLE);

                String number = numberNameText.getText().toString();

                if (number.isEmpty()) {

                    Toast.makeText(ShowPharmaciesActivity.this, "Enter Mobile Number", Toast.LENGTH_SHORT).show();
                    binding.progressBar.setVisibility(View.GONE);

                } else {

                    addNumberDialog.cancel();
                    addDataToPharmacy(pharmacy, number);

                }

            }
        });

}

    private void addDataToPharmacy(Pharmacy pharmacy, String number) {

        binding.progressBar.setVisibility(View.VISIBLE);

        database.getReference().child("UserDetails").child(auth.getCurrentUser().getUid())
                .addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {

                        User user = snapshot.getValue(User.class);

                        if (user != null) {

                            userName = user.getName();
                            Map<String, Object>dataMap = new ArrayMap<>();
                            dataMap.put("clientName", user.getName());
                            dataMap.put("phoneNumber", number);
                            dataMap.put("medicines", medicines);

                            database.getReference().child("Orders").push().setValue(dataMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {

                                    if (task.isSuccessful()) {

                                        Toast.makeText(ShowPharmaciesActivity.this, "The order has been sent Successfully!", Toast.LENGTH_SHORT).show();

                                    } else {

                                        Toast.makeText(ShowPharmaciesActivity.this, "Error - "+task.getException().getMessage(), Toast.LENGTH_SHORT).show();

                                    }

                                    binding.progressBar.setVisibility(View.GONE);

                                }
                            });

                        }

                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {

                        Toast.makeText(ShowPharmaciesActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();

                    }
                });

    }
}