package com.example.kasirapp

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.kasirapp.data.AppDatabase
import com.example.kasirapp.data.TransactionWithItems
import kotlinx.coroutines.launch
import java.text.NumberFormat
import java.text.SimpleDateFormat
import java.util.*

class SalesReportActivity : AppCompatActivity() {

    private lateinit var rvTransactions: RecyclerView
    private lateinit var transactionAdapter: TransactionAdapter
    private lateinit var tvTotalSales: TextView
    private lateinit var tvTotalTransactions: TextView
    private lateinit var tvNoTransactions: TextView
    private lateinit var spinnerDateFilter: Spinner

    private val db by lazy { AppDatabase.getDatabase(this) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sales_report)

        initializeViews()
        setupFilterSpinner()
        
        rvTransactions.layoutManager = LinearLayoutManager(this)
        transactionAdapter = TransactionAdapter(emptyList(), this)
        rvTransactions.adapter = transactionAdapter

        // Initial load with default filter (All)
        loadTransactionReport(FilterOption.ALL)
    }

    private fun initializeViews() {
        rvTransactions = findViewById(R.id.rv_transactions)
        tvTotalSales = findViewById(R.id.tv_total_sales)
        tvTotalTransactions = findViewById(R.id.tv_total_transactions)
        tvNoTransactions = findViewById(R.id.tv_no_transactions)
        spinnerDateFilter = findViewById(R.id.spinner_date_filter)
    }

    private fun setupFilterSpinner() {
        val filterOptions = FilterOption.values().map { it.displayName }
        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, filterOptions)
        spinnerDateFilter.adapter = adapter

        spinnerDateFilter.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                val selectedFilter = FilterOption.values()[position]
                loadTransactionReport(selectedFilter)
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }
    }

    private fun loadTransactionReport(filter: FilterOption) {
        lifecycleScope.launch {
            val (startDate, endDate) = filter.getStartAndEndTimestamps()
            
            val transactions = if (filter == FilterOption.ALL) {
                db.transactionDao().getTransactionsWithItems()
            } else {
                db.transactionDao().getTransactionsWithItemsInRange(startDate, endDate)
            }

            updateUI(transactions)
        }
    }

    private fun updateUI(transactions: List<TransactionWithItems>) {
        if (transactions.isEmpty()) {
            tvNoTransactions.visibility = View.VISIBLE
            rvTransactions.visibility = View.GONE
            tvTotalSales.text = "Total Penjualan: ${formatCurrency(0)}"
            tvTotalTransactions.text = "Total Transaksi: 0"
        } else {
            tvNoTransactions.visibility = View.GONE
            rvTransactions.visibility = View.VISIBLE

            val totalSales = transactions.sumOf { it.transaction.total }
            val totalTransactions = transactions.size

            tvTotalSales.text = "Total Penjualan: ${formatCurrency(totalSales)}"
            tvTotalTransactions.text = "Total Transaksi: $totalTransactions"

            transactionAdapter.updateData(transactions)
        }
    }

    private fun formatCurrency(amount: Int): String {
        return NumberFormat.getCurrencyInstance(Locale("id", "ID")).format(amount.toLong())
    }

    enum class FilterOption(val displayName: String) {
        TODAY("Hari Ini"),
        LAST_7_DAYS("7 Hari Terakhir"),
        THIS_MONTH("Bulan Ini"),
        ALL("Semua");

        fun getStartAndEndTimestamps(): Pair<Long, Long> {
            val calendar = Calendar.getInstance()
            val endDate = calendar.timeInMillis

            when (this) {
                TODAY -> {
                    calendar.set(Calendar.HOUR_OF_DAY, 0)
                    calendar.set(Calendar.MINUTE, 0)
                    calendar.set(Calendar.SECOND, 0)
                    calendar.set(Calendar.MILLISECOND, 0)
                }
                LAST_7_DAYS -> {
                    calendar.add(Calendar.DAY_OF_YEAR, -6) // Include today, so go back 6 days
                    calendar.set(Calendar.HOUR_OF_DAY, 0)
                    calendar.set(Calendar.MINUTE, 0)
                }
                THIS_MONTH -> {
                    calendar.set(Calendar.DAY_OF_MONTH, 1)
                    calendar.set(Calendar.HOUR_OF_DAY, 0)
                    calendar.set(Calendar.MINUTE, 0)
                }
                ALL -> {
                    return Pair(0, Long.MAX_VALUE)
                }
            }
            val startDate = calendar.timeInMillis
            return Pair(startDate, endDate)
        }
    }

    class TransactionAdapter(private var transactionList: List<TransactionWithItems>, private val context: Context) :
        RecyclerView.Adapter<TransactionAdapter.TransactionViewHolder>() {

        fun updateData(newTransactions: List<TransactionWithItems>) {
            transactionList = newTransactions
            notifyDataSetChanged()
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TransactionViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_transaction, parent, false)
            return TransactionViewHolder(view)
        }

        override fun onBindViewHolder(holder: TransactionViewHolder, position: Int) {
            holder.bind(transactionList[position], context)
        }

        override fun getItemCount(): Int = transactionList.size

        class TransactionViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            private val tvTransactionId: TextView = itemView.findViewById(R.id.tv_transaction_id)
            private val tvTransactionTotal: TextView = itemView.findViewById(R.id.tv_transaction_total)
            private val tvTransactionDate: TextView = itemView.findViewById(R.id.tv_transaction_date)

            fun bind(transactionWithItems: TransactionWithItems, context: Context) {
                val transaction = transactionWithItems.transaction
                tvTransactionId.text = "ID Transaksi: ${transaction.id}"
                tvTransactionTotal.text = "Total: ${NumberFormat.getCurrencyInstance(Locale("id", "ID")).format(transaction.total.toLong())}"
                val sdf = SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.getDefault())
                tvTransactionDate.text = "Tanggal: ${sdf.format(Date(transaction.timestamp))}"

                itemView.setOnClickListener {
                    val intent = Intent(context, TransactionDetailActivity::class.java).apply {
                        putExtra("TRANSACTION_ID", transaction.id)
                    }
                    context.startActivity(intent)
                }
            }
        }
    }
}
