package com.fieldlabel.collector.ui.viewmodel

import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.fieldlabel.collector.data.RouteLogRepository
import com.fieldlabel.collector.domain.model.RouteLog
import com.fieldlabel.collector.domain.model.RoutePoint
import com.fieldlabel.collector.service.RouteLoggerService
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import java.time.format.DateTimeFormatter
import java.time.LocalDateTime
import javax.inject.Inject

@HiltViewModel
class RouteLogViewModel @Inject constructor(
    @ApplicationContext private val context: Context,
    private val routeLogRepository: RouteLogRepository
) : ViewModel() {

    // ── 全ログ一覧 ────────────────────────────────────────────────────────────
    val routeLogs: StateFlow<List<RouteLog>> = routeLogRepository.allRouteLogs
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())

    // ── 記録状態 ──────────────────────────────────────────────────────────────
    private val _isRecording = MutableStateFlow(RouteLoggerService.isRunning)
    val isRecording: StateFlow<Boolean> = _isRecording

    // ── 現在のルートの測位点（マップ上のリアルタイム表示用） ──────────────────
    private val _currentRoutePoints = MutableStateFlow<List<RoutePoint>>(emptyList())
    val currentRoutePoints: StateFlow<List<RoutePoint>> = _currentRoutePoints

    // ── 選択ルートの測位点（RouteMapScreen 表示用） ───────────────────────────
    private val _selectedRoutePoints = MutableStateFlow<List<RoutePoint>>(emptyList())
    val selectedRoutePoints: StateFlow<List<RoutePoint>> = _selectedRoutePoints

    private var pollingJob: Job? = null

    init {
        // 起動時にすでにサービスが動いていた場合、ポーリングを再開する
        if (RouteLoggerService.isRunning) {
            _isRecording.value = true
            startPolling()
        }
    }

    // ── 記録開始 ─────────────────────────────────────────────────────────────
    fun startRecording(name: String = defaultRouteName()) {
        val intent = Intent(context, RouteLoggerService::class.java).apply {
            action = RouteLoggerService.ACTION_START
            putExtra(RouteLoggerService.EXTRA_ROUTE_NAME, name)
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.startForegroundService(intent)
        } else {
            context.startService(intent)
        }
        _isRecording.value = true
        startPolling()
    }

    // ── 記録停止 ─────────────────────────────────────────────────────────────
    fun stopRecording() {
        context.startService(
            Intent(context, RouteLoggerService::class.java).apply {
                action = RouteLoggerService.ACTION_STOP
            }
        )
        _isRecording.value = false
        pollingJob?.cancel()
        pollingJob = null
        _currentRoutePoints.value = emptyList()
    }

    // ── 特定ルートの測位点をロード（RouteMapScreen 用） ──────────────────────
    fun loadRoutePoints(routeLogId: String) {
        viewModelScope.launch {
            _selectedRoutePoints.value = routeLogRepository.getPoints(routeLogId)
        }
    }

    fun clearSelectedRoute() {
        _selectedRoutePoints.value = emptyList()
    }

    // ── ログ削除 ─────────────────────────────────────────────────────────────
    fun deleteLog(routeLog: RouteLog) {
        viewModelScope.launch {
            routeLogRepository.deleteLog(routeLog.id)
        }
    }

    // ── 内部処理 ─────────────────────────────────────────────────────────────

    private fun startPolling() {
        pollingJob?.cancel()
        pollingJob = viewModelScope.launch {
            while (isActive) {
                delay(3_000)
                val id = RouteLoggerService.currentRouteLogId ?: break
                _currentRoutePoints.value = routeLogRepository.getPoints(id)
            }
        }
    }

    private fun defaultRouteName(): String {
        val fmt = DateTimeFormatter.ofPattern("MM/dd HH:mm")
        return "ルート ${LocalDateTime.now().format(fmt)}"
    }
}
