package com.fieldlabel.collector.ui.screens

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Print
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.fieldlabel.collector.domain.model.CollectionRecord
import com.fieldlabel.collector.ui.viewmodel.CollectionViewModel
import com.fieldlabel.collector.ui.viewmodel.PrintState

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LabelPreviewScreen(
    recordId: String,
    onBack: () -> Unit,
    viewModel: CollectionViewModel = hiltViewModel()
) {
    val uiState by viewModel.uiState.collectAsState()
    val allRecords by viewModel.allRecords.collectAsState(initial = emptyList())
    val record = allRecords.find { it.id == recordId }

    LaunchedEffect(record) {
        record?.let { viewModel.buildPreview(it) }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("ラベルプレビュー") },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.Default.ArrowBack, "戻る")
                    }
                }
            )
        }
    ) { padding ->
        if (record == null) {
            Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                Text("レコードが見つかりません")
            }
            return@Scaffold
        }

        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .verticalScroll(rememberScrollState())
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            // ---- ラベルビットマッププレビュー ----
            val bitmap = uiState.labelBitmap
            Card(
                modifier = Modifier.fillMaxWidth(),
                shape    = RoundedCornerShape(8.dp)
            ) {
                Column(modifier = Modifier.padding(12.dp)) {
                    Text("ラベルイメージ", style = MaterialTheme.typography.labelMedium)
                    Spacer(Modifier.height(8.dp))
                    if (bitmap != null) {
                        Image(
                            bitmap      = bitmap.asImageBitmap(),
                            contentDescription = "ラベルプレビュー",
                            contentScale = ContentScale.FillWidth,
                            modifier    = Modifier
                                .fillMaxWidth()
                                .background(Color.White)
                        )
                    } else {
                        Box(
                            Modifier
                                .fillMaxWidth()
                                .height(100.dp)
                                .background(Color.LightGray),
                            contentAlignment = Alignment.Center
                        ) {
                            CircularProgressIndicator()
                        }
                    }
                }
            }

            // ---- レコード詳細 ----
            RecordDetailCard(record)

            // ---- 再印刷ボタン ----
            when (val ps = uiState.printState) {
                is PrintState.Error -> {
                    Text("印刷エラー: ${ps.message}",
                        color = MaterialTheme.colorScheme.error,
                        style = MaterialTheme.typography.bodySmall)
                }
                is PrintState.Done -> {
                    Text("✓ ${ps.message}",
                        color = MaterialTheme.colorScheme.primary,
                        style = MaterialTheme.typography.bodySmall)
                }
                else -> {}
            }

            Button(
                onClick  = { viewModel.reprintRecord(record) },
                enabled  = uiState.printState !is PrintState.Printing,
                modifier = Modifier.fillMaxWidth()
            ) {
                Icon(Icons.Default.Print, null)
                Spacer(Modifier.width(8.dp))
                Text("再印刷")
            }
        }
    }
}

@Composable
private fun RecordDetailCard(record: CollectionRecord) {
    Card(modifier = Modifier.fillMaxWidth()) {
        Column(
            modifier = Modifier.padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            LabeledField("標本ID",   record.specimenId, monospace = true)
            LabeledField("地点ID",   record.locationId, monospace = true)
            LabeledField("採集日",   record.collectionDate.toString())
            LabeledField("採集場所", record.displayLocation)
            LabeledField("GPS",
                "${"%.6f".format(record.latitude)}°N, ${"%.6f".format(record.longitude)}°E")
            if (record.altitude != null)
                LabeledField("標高", "${"%.1f".format(record.altitude)} m")
            LabeledField("採集者",   record.collectorName)
            if (record.notes.isNotBlank())
                LabeledField("備考", record.notes)
            LabeledField("同期状態", if (record.synced) "✓ 同期済み" else "⏳ 同期待ち")
        }
    }
}

@Composable
private fun LabeledField(label: String, value: String, monospace: Boolean = false) {
    Column {
        Text(label, style = MaterialTheme.typography.labelSmall,
            color = MaterialTheme.colorScheme.outline)
        Text(
            value,
            style = if (monospace)
                MaterialTheme.typography.bodyMedium.copy(fontFamily = FontFamily.Monospace)
            else MaterialTheme.typography.bodyMedium
        )
    }
    HorizontalDivider(thickness = 0.5.dp, color = MaterialTheme.colorScheme.outlineVariant)
}
