package com.example.salonappnew;

import android.graphics.Color;
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.ListView;
import android.widget.TextView;

import com.example.salonappnew.common.CommonConstants;
import com.example.salonappnew.models.Comments;
import com.example.salonappnew.models.DailyActivity;
import com.example.salonappnew.models.MedicineWeek;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;

import org.w3c.dom.Text;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import app.futured.donut.DonutProgressView;
import app.futured.donut.DonutSection;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ReportsFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ReportsFragment 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";
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    FirebaseAuth mFirebaseAuth = FirebaseAuth.getInstance();



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

    public ReportsFragment() {
        // 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 ReportsFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ReportsFragment newInstance(String param1, String param2) {
        ReportsFragment fragment = new ReportsFragment();
        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

        // Take data from firestore
        FirebaseUser user = mFirebaseAuth.getCurrentUser();
        View rootView = inflater.inflate(R.layout.fragment_reports, container, false);

        DonutProgressView dpvChart = rootView.findViewById(R.id.dpvChart);
        TextView txtMonth = (TextView) rootView.findViewById(R.id.txtMonth);
        ListView listParentsCommentsWeek1 = (ListView) rootView.findViewById(R.id.listParentsCommentsWeek1);
        ListView listParentsCommentsWeek2 = (ListView) rootView.findViewById(R.id.listParentsCommentsWeek2);
        ListView listParentsCommentsWeek3 = (ListView) rootView.findViewById(R.id.listParentsCommentsWeek3);
        ListView listParentsCommentsWeek4 = (ListView) rootView.findViewById(R.id.listParentsCommentsWeek4);

        ListView listDoctorsCommentsWeek1 = (ListView) rootView.findViewById(R.id.listDoctorsCommentsWeek1);
        ListView listDoctorsCommentsWeek2 = (ListView) rootView.findViewById(R.id.listDoctorsCommentsWeek2);
        ListView listDoctorsCommentsWeek3 = (ListView) rootView.findViewById(R.id.listDoctorsCommentsWeek3);
        ListView listDoctorsCommentsWeek4 = (ListView) rootView.findViewById(R.id.listDoctorsCommentsWeek4);


        String monthInText;

        Calendar c = Calendar.getInstance();

        int month =
                c.get(Calendar.MONTH);
        switch(month){
            case 0:
                monthInText = "January";
            break;
            case 1:
                monthInText = "February";
                break;
            case 2:
                monthInText = "March";
                break;
            case 3:
                monthInText = "April";
                break;
            case 4:
                monthInText = "May";
                break;
            case 5:
                monthInText = "June";
                break;
            case 6:
                monthInText = "July";
                break;
            case 7:
                monthInText = "August";
                break;
            case 8:
                monthInText = "September";
                break;
            case 9:
                monthInText = "October";
                break;
            case 10:
                monthInText = "November";
                break;
            case 11:
                monthInText = "December";
                break;

            default:
                monthInText = "Err";
                throw new IllegalStateException("Unexpected value: " + month);
        }
        txtMonth.setText(monthInText);

        final int[] completeCount = {0};
        final int[] notCompleteCount = {0};
        final int[] inProgressCount = {0};


        db.collection("dailyActivities").whereEqualTo("uid",user.getUid()).whereEqualTo("month",month+"").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        Log.d("chata",document.toString());

                        DailyActivity dailyActivity = document.toObject(DailyActivity.class);


                        if(dailyActivity.getProgressStatus().equals(CommonConstants.PROGRESS_STATUS_COMPLETE)){
                            completeCount[0] = completeCount[0] +1;
                        }

                        if(dailyActivity.getProgressStatus().equals(CommonConstants.PROGRESS_STATUS_IN_PROGRESS)){
                            inProgressCount[0] = inProgressCount[0] +1;
                        }

                        if(dailyActivity.getProgressStatus().equals(CommonConstants.PROGRESS_STATUS_NOT_COMPLETE)){
                            notCompleteCount[0] = notCompleteCount[0] +1;
                        }


                    }


                    int totalProgressCount = completeCount[0] + inProgressCount[0] + notCompleteCount[0];

                    float completeCountFloat = 100/totalProgressCount * completeCount[0];
                    float inProgressCountFloat = 100/totalProgressCount * inProgressCount[0];
                    float notCompleteCountFloat = 100/totalProgressCount * notCompleteCount[0];

                    Log.d("chata","count complete "+completeCount[0]);
                    Log.d("chata","count in progress "+inProgressCount[0]);
                    Log.d("chata","count not complete "+notCompleteCount[0]);
                    Log.d("chata","count total "+totalProgressCount);

                    Log.d("chata","count complete "+completeCountFloat);
                    Log.d("chata","count in progress "+inProgressCountFloat);
                    Log.d("chata","count not complete "+notCompleteCountFloat);

                    //Show chart from here
                    DonutSection complete = new DonutSection("Complete", Color.parseColor("#4E9FE5"), completeCountFloat);
                    DonutSection notComplete = new DonutSection("Not complete", Color.parseColor("#0000FF"), notCompleteCountFloat);
                    DonutSection inProgress = new DonutSection("In Progress", Color.parseColor("#AFE2EF"), inProgressCountFloat);
                    dpvChart.setCap(100f);

                    ArrayList arr = new ArrayList<>();
                    arr.add(complete);
                    arr.add(notComplete);
                    arr.add(inProgress);
                    dpvChart.submitData(arr);


                } else {
                    Log.d("chata", "Error getting documents: ", task.getException());
                }
            }
        });



        //start show comments
        //Start take data
        // Parent comments
        String[] weeksListArr = {CommonConstants.WEEK_1, CommonConstants.WEEK_2, CommonConstants.WEEK_3, CommonConstants.WEEK_4};
        ListView[] parentsCommentListArrr = {listParentsCommentsWeek1,listParentsCommentsWeek2,listParentsCommentsWeek3,listParentsCommentsWeek4};
        ListView[] doctorsCommentListArrr = {listDoctorsCommentsWeek1,listDoctorsCommentsWeek2,listDoctorsCommentsWeek3,listDoctorsCommentsWeek4};
        Log.d("chata","report "+user.getUid());
        Log.d("chata","report "+CommonConstants.WEEK_1);
        Log.d("chata","report "+month);


        //For doctors comments
        for (int i = 0; i < weeksListArr.length; i++) {
            int finalI = i;
            db.collection("dailyActivities").whereEqualTo("uid",user.getUid()).whereEqualTo("weekText", weeksListArr[i]).whereEqualTo("month",month+"").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        ArrayList<Comments> myListP = new ArrayList<>();
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            Log.d("chata",document.toString());

                            Comments comments = document.toObject(Comments.class);
                            comments.setParentComment(false);
                            myListP.add(comments);
                        }
                        CommentAdapter myAdapterP = new CommentAdapter(getContext(),myListP);
                        doctorsCommentListArrr[finalI].setAdapter(myAdapterP);

                    } else {
                        Log.d("chata", "Error getting documents: ", task.getException());
                    }
                }
            });
        }

        //For parents comments
        for (int i = 0; i < weeksListArr.length; i++) {
            int finalI = i;
            db.collection("dailyActivities").whereEqualTo("uid",user.getUid()).whereEqualTo("weekText", weeksListArr[i]).whereEqualTo("month",month+"").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        ArrayList<Comments> myListP = new ArrayList<>();
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            Log.d("chata",document.toString());

                            Comments comments = document.toObject(Comments.class);
                            comments.setParentComment(true);
                            myListP.add(comments);
                        }
                        CommentAdapter myAdapterP = new CommentAdapter(getContext(),myListP);
                        parentsCommentListArrr[finalI].setAdapter(myAdapterP);

                    } else {
                        Log.d("chata", "Error getting documents: ", task.getException());
                    }
                }
            });
        }


        //End take data
        //end show comments

        return rootView;
    }
}