package com.kolobochki.memory;

import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.OnBackPressedCallback;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class fragment_task3 extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final int LEVEL_ID = 3;

    private AppDatabase database;
    private LevelRecordDao levelRecordDao;
    private Executor executor = Executors.newSingleThreadExecutor();

    private String mParam1;
    private String mParam2;
    private String previousTitle;
    private boolean isGameComplete = false;

    private GridLayout gridLayout;
    private TextView roundTextView;
    private TextView livesTextView;
    private List<Integer> sequence = new ArrayList<>();
    private List<Integer> userSequence = new ArrayList<>();
    private int currentRound = 1;
    private int lives = 3;
    private int rows = 3;
    private int cols = 3;
    private final int SHOW_TIME = 4500;

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

    public static fragment_task3 newInstance(String param1, String param2) {
        fragment_task3 fragment = new fragment_task3();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

        database = AppDatabase.getDatabase(requireContext());
        levelRecordDao = database.levelRecordDao();

        executor.execute(() -> {
            LevelRecord existingRecord = levelRecordDao.getRecordForLevel(LEVEL_ID);
            if (existingRecord != null) {
                existingRecord.attemptsCount++;
                levelRecordDao.update(existingRecord);
            } else {
                LevelRecord newRecord = new LevelRecord(LEVEL_ID, 0, 1);
                levelRecordDao.insert(newRecord);
            }
        });

        OnBackPressedCallback backPressedCallback = new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                if (!isGameComplete) {
                    showExitConfirmationDialog();
                } else {
                    setEnabled(false);
                    navigateHome();
                }
            }
        };
        requireActivity().getOnBackPressedDispatcher().addCallback(this, backPressedCallback);

        if (getActivity() instanceof AppCompatActivity) {
            ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
            if (actionBar != null) {
                actionBar.setTitle("Упражнение 3");
            }
        }
    }

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

        gridLayout = view.findViewById(R.id.gridLayout);
        roundTextView = view.findViewById(R.id.roundTextView);
        livesTextView = view.findViewById(R.id.livesTextView);

        setupGame();

        return view;
    }

    private void setupGame() {
        sequence.clear();
        userSequence.clear();
        gridLayout.removeAllViews();

        gridLayout.setRowCount(rows);
        gridLayout.setColumnCount(cols);

        DisplayMetrics displayMetrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int screenWidth = displayMetrics.widthPixels;
        int cellSize = (int) (screenWidth * 0.8 / cols);

        int totalCells = rows * cols;
        for (int i = 1; i <= totalCells; i++) {
            sequence.add(i);
        }

        Collections.shuffle(sequence);

        for (int i = 0; i < totalCells; i++) {
            Button button = new Button(getContext());
            button.setTag(sequence.get(i));
            button.setText(String.valueOf(sequence.get(i)));
            button.setTextSize(24);
            //button.setBackgroundResource(R.drawable.cell_background);

            GridLayout.LayoutParams params = new GridLayout.LayoutParams();
            params.width = cellSize;
            params.height = cellSize;
            params.rowSpec = GridLayout.spec(i / cols, 1f);
            params.columnSpec = GridLayout.spec(i % cols, 1f);
            params.setMargins(4, 4, 4, 4);

            button.setLayoutParams(params);
            gridLayout.addView(button);
        }

        updateUI();

        new Handler().postDelayed(this::hideNumbers, SHOW_TIME);
    }

    private void hideNumbers() {
        for (int i = 0; i < gridLayout.getChildCount(); i++) {
            Button button = (Button) gridLayout.getChildAt(i);
            button.setText("");
            button.setOnClickListener(v -> {
                Button clickedButton = (Button) v;
                int number = (int) clickedButton.getTag();
                userSequence.add(number);
                clickedButton.setText(String.valueOf(number));

                if (userSequence.size() == sequence.size()) {
                    checkSequence();
                }
            });
        }
    }

    private void checkSequence() {
        boolean isCorrect = true;
        for (int i = 0; i < sequence.size(); i++) {
            if (!sequence.get(i).equals(userSequence.get(i))) {
                isCorrect = false;
                break;
            }
        }

        if (isCorrect) {
            currentRound++;
            // Проверяем и обновляем рекорд сразу при увеличении раунда
            checkAndUpdateRecord(currentRound);

            Toast.makeText(getContext(), "Правильно! Раунд " + currentRound, Toast.LENGTH_SHORT).show();
            new Handler().postDelayed(this::setupGame, 1500);
        } else {
            lives--;
            if (lives <= 0) {
                gameOver();
            } else {
                Toast.makeText(getContext(), "Ошибка! Осталось жизней: " + lives, Toast.LENGTH_SHORT).show();
                new Handler().postDelayed(this::setupGame, 1500);
            }
        }
    }

    private void checkAndUpdateRecord(int currentRound) {
        executor.execute(() -> {
            LevelRecord record = levelRecordDao.getRecordForLevel(LEVEL_ID);
            if (record != null && currentRound > record.bestScore) {
                record.bestScore = currentRound;
                levelRecordDao.update(record);
                showNewRecordToast(currentRound);
            }
        });
    }

    private void showNewRecordToast(int round) {
        requireActivity().runOnUiThread(() -> {
            Toast.makeText(requireContext(),
                    "Новый рекорд: " + round + " раундов", Toast.LENGTH_SHORT).show();
        });
    }

    private void gameOver() {
        isGameComplete = true;
        new AlertDialog.Builder(requireContext())
                .setTitle("Игра окончена")
                .setMessage("Вы прошли " + (currentRound - 1) + " раундов")
                .setPositiveButton("OK", (dialog, which) -> navigateHome())
                .setCancelable(false)
                .show();
    }

    private void updateUI() {
        roundTextView.setText("Раунд: " + currentRound);

        StringBuilder hearts = new StringBuilder();
        for (int i = 0; i < 3; i++) {
            hearts.append(i < lives ? "❤️" : "");
        }
        livesTextView.setText(hearts.toString());
    }

    private void showExitConfirmationDialog() {
        new AlertDialog.Builder(requireContext())
                .setTitle("Закончить упражнение?")
                .setMessage("Вы точно хотите закончить упражнение?")
                .setPositiveButton("Да", (dialog, which) -> {
                    NavController navController = Navigation.findNavController(requireView());
                    navController.popBackStack();
                })
                .setNegativeButton("Нет", null)
                .show();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getActivity() != null && ((AppCompatActivity)getActivity()).getSupportActionBar() != null) {
            ((AppCompatActivity)getActivity()).getSupportActionBar().hide();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (getActivity() != null && ((AppCompatActivity)getActivity()).getSupportActionBar() != null) {
            ((AppCompatActivity)getActivity()).getSupportActionBar().show();
        }

        if (getActivity() instanceof AppCompatActivity) {
            ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
            if (actionBar != null && previousTitle != null) {
                actionBar.setTitle(previousTitle);
            }
        }
    }

    private void navigateHome() {
        NavController navController = Navigation.findNavController(requireView());
        navController.popBackStack();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (database != null) {
            database.close();
        }
    }
}