package com.recordatorios.app

import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

class NotesManager private constructor(context: Context) {

    private var prefs: SharedPreferences =
        context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
    private val gson = Gson()
    private var securityManager: SecurityManager? = null

    fun setSecurityManager(securityManager: SecurityManager) {
        this.securityManager = securityManager
    }

    private fun getPrefs(): SharedPreferences {
        return securityManager?.getEncryptedPrefs() ?: prefs
    }

    fun getAllNotes(): MutableList<Note> {
        val json = getPrefs().getString(KEY_NOTES, null) ?: return mutableListOf()
        val type = object : TypeToken<MutableList<Note>>() {}.type
        return gson.fromJson(json, type) ?: mutableListOf()
    }

    fun saveNotes(notes: List<Note>) {
        getPrefs().edit().putString(KEY_NOTES, gson.toJson(notes)).apply()
    }

    fun addNote(note: Note) {
        val notes = getAllNotes()
        notes.add(0, note)
        saveNotes(notes)
    }

    fun updateNote(note: Note) {
        val notes = getAllNotes()
        val index = notes.indexOfFirst { it.id == note.id }
        if (index != -1) {
            notes[index] = note
            saveNotes(notes)
        }
    }

    fun softDeleteNote(noteId: Long) {
        val notes = getAllNotes()
        val note = notes.find { it.id == noteId } ?: return
        note.deletedAt = System.currentTimeMillis()
        saveNotes(notes)
    }

    fun restoreNote(noteId: Long) {
        val notes = getAllNotes()
        val note = notes.find { it.id == noteId } ?: return
        note.deletedAt = null
        note.isCompleted = false
        saveNotes(notes)
    }

    fun permanentlyDeleteNote(noteId: Long) {
        val notes = getAllNotes()
        notes.removeAll { it.id == noteId }
        saveNotes(notes)
    }

    fun getNote(noteId: Long): Note? {
        return getAllNotes().find { it.id == noteId }
    }

    fun toggleComplete(noteId: Long) {
        val notes = getAllNotes()
        val note = notes.find { it.id == noteId } ?: return
        note.isCompleted = true
        note.deletedAt = System.currentTimeMillis()
        saveNotes(notes)
    }

    fun exportToJson(): String {
        return gson.toJson(getAllNotes())
    }

    fun importFromJson(json: String) {
        val type = object : TypeToken<List<Note>>() {}.type
        val importedNotes = gson.fromJson<List<Note>>(json, type) ?: return
        val existingNotes = getAllNotes()
        val existingIds = existingNotes.map { it.id }.toSet()
        
        for (note in importedNotes) {
            if (note.id !in existingIds) {
                existingNotes.add(note)
            } else {
                val index = existingNotes.indexOfFirst { it.id == note.id }
                if (index != -1) {
                    existingNotes[index] = note
                }
            }
        }
        saveNotes(existingNotes)
    }
    companion object {
        private const val PREFS_NAME = "recordatorios_prefs"
        private const val KEY_NOTES = "notes"

        @Volatile
        private var INSTANCE: NotesManager? = null

        fun getInstance(context: Context): NotesManager {
            return INSTANCE ?: synchronized(this) {
                INSTANCE ?: NotesManager(context.applicationContext).also { INSTANCE = it }
            }
        }
    }
}
