package com.rugvedsarika.areacalc

import android.content.Context
import android.content.SharedPreferences
import org.json.JSONArray
import org.json.JSONObject

data class HistoryItem(
    val input: String,
    val fromUnit: String,
    val toUnit: String,
    val result: String,
    val timestamp: Long = System.currentTimeMillis()
)

class HistoryManager(private val context: Context) {
    private val prefs: SharedPreferences = context.getSharedPreferences("conversion_history", Context.MODE_PRIVATE)
    private val historyKey = "history_list"

    fun saveConversion(item: HistoryItem) {
        val list = getHistory().toMutableList()
        // Avoid duplicates at the top
        if (list.isNotEmpty() && list[0].input == item.input && list[0].fromUnit == item.fromUnit && list[0].toUnit == item.toUnit) {
            return
        }
        list.add(0, item)
        if (list.size > 20) {
            list.removeAt(list.size - 1)
        }
        saveList(list)
    }

    fun getHistory(): List<HistoryItem> {
        val jsonString = prefs.getString(historyKey, null) ?: return emptyList()
        val list = mutableListOf<HistoryItem>()
        try {
            val jsonArray = JSONArray(jsonString)
            for (i in 0 until jsonArray.length()) {
                val obj = jsonArray.getJSONObject(i)
                list.add(HistoryItem(
                    input = obj.getString("input"),
                    fromUnit = obj.getString("fromUnit"),
                    toUnit = obj.getString("toUnit"),
                    result = obj.getString("result"),
                    timestamp = obj.optLong("timestamp", System.currentTimeMillis())
                ))
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return list
    }
    
    fun clearHistory() {
        prefs.edit().remove(historyKey).apply()
    }

    fun addDummyDataIfEmpty() {
        if (getHistory().isNotEmpty()) return

        val now = System.currentTimeMillis()
        val dummyItems = listOf(
            HistoryItem(
                input = "1",
                fromUnit = context.getString(AreaUnit.ACRE.nameResId),
                toUnit = context.getString(AreaUnit.SQUARE_METER.nameResId),
                result = "4046.86",
                timestamp = now - 1000 * 60 * 60 // 1 hour ago
            ),
            HistoryItem(
                input = "1000",
                fromUnit = context.getString(AreaUnit.SQUARE_FOOT.nameResId),
                toUnit = context.getString(AreaUnit.GUNTHA.nameResId),
                result = "0.92",
                timestamp = now - 1000 * 60 * 60 * 2 // 2 hours ago
            ),
            HistoryItem(
                input = "5",
                fromUnit = context.getString(AreaUnit.BIGHA.nameResId),
                toUnit = context.getString(AreaUnit.HECTARE.nameResId),
                result = "1.26",
                timestamp = now - 1000 * 60 * 60 * 5 // 5 hours ago
            ),
            HistoryItem(
                input = "10",
                fromUnit = context.getString(AreaUnit.CENT.nameResId),
                toUnit = context.getString(AreaUnit.SQUARE_FOOT.nameResId),
                result = "4356",
                timestamp = now - 1000 * 60 * 60 * 24 // 1 day ago
            ),
            HistoryItem(
                input = "2.5",
                fromUnit = context.getString(AreaUnit.HECTARE.nameResId),
                toUnit = context.getString(AreaUnit.ACRE.nameResId),
                result = "6.18",
                timestamp = now - 1000 * 60 * 60 * 48 // 2 days ago
            ),
            HistoryItem(
                input = "500",
                fromUnit = context.getString(AreaUnit.SQUARE_METER.nameResId),
                toUnit = context.getString(AreaUnit.ARE.nameResId),
                result = "5.0",
                timestamp = now - 1000 * 60 * 60 * 72 // 3 days ago
            )
        )
        saveList(dummyItems)
    }

    private fun saveList(list: List<HistoryItem>) {
        val jsonArray = JSONArray()
        for (item in list) {
            val obj = JSONObject()
            obj.put("input", item.input)
            obj.put("fromUnit", item.fromUnit)
            obj.put("toUnit", item.toUnit)
            obj.put("result", item.result)
            obj.put("timestamp", item.timestamp)
            jsonArray.put(obj)
        }
        prefs.edit().putString(historyKey, jsonArray.toString()).apply()
    }
}
