package com.fieldlabel.collector.ui.screens

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.fieldlabel.collector.domain.model.RouteLog
import com.fieldlabel.collector.ui.viewmodel.RouteLogViewModel
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter

// ════════════════════════════════════════════════════════════════════════════
// RouteLogListScreen  — 移動ログ一覧
// ════════════════════════════════════════════════════════════════════════════

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RouteLogListScreen(
    onNavigateBack:   () -> Unit,
    onNavigateToMap:  (String) -> Unit,
    viewModel:        RouteLogViewModel = hiltViewModel()
) {
    val routeLogs by viewModel.routeLogs.collectAsState()

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("移動ログ一覧") },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(Icons.Default.ArrowBack, "戻る")
                    }
                }
            )
        }
    ) { padding ->
        if (routeLogs.isEmpty()) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(padding),
                contentAlignment = Alignment.Center
            ) {
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Icon(
                        Icons.Default.Route,
                        contentDescription = null,
                        modifier = Modifier.size(48.dp),
                        tint     = MaterialTheme.colorScheme.outline
                    )
                    Text(
                        "移動ログがありません",
                        style = MaterialTheme.typography.titleMedium,
                        color = MaterialTheme.colorScheme.outline
                    )
                    Text(
                        "マップ画面で記録を開始してください",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.outline
                    )
                }
            }
        } else {
            LazyColumn(
                modifier       = Modifier
                    .fillMaxSize()
                    .padding(padding),
                contentPadding = PaddingValues(12.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                items(routeLogs, key = { it.id }) { log ->
                    RouteLogCard(
                        routeLog        = log,
                        onTap           = { onNavigateToMap(log.id) },
                        onDelete        = { viewModel.deleteLog(log) }
                    )
                }
            }
        }
    }
}

// ── ルートログカード ──────────────────────────────────────────────────────────

@Composable
private fun RouteLogCard(
    routeLog: RouteLog,
    onTap:    () -> Unit,
    onDelete: () -> Unit
) {
    var showDeleteDialog by remember { mutableStateOf(false) }

    if (showDeleteDialog) {
        AlertDialog(
            onDismissRequest = { showDeleteDialog = false },
            title            = { Text("ログを削除") },
            text             = { Text("「${routeLog.name}」を削除しますか？この操作は取り消せません。") },
            confirmButton    = {
                TextButton(onClick = {
                    onDelete()
                    showDeleteDialog = false
                }) { Text("削除", color = MaterialTheme.colorScheme.error) }
            },
            dismissButton    = {
                TextButton(onClick = { showDeleteDialog = false }) { Text("キャンセル") }
            }
        )
    }

    Card(
        modifier  = Modifier
            .fillMaxWidth()
            .clickable(onClick = onTap),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Row(
            modifier          = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp, vertical = 12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // ルートアイコン（記録中は赤）
            Icon(
                imageVector        = if (routeLog.isRecording) Icons.Default.FiberManualRecord
                                     else Icons.Default.Route,
                contentDescription = null,
                tint               = if (routeLog.isRecording) MaterialTheme.colorScheme.error
                                     else MaterialTheme.colorScheme.primary,
                modifier           = Modifier
                    .size(40.dp)
                    .padding(end = 12.dp)
            )

            Column(modifier = Modifier.weight(1f)) {
                // ルート名
                Text(
                    text  = routeLog.name,
                    style = MaterialTheme.typography.titleSmall
                )
                Spacer(modifier = Modifier.height(2.dp))
                // 開始日時
                Text(
                    text  = formatEpochMs(routeLog.startTime),
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.outline
                )
                Spacer(modifier = Modifier.height(4.dp))

                // 統計行
                Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) {
                    // 距離
                    RouteStatChip(
                        icon  = Icons.Default.Straighten,
                        label = formatDistance(routeLog.totalDistanceMeters)
                    )
                    // 所要時間
                    RouteStatChip(
                        icon  = Icons.Default.Timer,
                        label = formatDuration(routeLog.durationMs)
                    )
                    // ポイント数
                    RouteStatChip(
                        icon  = Icons.Default.LocationOn,
                        label = "${routeLog.pointCount} 点"
                    )
                }

                if (routeLog.isRecording) {
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        "● 記録中",
                        style = MaterialTheme.typography.labelSmall,
                        color = MaterialTheme.colorScheme.error
                    )
                }
            }

            // 削除ボタン
            IconButton(onClick = { showDeleteDialog = true }) {
                Icon(
                    Icons.Default.Delete,
                    contentDescription = "削除",
                    tint               = MaterialTheme.colorScheme.outline
                )
            }
        }
    }
}

@Composable
private fun RouteStatChip(icon: androidx.compose.ui.graphics.vector.ImageVector, label: String) {
    Row(
        verticalAlignment    = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(2.dp)
    ) {
        Icon(
            imageVector        = icon,
            contentDescription = null,
            modifier           = Modifier.size(12.dp),
            tint               = MaterialTheme.colorScheme.outline
        )
        Text(
            text  = label,
            style = MaterialTheme.typography.labelSmall,
            color = MaterialTheme.colorScheme.outline
        )
    }
}

// ── ユーティリティ ────────────────────────────────────────────────────────────

private val DATE_FMT: DateTimeFormatter =
    DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm")

private fun formatEpochMs(ms: Long): String =
    Instant.ofEpochMilli(ms)
        .atZone(ZoneId.systemDefault())
        .format(DATE_FMT)

private fun formatDuration(ms: Long): String {
    val totalSec = ms / 1_000
    val h = totalSec / 3600
    val m = (totalSec % 3600) / 60
    val s = totalSec % 60
    return if (h > 0) "%d:%02d:%02d".format(h, m, s)
    else "%d:%02d".format(m, s)
}

private fun formatDistance(meters: Double): String = when {
    meters >= 1_000 -> "${"%.2f".format(meters / 1_000)} km"
    else            -> "${"%.0f".format(meters)} m"
}
