package com.example.salonappnew;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;

import com.example.salonappnew.models.MedicineWeek;
import com.example.salonappnew.models.User;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;

import org.w3c.dom.Text;

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

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

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    FirebaseFirestore db = FirebaseFirestore.getInstance();
    FirebaseAuth mFirebaseAuth = FirebaseAuth.getInstance();

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

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ProfileFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ProfileFragment newInstance(String param1, String param2) {
        ProfileFragment fragment = new ProfileFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View rootView = inflater.inflate(R.layout.fragment_profile, container, false);

        EditText editTextName =(EditText) rootView.findViewById(R.id.editTextName);
        EditText editTextAge =(EditText) rootView.findViewById(R.id.editTextAge);
        EditText editTextAddress =(EditText) rootView.findViewById(R.id.editTextAddress);
        EditText editTextTelephone =(EditText) rootView.findViewById(R.id.editTextTelephone);
        EditText editTextRegisteredDate =(EditText) rootView.findViewById(R.id.editTextRegisteredDate);
        Button btnSave = (Button) rootView.findViewById(R.id.btnSave);
        Button btnSignOut = (Button) rootView.findViewById(R.id.btnSignOut);
        final String[] docId = {""};

        // Take data from firestore
        FirebaseUser user = mFirebaseAuth.getCurrentUser();

        //Start Take user data
        db.collection("users").whereEqualTo("uid",user.getUid()).get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        Log.d("chata","fire search done");
                        Log.d("chata","data"+task);

                        for (QueryDocumentSnapshot document : task.getResult()) {
                            Log.d("chata",document.toString());

                            User user = document.toObject(User.class);

                            docId[0] = document.getId();

                            editTextName.setText(user.getFullName());
                            editTextAge.setText(user.getAge()+"");
                            editTextAddress.setText(user.getAddress());
                            editTextTelephone.setText(user.getTelephone());
                            editTextRegisteredDate.setText(user.getRegDate());

                        }

                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.d("chata","fire search failed");
                    }
                });

        //end Take user data




        editTextName.setEnabled(false);
        editTextAge.setEnabled(false);
        editTextAddress.setEnabled(false);
        editTextTelephone.setEnabled(false);
        editTextRegisteredDate.setEnabled(false);

        TextView txtVEditProfile = (TextView) rootView.findViewById(R.id.txtVEditProfile);

        txtVEditProfile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                editTextName.setEnabled(true);
                editTextAge.setEnabled(true);
                editTextAddress.setEnabled(true);
                editTextTelephone.setEnabled(true);
                btnSave.setVisibility(View.VISIBLE);
            }
        });

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                editTextName.setEnabled(false);
                editTextAge.setEnabled(false);
                editTextAddress.setEnabled(false);
                editTextTelephone.setEnabled(false);
                btnSave.setVisibility(View.GONE);


                String fullName = editTextName.getText().toString();
                int age = Integer.parseInt(editTextAge.getText().toString());
                String address = editTextAddress.getText().toString();
                String telephone = editTextTelephone.getText().toString();
                String registeredDate=editTextRegisteredDate.getText().toString();

                Map<String, Object> usr = new HashMap<>();
                usr.put("fullName", fullName);
                usr.put("age", age);
                usr.put("address", address);
                usr.put("telephone", telephone);
                usr.put("uid", user.getUid());
                usr.put("regDate", registeredDate);

                db.collection("users").document(docId[0])
                        .set(usr)
                        .addOnSuccessListener(new OnSuccessListener<Void>() {
                            @Override
                            public void onSuccess(Void aVoid) {
                                Log.d("chata", "DocumentSnapshot successfully written!");
                            }
                        })
                        .addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                Log.w("chata", "Error writing document", e);
                            }
                        });

            }
        });



        btnSignOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FirebaseAuth.getInstance().signOut();
                Intent intent = new Intent(getContext(), login.class);
                startActivity(intent);
            }
        });



        return rootView;
    }
}