package com.example.bdkipoc;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.WindowManager;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.android.material.button.MaterialButton;

import com.example.bdkipoc.transaction.CreateTransactionActivity;
import com.example.bdkipoc.kredit.CreditCardActivity;

public class MainActivity extends AppCompatActivity {

    private boolean isExpanded = false; // False = showing only 9 main menus, True = showing all 15 menus
    private MaterialButton btnLainnya;

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Enable hardware acceleration for smoother scrolling
        getWindow().setFlags(
            WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
            WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED
        );
        
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(android.R.id.content), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // Initialize views
        btnLainnya = findViewById(R.id.btn_lainnya);

        // Check if we're returning from a completed transaction
        checkTransactionCompletion();

        // Setup initial state - 9 main menus visible, 6 dummy menus hidden
        setupInitialMenuState();

        // Setup menu listeners
        setupMenuListeners();
    }

    private void setupInitialMenuState() {
        // 9 main menus should always be visible
        CardView cardBantuan = findViewById(R.id.card_bantuan);
        CardView cardInfoToko = findViewById(R.id.card_info_toko);
        
        if (cardBantuan != null) {
            cardBantuan.setVisibility(View.VISIBLE);
        }
        if (cardInfoToko != null) {
            cardInfoToko.setVisibility(View.VISIBLE);
        }

        // 6 dummy menus should be hidden initially
        CardView[] dummyCards = {
            findViewById(R.id.card_dummy_menu_1),
            findViewById(R.id.card_dummy_menu_2),
            findViewById(R.id.card_dummy_menu_3),
            findViewById(R.id.card_dummy_menu_4),
            findViewById(R.id.card_dummy_menu_5),
            findViewById(R.id.card_dummy_menu_6)
        };

        for (CardView card : dummyCards) {
            if (card != null) {
                card.setVisibility(View.GONE);
            }
        }

        // Set initial button text
        isExpanded = false;
        btnLainnya.setText("Lainnya");
    }

    private void checkTransactionCompletion() {
        Intent intent = getIntent();
        if (intent != null) {
            boolean transactionCompleted = intent.getBooleanExtra("transaction_completed", false);
            String transactionAmount = intent.getStringExtra("transaction_amount");
            
            if (transactionCompleted) {
                if (transactionAmount != null) {
                    Toast.makeText(this, "Transaksi berhasil! Jumlah: Rp " + formatCurrency(transactionAmount), Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(this, "Transaksi berhasil diselesaikan!", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    private String formatCurrency(String amount) {
        try {
            long amountValue = Long.parseLong(amount);
            return String.format("%,d", amountValue).replace(',', '.');
        } catch (NumberFormatException e) {
            return amount;
        }
    }

    private void setupMenuListeners() {
        // Card IDs to set up listeners - Total 15 menu items
        int[] cardIds = {
            // Row 1 (Always visible - 3 items)
            R.id.card_kartu_kredit,
            R.id.card_kartu_debit,
            R.id.card_qris,
            // Row 2 (Always visible - 3 items)
            R.id.card_uang_elektronik,
            R.id.card_cetak_ulang,
            R.id.card_settlement,
            // Row 3 (Always visible - 3 items)
            R.id.card_histori,
            R.id.card_bantuan,
            R.id.card_info_toko,
            // Row 4 (Hidden initially - 3 items)
            R.id.card_dummy_menu_1,
            R.id.card_dummy_menu_2,
            R.id.card_dummy_menu_3,
            // Row 5 (Hidden initially - 3 items)
            R.id.card_dummy_menu_4,
            R.id.card_dummy_menu_5,
            R.id.card_dummy_menu_6
        };

        // Set up click listeners for all cards
        for (int cardId : cardIds) {
            CardView cardView = findViewById(cardId);
            if (cardView != null) {
                cardView.setOnClickListener(v -> {
                    if (cardId == R.id.card_kartu_kredit) {
                        startActivity(new Intent(MainActivity.this, CreateTransactionActivity.class));
                    } else if (cardId == R.id.card_kartu_debit) {
                        startActivity(new Intent(MainActivity.this, PaymentActivity.class));
                    } else if (cardId == R.id.card_qris) {
                        startActivity(new Intent(MainActivity.this, QrisActivity.class));
                    } else if (cardId == R.id.card_uang_elektronik) {
                        startActivity(new Intent(MainActivity.this, PaymentActivity.class));
                    } else if (cardId == R.id.card_cetak_ulang) {
                        startActivity(new Intent(MainActivity.this, TransactionActivity.class));
                    } else if (cardId == R.id.card_settlement) {
                        Toast.makeText(this, "Settlement - Coming Soon", Toast.LENGTH_SHORT).show();
                    } else if (cardId == R.id.card_histori) {
                        Toast.makeText(this, "Histori - Coming Soon", Toast.LENGTH_SHORT).show();
                    } else if (cardId == R.id.card_bantuan) {
                        Toast.makeText(this, "Bantuan - Coming Soon", Toast.LENGTH_SHORT).show();
                    } else if (cardId == R.id.card_info_toko) {
                        Toast.makeText(this, "Info Toko - Coming Soon", Toast.LENGTH_SHORT).show();
                    } else if (cardId == R.id.card_dummy_menu_1) {
                        Toast.makeText(this, "Dummy Menu 1 - Coming Soon", Toast.LENGTH_SHORT).show();
                    } else if (cardId == R.id.card_dummy_menu_2) {
                        Toast.makeText(this, "Dummy Menu 2 - Coming Soon", Toast.LENGTH_SHORT).show();
                    } else if (cardId == R.id.card_dummy_menu_3) {
                        Toast.makeText(this, "Dummy Menu 3 - Coming Soon", Toast.LENGTH_SHORT).show();
                    } else if (cardId == R.id.card_dummy_menu_4) {
                        Toast.makeText(this, "Dummy Menu 4 - Coming Soon", Toast.LENGTH_SHORT).show();
                    } else if (cardId == R.id.card_dummy_menu_5) {
                        Toast.makeText(this, "Dummy Menu 5 - Coming Soon", Toast.LENGTH_SHORT).show();
                    } else if (cardId == R.id.card_dummy_menu_6) {
                        Toast.makeText(this, "Dummy Menu 6 - Coming Soon", Toast.LENGTH_SHORT).show();
                    } else {
                        // Fallback for any other cards
                        Toast.makeText(this, "Menu Diklik: " + getResources().getResourceEntryName(cardId), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }

        // Get references to ONLY the dummy cards that need to be toggled
        CardView[] toggleableCards = {
            findViewById(R.id.card_dummy_menu_1),
            findViewById(R.id.card_dummy_menu_2),
            findViewById(R.id.card_dummy_menu_3),
            findViewById(R.id.card_dummy_menu_4),
            findViewById(R.id.card_dummy_menu_5),
            findViewById(R.id.card_dummy_menu_6)
        };

        // Set up "Lainnya" button click listener
        btnLainnya.setOnClickListener(v -> {
            isExpanded = !isExpanded;
            
            if (isExpanded) {
                // Show the 6 dummy menus with animation
                for (CardView card : toggleableCards) {
                    if (card != null) {
                        card.setVisibility(View.VISIBLE);
                        card.setAlpha(0f);
                        card.animate()
                            .alpha(1f)
                            .setDuration(300)
                            .setInterpolator(new AccelerateDecelerateInterpolator())
                            .start();
                    }
                }
                btnLainnya.setText("Tampilkan Lebih Sedikit");
            } else {
                // Hide the 6 dummy menus with animation
                for (CardView card : toggleableCards) {
                    if (card != null) {
                        card.animate()
                            .alpha(0f)
                            .setDuration(300)
                            .setInterpolator(new AccelerateDecelerateInterpolator())
                            .withEndAction(() -> card.setVisibility(View.GONE))
                            .start();
                    }
                }
                btnLainnya.setText("Lainnya");
            }
        });

        // Set up scan dan bayar card click listener
        LinearLayout scanBayarContent = findViewById(R.id.scan_bayar_content);
        if (scanBayarContent != null) {
            scanBayarContent.setOnClickListener(v -> {
                // Navigate to QRIS payment activity
                startActivity(new Intent(MainActivity.this, QrisActivity.class));
            });
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        // Check for transaction completion when returning to MainActivity
        checkTransactionCompletion();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // Clear any transaction completion flags to avoid repeated messages
        getIntent().removeExtra("transaction_completed");
        getIntent().removeExtra("transaction_amount");
    }
}