package com.m2sdl.undercooked;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.m2sdl.undercooked.domain.Review;
import com.m2sdl.undercooked.services.FirebaseBackendService;
import com.m2sdl.undercooked.services.PoiService;
import com.m2sdl.undercooked.services.UndercookedService;
import com.m2sdl.undercooked.utils.ActivityUtils;
import com.squareup.picasso.Picasso;

import org.mapsforge.core.model.LatLong;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class InfoActivity extends AppCompatActivity {

    public static final String ONLY_RESTAURANTS_POI = "midi-pyrenees.poi";
    private final FirebaseBackendService db = new FirebaseBackendService();
    private PoiService poiService;
    private Picasso picasso;

    private double latitude;
    private double longitude;

    public static Intent newIntent(Context context, LatLong position) {
        Intent intent = new Intent(context, InfoActivity.class);
        intent.putExtra(ActivityUtils.LATITUDE_KEY, position.latitude);
        intent.putExtra(ActivityUtils.LONGITUDE_KEY, position.longitude);
        return intent;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_info);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.info_page), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        poiService = new PoiService(getPoiDbPath());
        latitude = ActivityUtils.getExtraAsDouble(this, ActivityUtils.LATITUDE_KEY);
        longitude =  ActivityUtils.getExtraAsDouble(this, ActivityUtils.LONGITUDE_KEY);

        // synchronous call XD
        LinearLayout infoLayout = findViewById(R.id.informations);
        loadInfos(latitude, longitude, infoLayout);

        UndercookedService service = new UndercookedService();
        picasso = service.getPicassoWithAuth(this);
    }

    private String getPoiDbPath() {
        var medias = getExternalMediaDirs()[0];
        var ff = Arrays.stream(Objects.requireNonNull(medias.listFiles()))
                .filter(fi -> fi.getName().contains(ONLY_RESTAURANTS_POI))
                .findFirst();
        if (ff.isPresent()) {
            return ff.get().getAbsolutePath();
        } else {
            Toast.makeText(this, "Db file not found", Toast.LENGTH_SHORT).show();
            return "";
        }
    }


    private void loadInfos(double lat, double lon, LinearLayout layout) {
        var restaurant = poiService.getRestaurant(new LatLong(lat, lon));
        restaurant.addInfoToLayout(this, layout);
    }


    private void loadReviews(double lat, double lon, LinearLayout container) {
        db.getReviews(lat, lon, container, this::addReviewToUI);
    }

    private void addReviewToUI(Review review, LinearLayout container) {
        View reviewView = getLayoutInflater().inflate(R.layout.review_item, container, false);

        TextView text = reviewView.findViewById(R.id.reviewText);
        ImageView imageView = reviewView.findViewById(R.id.reviewImage);

        text.setText(review.getText());

        List<String> images = review.getImageUrls();
        if (images != null && !images.isEmpty()) {
            final int[] index = {0};
            picasso.load(images.get(index[0])).into(imageView);
            imageView.setOnClickListener(v -> {
                index[0] = (index[0] + 1) % images.size();
                picasso.load(images.get(index[0])).into(imageView);
            });
        } else {
            imageView.setVisibility(View.GONE);
        }

        container.addView(reviewView);
    }

    public void startBookingActivity(View view) {
        Intent intent = new Intent(this, BookingActivity.class);
        intent.putExtra(ActivityUtils.LATITUDE_KEY, ActivityUtils.getExtraAsDouble(this, ActivityUtils.LATITUDE_KEY));
        intent.putExtra(ActivityUtils.LONGITUDE_KEY, ActivityUtils.getExtraAsDouble(this, ActivityUtils.LONGITUDE_KEY));
        startActivity(intent);
    }

    public void startReviewActivity(View view) {
        Intent intent = new Intent(this, ReviewActivity.class);
        intent.putExtra("lat", latitude);
        intent.putExtra("lon", longitude);

        startActivity(intent);
    }

    public void startViewBookingsActivity(View view) {
        Intent intent = new Intent(this, ViewBookingsActivity.class);
        intent.putExtra("lat", latitude);
        intent.putExtra("lon", longitude);

        startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        LinearLayout reviewContainer = findViewById(R.id.review_container);
        reviewContainer.removeAllViews();
        loadReviews(latitude, longitude, reviewContainer);
    }

    @Override
    protected void onDestroy() {
        poiService.finish();
        super.onDestroy();
    }
}
