package com.kolobochki.memory;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.kolobochki.memory.AppDatabase;
import com.kolobochki.memory.LevelRecord;
import com.kolobochki.memory.LevelRecordDao;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class fragment_records extends Fragment {

    private RecyclerView recyclerView;
    private StatsAdapter adapter;
    private LevelRecordDao levelRecordDao;
    private Executor executor = Executors.newSingleThreadExecutor();

    private OnBackPressedCallback backPressedCallback;
    private String previousTitle;

    // Названия уровней
    private final String[] levelNames = {
            "Найти пары",
            "Саймон говорит",
            "Числовая матрица",
            "Найти лишнее"
    };

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

        // Инициализация базы данных
        AppDatabase db = AppDatabase.getDatabase(requireContext().getApplicationContext());
        levelRecordDao = db.levelRecordDao();

        if (getActivity() instanceof AppCompatActivity) {
            ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
            if (actionBar != null) {
                actionBar.setTitle("Мой прогресс");
            }
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_records, container, false);

        recyclerView = view.findViewById(R.id.stats_recycler);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        adapter = new StatsAdapter();
        recyclerView.setAdapter(adapter);

        loadStats();

        return view;
    }

    private void loadStats() {
        executor.execute(() -> {
            try {
                List<LevelRecord> records = levelRecordDao.getAllRecords();

                // Если записей нет - создаем пустые
                if (records == null || records.isEmpty()) {
                    for (int i = 1; i <= 4; i++) {
                        LevelRecord record = new LevelRecord(i, 0, 0);
                        levelRecordDao.insert(record);
                    }
                    records = levelRecordDao.getAllRecords();
                }

                List<LevelRecord> finalRecords = records;
                requireActivity().runOnUiThread(() -> {
                    if (adapter != null) {
                        adapter.setRecords(finalRecords);
                    }
                });
            } catch (Exception e) {
                requireActivity().runOnUiThread(() ->
                        Toast.makeText(requireContext(), "Ошибка загрузки данных", Toast.LENGTH_SHORT).show()
                );
            }
        });
    }

    // Адаптер для RecyclerView
    private class StatsAdapter extends RecyclerView.Adapter<StatsAdapter.StatsViewHolder> {

        private List<LevelRecord> records;

        public void setRecords(List<LevelRecord> records) {
            this.records = records;
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public StatsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_level_stat, parent, false);
            return new StatsViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull StatsViewHolder holder, int position) {
            LevelRecord record = records.get(position);
            holder.levelName.setText(levelNames[record.levelId - 1]);
            holder.bestScore.setText("Рекорд: " + record.bestScore);
            holder.attempts.setText("Попыток: " + record.attemptsCount);
        }

        @Override
        public int getItemCount() {
            return records != null ? records.size() : 0;
        }

        class StatsViewHolder extends RecyclerView.ViewHolder {
            TextView levelName, bestScore, attempts;

            StatsViewHolder(View itemView) {
                super(itemView);
                levelName = itemView.findViewById(R.id.level_name);
                bestScore = itemView.findViewById(R.id.best_score);
                attempts = itemView.findViewById(R.id.attempts_count);
            }
        }
    }
}