package com.applemand.zmanim.core.notifications

import android.Manifest
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import androidx.hilt.work.HiltWorker
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.applemand.zmanim.core.jewcal.DafYomiCalculator
import com.applemand.zmanim.core.jewcal.toHebrewDate
import com.applemand.zmanim.core.settings.SettingsRepository
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import kotlinx.coroutines.flow.first
import kotlinx.datetime.Clock
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime

/**
 * Fires once per day to post a concise Hebrew-date + daf yomi summary.
 * Scheduled via ZmanimAlarmScheduler.schedulePeriodic(context).
 */
@HiltWorker
class DailyZmanimWorker @AssistedInject constructor(
    @Assisted context: Context,
    @Assisted params: WorkerParameters,
    private val settings: SettingsRepository,
    private val dafCalc: DafYomiCalculator,
) : CoroutineWorker(context, params) {

    override suspend fun doWork(): Result {
        val s = settings.settings.first()
        if (!s.enableNotifications) return Result.success()

        val today = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).date
        val hebrew = today.toHebrewDate()
        val daf = dafCalc.bavli(today)?.displayEn ?: ""

        val ctx = applicationContext
        if (ContextCompat.checkSelfPermission(ctx, Manifest.permission.POST_NOTIFICATIONS)
            != PackageManager.PERMISSION_GRANTED) return Result.success()

        val tapIntent = Intent(Intent.ACTION_VIEW, android.net.Uri.parse("luach://day"))
            .setPackage(ctx.packageName)
        val pi = PendingIntent.getActivity(
            ctx, 0, tapIntent,
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
        )

        val text = buildString {
            append(hebrew.displayEn())
            if (daf.isNotEmpty()) { append(" • "); append(daf) }
        }
        val notif = NotificationCompat.Builder(ctx, Channels.CHANNEL_DAILY)
            .setSmallIcon(android.R.drawable.ic_dialog_info)
            .setContentTitle("Luach")
            .setContentText(text)
            .setStyle(NotificationCompat.BigTextStyle().bigText(text))
            .setContentIntent(pi)
            .setAutoCancel(true)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .build()

        NotificationManagerCompat.from(ctx).notify(NOTIFICATION_ID_DAILY, notif)
        return Result.success()
    }

    companion object {
        const val NOTIFICATION_ID_DAILY = 1001
    }
}
