package com.kolobochki.memory;

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

import androidx.activity.OnBackPressedCallback;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.appcompat.app.AppCompatActivity;
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_task4 extends Fragment {

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

    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 ImageView[][] cards = new ImageView[2][2];
    private int[][] cardValues = new int[2][2];
    private int changedRow = -1, changedCol = -1;
    private int lives = 3;
    private int round = 1;
    private Handler handler = new Handler();
    private Random random = new Random();
    private TextView roundTextView;
    private TextView livesTextView;
    private GridLayout gridLayout;

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

    public static fragment_task4 newInstance(String param1, String param2) {
        fragment_task4 fragment = new fragment_task4();
        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("Упражнение 4");
            }
        }
    }

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

        gridLayout = view.findViewById(R.id.grid_layout);
        cards[0][0] = view.findViewById(R.id.card00);
        cards[0][1] = view.findViewById(R.id.card01);
        cards[1][0] = view.findViewById(R.id.card10);
        cards[1][1] = view.findViewById(R.id.card11);

        roundTextView = view.findViewById(R.id.round_text);
        livesTextView = view.findViewById(R.id.lives_text);

        gridLayout.setAlignmentMode(GridLayout.ALIGN_BOUNDS);
        gridLayout.setUseDefaultMargins(true);

        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                final int row = i;
                final int col = j;
                cards[i][j].setOnClickListener(v -> onCardClicked(row, col));
            }
        }

        startNewRound();

        return view;
    }

    private void startNewRound() {
        if (!isAdded()) return;

        roundTextView.setText("Раунд: " + round);
        updateLivesDisplay();

        List<Integer> availableImages = new ArrayList<>();
        for (int i = 1; i <= 6; i++) {
            availableImages.add(i);
        }
        Collections.shuffle(availableImages);

        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                int index = i * 2 + j;
                if (index < availableImages.size()) {
                    cardValues[i][j] = availableImages.get(index);
                    setCardImage(i, j, "tile" + cardValues[i][j]);
                }
            }
        }

        handler.postDelayed(() -> {
            // Flip all cards to back
            for (int i = 0; i < 2; i++) {
                for (int j = 0; j < 2; j++) {
                    setCardImage(i, j, "tile_back");
                }
            }

            handler.postDelayed(() -> {
                changedRow = random.nextInt(2);
                changedCol = random.nextInt(2);

                int newImage;
                List<Integer> currentImages = new ArrayList<>();
                for (int i = 0; i < 2; i++) {
                    for (int j = 0; j < 2; j++) {
                        if (!currentImages.contains(cardValues[i][j])) {
                            currentImages.add(cardValues[i][j]);
                        }
                    }
                }

                do {
                    newImage = random.nextInt(6) + 1;
                } while (currentImages.contains(newImage));

                cardValues[changedRow][changedCol] = newImage;

                for (int i = 0; i < 2; i++) {
                    for (int j = 0; j < 2; j++) {
                        setCardImage(i, j, "tile" + cardValues[i][j]);
                    }
                }

                setCardsClickable(true);

            }, 750);
        }, 1000);
    }


    private void onCardClicked(int row, int col) {
        if (!isAdded()) return;

        setCardsClickable(false);

        if (row == changedRow && col == changedCol) {
            round++;
            checkAndUpdateRecord(round);

            handler.postDelayed(() -> {
                if (isAdded()) startNewRound();
            }, 1000);
        } else {
            lives--;
            updateLivesDisplay();

            if (lives <= 0) {
                gameOver();
            } else {
                cards[changedRow][changedCol].setImageResource(
                        getResourceId("tile" + cardValues[changedRow][changedCol] + "_highlight")
                );

                handler.postDelayed(() -> {
                    if (!isAdded()) return;
                    setCardImage(changedRow, changedCol, "tile" + cardValues[changedRow][changedCol]);
                    startNewRound();
                }, 1000);
            }
        }
    }

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

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

    private void setCardImage(int row, int col, String imageName) {
        cards[row][col].setImageResource(getResourceId(imageName));
    }

    private int getResourceId(String name) {
        return getResources().getIdentifier(name, "drawable", requireContext().getPackageName());
    }

    private void setCardsClickable(boolean clickable) {
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                cards[i][j].setClickable(clickable);
            }
        }
    }

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

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

    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() {
        if (getView() == null) return;

        NavController navController = Navigation.findNavController(requireView());
        navController.popBackStack();
    }
}