package com.recordatorios.app

import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.widget.RemoteViews
import android.widget.RemoteViewsService
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

class TodayWidgetFactory(
    private val context: Context,
    private val appWidgetId: Int,
    private val showTime: Boolean,
    private val showCategory: Boolean,
    private val maxItems: Int
) : RemoteViewsService.RemoteViewsFactory {

    private var notes: List<Note> = emptyList()
    private var categories: List<Category> = emptyList()
    private val timeFormat = SimpleDateFormat("HH:mm", Locale.getDefault())

    override fun onCreate() {
        loadData()
    }

    override fun onDataSetChanged() {
        loadData()
    }

    override fun onDestroy() {}

    override fun getCount(): Int = notes.size

    override fun getViewAt(position: Int): RemoteViews {
        val note = notes[position]
        val item = RemoteViews(context.packageName, R.layout.widget_note_item)

        item.setTextViewText(R.id.widgetItemTitle, note.title.ifBlank { "Sin t\u00edtulo" })

        if (showTime && note.reminderDate != null) {
            item.setTextViewText(R.id.widgetItemTime, timeFormat.format(Date(note.reminderDate!!)))
            item.setViewVisibility(R.id.widgetItemTime, android.view.View.VISIBLE)
        } else {
            item.setViewVisibility(R.id.widgetItemTime, android.view.View.GONE)
        }

        if (showCategory) {
            val cat = categories.find { it.id == note.category }
            if (cat != null) {
                item.setViewVisibility(R.id.widgetItemDot, android.view.View.VISIBLE)
                item.setInt(R.id.widgetItemDot, "setColorFilter", cat.color)
            } else {
                item.setViewVisibility(R.id.widgetItemDot, android.view.View.GONE)
            }
        } else {
            item.setViewVisibility(R.id.widgetItemDot, android.view.View.GONE)
        }

        val fillIntent = Intent().apply {
            putExtra("note_id", note.id)
        }
        item.setOnClickFillInIntent(R.id.widgetItemTitle, fillIntent)

        return item
    }

    override fun getLoadingView(): RemoteViews? = null

    override fun getViewTypeCount(): Int = 1

    override fun getItemId(position: Int): Long = notes[position].id

    override fun hasStableIds(): Boolean = true

    private fun loadData() {
        categories = CategoryManager.getInstance(context).getAllCategories()

        val allNotes = NotesManager.getInstance(context)
            .getAllNotes()
            .filter { !it.isCompleted && it.deletedAt == null }

        val todayStart = Calendar.getInstance().apply {
            set(Calendar.HOUR_OF_DAY, 0)
            set(Calendar.MINUTE, 0)
            set(Calendar.SECOND, 0)
            set(Calendar.MILLISECOND, 0)
        }.timeInMillis
        val todayEnd = todayStart + 86400000L

        val todayNotes = allNotes.filter { note ->
            note.reminderDate != null && note.reminderDate!! >= todayStart && note.reminderDate!! < todayEnd
        }

        val overdueNotes = allNotes.filter { note ->
            note.reminderDate != null && note.reminderDate!! < todayStart
        }

        notes = (todayNotes + overdueNotes)
            .sortedByDescending { it.reminderDate ?: 0L }

        if (maxItems > 0 && notes.size > maxItems) {
            notes = notes.take(maxItems)
        }
    }
}
