package com.example.myapplication;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity5 extends AppCompatActivity {

    private DatabaseHelper db;
    private ListView listViewFavs;
    private LinearLayout llFavEmptyState;
    private Button btnBack;

    private ArrayList<Integer> ids = new ArrayList<>();
    private ArrayList<String> adlar = new ArrayList<>();
    private ArrayList<String> mallar = new ArrayList<>();
    private ArrayList<String> yaplar = new ArrayList<>();
    private ArrayList<String> kategoriler = new ArrayList<>();
    private ArrayList<String> resimler = new ArrayList<>();
    private ArrayList<Integer> ekleyenIds = new ArrayList<>();
    private ArrayList<String> ekleyenAdlar = new ArrayList<>();
    private ArrayList<Integer> favoriler = new ArrayList<>();

    private CustomFavAdapter adapter;
    private ExecutorService executorService = Executors.newFixedThreadPool(4);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Oturum kontrolü
        SharedPreferences pref = getSharedPreferences("UserSession", Context.MODE_PRIVATE);
        if (!pref.contains("userId")) {
            Intent intent = new Intent(MainActivity5.this, LoginActivity.class);
            startActivity(intent);
            finish();
            return;
        }

        setContentView(R.layout.activity_main5);

        db = new DatabaseHelper(this);
        listViewFavs = findViewById(R.id.liste_view_favori);
        llFavEmptyState = findViewById(R.id.llFavEmptyState);
        btnBack = findViewById(R.id.btnFavsBack);

        adapter = new CustomFavAdapter();
        listViewFavs.setAdapter(adapter);

        verileriYukle();

        btnBack.setOnClickListener(v -> finish());
    }

    @Override
    protected void onResume() {
        super.onResume();
        verileriYukle();
    }

    private void verileriYukle() {
        ids.clear();
        adlar.clear();
        mallar.clear();
        yaplar.clear();
        kategoriler.clear();
        resimler.clear();
        ekleyenIds.clear();
        ekleyenAdlar.clear();
        favoriler.clear();

        Cursor c = db.favorileriGetir();
        if (c != null) {
            while (c.moveToNext()) {
                // columns: id (0), ad (1), malzeme (2), yapilis (3), kategori (4), resim_url (5), ekleyen_id (6), ekleyen_adi (7), favori (8)
                ids.add(c.getInt(0));
                adlar.add(c.getString(1));
                mallar.add(c.getString(2));
                yaplar.add(c.getString(3));
                kategoriler.add(c.getString(4));
                resimler.add(c.getString(5));
                ekleyenIds.add(c.getInt(6));
                ekleyenAdlar.add(c.getString(7));
                favoriler.add(c.getInt(8));
            }
            c.close();
        }

        if (adlar.isEmpty()) {
            llFavEmptyState.setVisibility(View.VISIBLE);
            listViewFavs.setVisibility(View.GONE);
        } else {
            llFavEmptyState.setVisibility(View.GONE);
            listViewFavs.setVisibility(View.VISIBLE);
        }

        adapter.notifyDataSetChanged();
    }

    private void loadRemoteImage(String urlString, ImageView imageView) {
        if (urlString == null || urlString.trim().isEmpty()) {
            imageView.setVisibility(View.GONE);
            return;
        }

        imageView.setTag(urlString);

        executorService.execute(() -> {
            try {
                URL url = new URL(urlString);
                InputStream is = url.openStream();
                Bitmap bmp = BitmapFactory.decodeStream(is);
                new Handler(Looper.getMainLooper()).post(() -> {
                    if (urlString.equals(imageView.getTag())) {
                        if (bmp != null) {
                            imageView.setImageBitmap(bmp);
                            imageView.setVisibility(View.VISIBLE);
                        } else {
                            imageView.setVisibility(View.GONE);
                        }
                    }
                });
            } catch (Exception e) {
                new Handler(Looper.getMainLooper()).post(() -> {
                    if (urlString.equals(imageView.getTag())) {
                        imageView.setVisibility(View.GONE);
                    }
                });
            }
        });
    }

    class CustomFavAdapter extends BaseAdapter {

        @Override public int getCount() { return adlar.size(); }
        @Override public Object getItem(int i) { return null; }
        @Override public long getItemId(int i) { return 0; }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.list_item_layout, null);
            }

            TextView txtAd = convertView.findViewById(R.id.txtYemekAdi);
            TextView txtKategori = convertView.findViewById(R.id.txtYemekKategori);
            TextView txtEkleyen = convertView.findViewById(R.id.txtYemekEkleyen);
            TextView txtEmoji = convertView.findViewById(R.id.txtCategoryEmoji);
            ImageView imgPoster = convertView.findViewById(R.id.imgRecipePoster);
            TextView btnFav = convertView.findViewById(R.id.btnFavoriEkle);

            txtAd.setText(adlar.get(position));
            
            String category = kategoriler.get(position);
            txtKategori.setText("Kategori: " + category);
            
            String ekleyen = ekleyenAdlar.get(position);
            txtEkleyen.setText("Şef: " + (ekleyen == null ? "Bilinmeyen Şef" : ekleyen));

            txtEmoji.setText(MainActivity.getEmojiForCategory(category));

            String imageUrl = resimler.get(position);
            imgPoster.setVisibility(View.GONE);
            if (imageUrl != null && !imageUrl.trim().isEmpty()) {
                loadRemoteImage(imageUrl, imgPoster);
            }

            // Favoriler ekranında hepsi favoridir (❤️)
            btnFav.setText("❤️");

            btnFav.setOnClickListener(v -> {
                // Favoriden çıkar (favori = 0 yap)
                db.favoriGuncelle(ids.get(position), 0);
                Toast.makeText(MainActivity5.this, adlar.get(position) + " favorilerden çıkarıldı! 🤍", Toast.LENGTH_SHORT).show();
                verileriYukle();
            });

            convertView.setOnClickListener(v -> {
                Intent intent = new Intent(MainActivity5.this, MainActivity4.class);
                intent.putExtra("pId", ids.get(position));
                intent.putExtra("pAd", adlar.get(position));
                intent.putExtra("pMal", mallar.get(position));
                intent.putExtra("pYap", yaplar.get(position));
                intent.putExtra("pKategori", category);
                intent.putExtra("pResimUrl", imageUrl);
                intent.putExtra("pEkleyen", ekleyen);
                startActivity(intent);
            });

            return convertView;
        }
    }
}