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.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

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.CommentaireAdapter;
import com.androiddev.project.ili.wishurgift.api.ElementsApi;
import com.androiddev.project.ili.wishurgift.application.Wishurgift;
import com.androiddev.project.ili.wishurgift.model.Commentaire;
import com.androiddev.project.ili.wishurgift.model.Element;
import com.google.gson.Gson;

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.
 * Use the {@link ElementFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ElementFragment 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";
    private static final String ARG_PARAM3 = "param3";
    // TODO: Rename and change types of parameters
    private int idParent, idElt;
    private boolean appartient;
    TextView nomElt, linkElt, eltAdresse, eltPrice, eltDescription, eltStatus;
    Button buttonAcheter, buttonUrgent, buttonReserver, buttonSupprimer, buttonAddComment, buttonEditElement;
    EditText commentaire;
    ImageView imgElement;
    Gson gson = new Gson();
    List<Commentaire> commentaires = new ArrayList<>();
    CommentaireAdapter commentaireAdapter;
    LinearLayout linkLayout, adresseLayout;
    private ProgressDialog pg;

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

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param idParent   Parameter 1.
     * @param id         Parameter 2.
     * @param appartient Parameter 3
     * @return A new instance of fragment ElementFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ElementFragment newInstance(int idParent, int id, boolean appartient) {
        ElementFragment fragment = new ElementFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, idParent);
        args.putInt(ARG_PARAM2, id);
        args.putBoolean(ARG_PARAM3, appartient);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            idParent = getArguments().getInt(ARG_PARAM1);
            idElt = getArguments().getInt(ARG_PARAM2);
            appartient = getArguments().getBoolean(ARG_PARAM3);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if(Wishurgift.getSessionVariables().getUserConnected()==null || Wishurgift.getSessionVariables().getToken()==null){
            getActivity().finish();
            startActivity(new Intent(getActivity(), LoginActivity.class));
        }
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_element, container, false);
        nomElt = view.findViewById(R.id.nomElt);
        linkElt = view.findViewById(R.id.linkElt);
        linkLayout = view.findViewById(R.id.layoutUrlElt);
        linkLayout.setOnClickListener(v -> {
            Log.d("log", "clic");
            String link = linkElt.getText().toString();
            if (link != null && link.startsWith("http://") || link.startsWith("https://")) {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(link)));
            }
        });
        eltAdresse = view.findViewById(R.id.adresseElt);
        adresseLayout = view.findViewById(R.id.layoutAdresseElt);
        adresseLayout.setOnClickListener(v -> {
            String adresse = eltAdresse.getText().toString();
            if (adresse != null) {
                Uri intentUri = Uri.parse("geo:0,0?q=" + adresse);
                Intent mapIntent = new Intent(Intent.ACTION_VIEW, intentUri);
                mapIntent.setPackage("com.google.android.apps.maps");
                if (mapIntent.resolveActivity(getActivity().getPackageManager()) != null) {
                    startActivity(mapIntent);
                }
            }
        });
        eltPrice = view.findViewById(R.id.eltPrice);
        eltDescription = view.findViewById(R.id.eltDescription);
        eltStatus = view.findViewById(R.id.eltStatus);
        buttonSupprimer = view.findViewById(R.id.supprimerElement);
        buttonAcheter = view.findViewById(R.id.boutonAcheter);
        buttonReserver = view.findViewById(R.id.boutonReserver);
        buttonUrgent = view.findViewById(R.id.boutonUrgent);
        afficherDonnees();
        commentaire = view.findViewById(R.id.addCommentText);
        buttonAddComment = view.findViewById(R.id.addCommentButton);
        buttonAddComment.setOnClickListener(v -> {
            envoyerCommentaire();
            commentaire.getText().clear();


        });
        buttonEditElement = view.findViewById(R.id.editElementButton);
        buttonEditElement.setOnClickListener(v -> ((AppMainActivity) getActivity()).updateElement(idParent, idElt));
        ListView listView = view.findViewById(R.id.listeCommentaire);
        commentaireAdapter = new CommentaireAdapter(getActivity(), commentaires);
        commentaireAdapter.setIdParent(idParent);
        commentaireAdapter.setAppartient(appartient);
        commentaireAdapter.setIdElement(idElt);
        afficherCommentaires();
        listView.setAdapter(commentaireAdapter);
        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();
    }


    private void envoyerCommentaire() {
        onPreExecute();
        ElementsApi.addComment(idElt, commentaire.getText().toString(), response -> {
                    pg.dismiss();
                    afficherCommentaires();
                }
                , error -> {
            onError();
        });
    }

    private void afficherDonnees() {
        onPreExecute();
        ElementsApi.getElementByID(idElt, (Response.Listener<String>) response -> {
            try {
                JSONObject jsonObject = new JSONObject(response);
                Element elt = gson.fromJson(jsonObject.getJSONObject("data").toString(), Element.class);
                nomElt.setText(elt.getName());
                linkElt.setText(elt.getLink());
                eltAdresse.setText(elt.getAddress());
                eltPrice.setText(String.valueOf(elt.getPrice()));
                eltDescription.setText(elt.getDescription());
                eltStatus.setText(elt.getStatus());
                afficherBoutonsAppartient(elt.getStatus());
                pg.dismiss();
                buttonSupprimer.setVisibility(View.VISIBLE);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }, error -> {
            onError();
        });
    }

    private void afficherCommentaires() {
        ElementsApi.getElementCommentByID(idElt, (Response.Listener<String>) response -> {
            try {
                JSONObject jsonObject = new JSONObject(response);
                updateComments(Arrays.asList(gson.fromJson(jsonObject.getJSONObject("data").getJSONArray("list").toString(), Commentaire[].class)));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }, error -> {
            onError();
        });
    }

    private void updateComments(List<Commentaire> asList) {
        commentaires.clear();
        commentaires.addAll(asList);
        Log.d("log", String.valueOf(asList.size()));
        commentaireAdapter.notifyDataSetChanged();
    }

    private void afficherBoutonsAppartient(String status) {
        buttonReserver.setVisibility(View.GONE);
        buttonUrgent.setVisibility(View.GONE);
        buttonAcheter.setVisibility(View.GONE);
        buttonSupprimer.setVisibility(View.GONE);
        if (appartient) {
            if (!status.equals("purchased")) {
                buttonSupprimer.setVisibility(View.VISIBLE);
                buttonSupprimer.setOnClickListener(v -> supprimerElement());
            }
            if (status.equals("idea")) {
                buttonUrgent.setVisibility(View.VISIBLE);
                buttonUrgent.setOnClickListener(v -> updateElement("crush"));
            }
        } else if (status.equals("idea") || status.equals("crush")) {
            buttonReserver.setVisibility(View.VISIBLE);
            buttonReserver.setOnClickListener(v -> updateElement("reserved"));
        } else if (status.equals("reserved")) {
            updateElement("purchased");
        }
    }

    private void updateElement(String newElement) {
        ElementsApi.updateStatus(idElt, newElement, response -> afficherDonnees(), error -> {
            onError();
        });
    }

    private void supprimerElement() {
        onPreExecute();
        ElementsApi.deleteElement(idElt, response -> ((AppMainActivity) getActivity()).afficherContenuWishList(idParent, appartient), error -> {
            pg.dismiss();
            onError();
        });
    }

    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();
    }
}
