package com.androiddev.project.ili.wishurgift.fragments;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
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 androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.android.volley.Response;
import com.androiddev.project.ili.wishurgift.R;
import com.androiddev.project.ili.wishurgift.activities.AppMainActivity;
import com.androiddev.project.ili.wishurgift.activities.LoginActivity;
import com.androiddev.project.ili.wishurgift.adapter.WishListAdapter;
import com.androiddev.project.ili.wishurgift.adapter.WishSharedAdapter;
import com.androiddev.project.ili.wishurgift.api.UserApi;
import com.androiddev.project.ili.wishurgift.application.Wishurgift;
import com.androiddev.project.ili.wishurgift.model.WishList;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link MyListFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link MyListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MyListFragment extends Fragment {

    private ArrayList<WishList> wishLists = new ArrayList<>();
    private ArrayList<WishList> wishSharedLists = new ArrayList<>();
    private Gson gson = new Gson();
    private WishListAdapter wishListAdapter;
    private WishSharedAdapter wishSharedAdapter;
    private TextView addNewWishlist;
    private ProgressDialog pg;

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

    public static MyListFragment newInstance() {
        MyListFragment myListFragment = new MyListFragment();
        return myListFragment;

    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my_list_dashboard, container, false);
        if(Wishurgift.getSessionVariables().getUserConnected()==null || Wishurgift.getSessionVariables().getToken()==null){
            getActivity().finish();
            startActivity(new Intent(getActivity(), LoginActivity.class));
        }
        getListItems();
        ListView listView = view.findViewById(R.id.myListList);
        wishListAdapter = new WishListAdapter(getActivity(), wishLists);
        listView.setAdapter(wishListAdapter);
        listView.setOnItemClickListener((parent, view1, position, id) -> {
            WishList selectedItem = (WishList) parent.getItemAtPosition(position);
            afficherDetail(selectedItem, true);
        });
        getListItemsShared();
        ListView listView1 = view.findViewById(R.id.mySharedList);
        wishSharedAdapter = new WishSharedAdapter(getActivity(), wishSharedLists);
        listView1.setAdapter(wishSharedAdapter);
        listView1.setOnItemClickListener((parent, view12, position, id) -> {
            WishList selectedItem = (WishList) parent.getItemAtPosition(position);
            afficherDetail(selectedItem, false);
        });
        addNewWishlist = view.findViewById(R.id.addWishlist);
        addNewWishlist.setOnClickListener(v -> afficherAjouterWishlist());
        return view;
    }


    protected void onPreExecute() {
        pg = new ProgressDialog(getContext(), R.style.AppTheme_Dark_Dialog);
        pg.setTitle("Processing...");
        pg.setMessage("Please wait.");
        pg.setCancelable(false);
        pg.setIndeterminate(true);
        pg.show();
    }

    public void getListItems() {
        onPreExecute();
        List<String> items = new ArrayList<>();
        UserApi.getWishListsFromUser(Wishurgift.getSessionVariables().getUserConnected().getId(), new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    Log.d("log", "success : " + response);
                    JSONObject jsonObject = new JSONObject(response);
                    JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("list");
                    updateWishList(Arrays.asList(gson.fromJson(jsonArray.toString(), WishList[].class)));
                    pg.dismiss();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, error -> onError());

    }

    public void getListItemsShared() {
        List<String> items = new ArrayList<>();
        UserApi.getSharedListFromUser((Response.Listener<String>) response -> {
            try {
                JSONObject jsonObject = new JSONObject(response);
                JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("list");

                updateWishListShared(Arrays.asList(gson.fromJson(jsonArray.toString(), WishList[].class)));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }, error -> onError());
    }

    public void updateWishList(List<WishList> newList) {
        wishLists.clear();
        wishLists.addAll(newList);
        wishListAdapter.notifyDataSetChanged();
    }

    public void updateWishListShared(List<WishList> newList) {
        wishSharedLists.clear();
        wishSharedLists.addAll(newList);
        wishSharedAdapter.notifyDataSetChanged();
    }

    public void deleteWishList(WishList toDelete) {
        //delete
        Log.d("delete", "item " + toDelete.getId() + "deleted");
    }

    public void afficherDetail(WishList toView, boolean appartient) {

        //view
        if (toView != null)
        ((AppMainActivity) getActivity()).afficherContenuWishList(toView.getId(), appartient);

    }

    public void afficherAjouterWishlist() {

        ((AppMainActivity) getActivity()).afficherAjouterWishList();

    }

    public void onError(){
        AlertDialog.Builder alertDialogBuilder=new AlertDialog.Builder(getContext());
        alertDialogBuilder.setTitle("An error has occured");
        alertDialogBuilder.setMessage("You will be redirected to the login page").setCancelable(false).setNeutralButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                Wishurgift.getSessionVariables().setUserConnected(null);
                Wishurgift.getSessionVariables().setToken(null);
                ((AppMainActivity)getActivity()).finish();
                getActivity().startActivity(new Intent(getContext(), LoginActivity.class));
            }
        });
        AlertDialog alertDialog =alertDialogBuilder.create();
        alertDialog.show();
    }
}