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.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Bluetooth
import androidx.compose.material.icons.filled.BluetoothSearching
import androidx.compose.material.icons.filled.Check
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.ui.viewmodel.BleScanState
import com.fieldlabel.collector.ui.viewmodel.BondedPrinterInfo
import com.fieldlabel.collector.ui.viewmodel.SettingsViewModel
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.rememberMultiplePermissionsState

@OptIn(ExperimentalMaterial3Api::class, ExperimentalPermissionsApi::class)
@Composable
fun PrinterScanScreen(
    onBack: () -> Unit,
    viewModel: SettingsViewModel = hiltViewModel()
) {
    val btPermissions = rememberMultiplePermissionsState(
        listOf(
            android.Manifest.permission.BLUETOOTH_CONNECT,
            android.Manifest.permission.BLUETOOTH_SCAN,
            // Android 11 以下では BLE スキャン結果に位置情報権限が必要
            android.Manifest.permission.ACCESS_FINE_LOCATION
        )
    )

    val savedLocalName by viewModel.printerLocalName.collectAsState()
    val bleScanState   by viewModel.bleScanState.collectAsState()

    // ペアリング済みデバイス（権限取得後に一度だけ取得）
    val bondedPrinters = remember(btPermissions.allPermissionsGranted) {
        if (btPermissions.allPermissionsGranted) viewModel.getBondedBrotherPrinters()
        else emptyList()
    }

    // 画面を離れたらスキャン状態をリセット
    DisposableEffect(Unit) {
        onDispose { viewModel.resetBleScan() }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("プリンター選択") },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.Default.ArrowBack, "戻る")
                    }
                }
            )
        }
    ) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .imePadding()                // キーボード表示時に自動スクロール余白を確保
                .verticalScroll(rememberScrollState())
                .padding(start = 16.dp, end = 16.dp, top = 16.dp, bottom = 64.dp),
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            if (!btPermissions.allPermissionsGranted) {
                Text("Bluetooth・位置情報の権限が必要です", color = MaterialTheme.colorScheme.error)
                Button(
                    onClick  = { btPermissions.launchMultiplePermissionRequest() },
                    modifier = Modifier.fillMaxWidth()
                ) { Text("権限を許可") }
                return@Column
            }

            // ---- 現在の設定 ----
            if (savedLocalName.isNotBlank()) {
                Surface(
                    color    = MaterialTheme.colorScheme.primaryContainer,
                    shape    = MaterialTheme.shapes.small,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Row(
                        modifier              = Modifier.padding(12.dp),
                        verticalAlignment     = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        Icon(Icons.Default.Check, null,
                            tint = MaterialTheme.colorScheme.primary)
                        Column {
                            Text("現在の設定",
                                style = MaterialTheme.typography.labelSmall,
                                color = MaterialTheme.colorScheme.onPrimaryContainer)
                            Text(savedLocalName,
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.onPrimaryContainer)
                        }
                    }
                }
            }

            // ---- ペアリング済みデバイス セクション ----
            Text("ペアリング済みデバイス", style = MaterialTheme.typography.titleMedium)
            if (bondedPrinters.isEmpty()) {
                Text(
                    "Bluetooth 設定でペアリング済みの Brother プリンターが見つかりません。\n" +
                    "先に Android の Bluetooth 設定でプリンターとペアリングしてください。",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.outline
                )
            } else {
                Text(
                    "タップして接続先として設定します（推奨）。",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.outline
                )
                bondedPrinters.forEach { printer ->
                    val isSelected = savedLocalName == printer.name
                    Card(
                        modifier = Modifier
                            .fillMaxWidth()
                            .clickable { viewModel.savePrinterLocalName(printer.name) },
                        colors = CardDefaults.cardColors(
                            containerColor = if (isSelected)
                                MaterialTheme.colorScheme.primaryContainer
                            else MaterialTheme.colorScheme.surface
                        ),
                        border = if (isSelected) ButtonDefaults.outlinedButtonBorder else null
                    ) {
                        Row(
                            modifier          = Modifier.padding(16.dp),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Icon(
                                Icons.Default.Bluetooth, null,
                                tint = if (isSelected)
                                    MaterialTheme.colorScheme.primary
                                else MaterialTheme.colorScheme.outline
                            )
                            Spacer(Modifier.width(12.dp))
                            Column(modifier = Modifier.weight(1f)) {
                                Text(printer.name,
                                    style = MaterialTheme.typography.bodyMedium)
                                Text(printer.address,
                                    style = MaterialTheme.typography.bodySmall,
                                    color = MaterialTheme.colorScheme.outline)
                            }
                            if (isSelected) {
                                Icon(Icons.Default.Check, "設定済み",
                                    tint = MaterialTheme.colorScheme.primary)
                            }
                        }
                    }
                }
            }

            HorizontalDivider()

            // ---- BLE スキャン セクション ----
            Text("BLE スキャン（任意）", style = MaterialTheme.typography.titleMedium)
            Text(
                "ペアリング済みデバイスが使えない場合のみ使用してください。\n" +
                "プリンターの電源を入れて「スキャン開始」を押してください。",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.outline
            )

            Button(
                onClick  = { viewModel.startBleScan() },
                enabled  = bleScanState !is BleScanState.Scanning,
                modifier = Modifier.fillMaxWidth()
            ) {
                if (bleScanState is BleScanState.Scanning) {
                    CircularProgressIndicator(
                        modifier    = Modifier.size(18.dp),
                        strokeWidth = 2.dp,
                        color       = MaterialTheme.colorScheme.onPrimary
                    )
                    Spacer(Modifier.width(8.dp))
                    Text("スキャン中… (10秒)")
                } else {
                    Icon(Icons.Default.BluetoothSearching, null)
                    Spacer(Modifier.width(8.dp))
                    Text("スキャン開始")
                }
            }

            // スキャン結果
            when (val state = bleScanState) {
                is BleScanState.Results -> {
                    Text(
                        "${state.printers.size} 台発見",
                        style = MaterialTheme.typography.labelMedium,
                        color = MaterialTheme.colorScheme.primary
                    )
                    state.printers.forEach { printer ->
                        val isSelected = savedLocalName == printer.localName
                        Card(
                            modifier = Modifier
                                .fillMaxWidth()
                                .clickable {
                                    viewModel.savePrinterLocalName(printer.localName)
                                },
                            colors = CardDefaults.cardColors(
                                containerColor = if (isSelected)
                                    MaterialTheme.colorScheme.primaryContainer
                                else
                                    MaterialTheme.colorScheme.surface
                            ),
                            border = if (isSelected) ButtonDefaults.outlinedButtonBorder else null
                        ) {
                            Row(
                                modifier          = Modifier.padding(16.dp),
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Icon(
                                    Icons.Default.Bluetooth, null,
                                    tint = if (isSelected)
                                        MaterialTheme.colorScheme.primary
                                    else
                                        MaterialTheme.colorScheme.outline
                                )
                                Spacer(Modifier.width(12.dp))
                                Column(modifier = Modifier.weight(1f)) {
                                    Text(printer.localName,
                                        style = MaterialTheme.typography.bodyMedium)
                                    if (printer.modelName.isNotBlank()) {
                                        Text(printer.modelName,
                                            style = MaterialTheme.typography.bodySmall,
                                            color = MaterialTheme.colorScheme.outline)
                                    }
                                }
                                if (isSelected) {
                                    Icon(Icons.Default.Check, "設定済み",
                                        tint = MaterialTheme.colorScheme.primary)
                                }
                            }
                        }
                    }
                }
                is BleScanState.Error -> {
                    Card(
                        colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.errorContainer
                        ),
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        Text(
                            state.message,
                            style    = MaterialTheme.typography.bodySmall,
                            color    = MaterialTheme.colorScheme.onErrorContainer,
                            modifier = Modifier.padding(12.dp)
                        )
                    }
                }
                else -> {}
            }

            HorizontalDivider()

            // ---- 手動入力セクション ----
            Text("手動入力", style = MaterialTheme.typography.titleMedium)
            Text(
                "スキャンで見つからない場合は、プリンターのBLE名を直接入力してください。\n" +
                "（例: PT-P710BT、PT-P910BT）",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.outline
            )

            var manualName by remember { mutableStateOf(savedLocalName) }
            OutlinedTextField(
                value         = manualName,
                onValueChange = { manualName = it },
                label         = { Text("BLE ローカルネーム") },
                placeholder   = { Text("例: PT-P710BT") },
                singleLine    = true,
                modifier      = Modifier.fillMaxWidth()
            )
            Button(
                onClick  = {
                    if (manualName.isNotBlank()) viewModel.savePrinterLocalName(manualName)
                },
                enabled  = manualName.isNotBlank() && manualName != savedLocalName,
                modifier = Modifier.fillMaxWidth()
            ) {
                Text("この名前で設定する")
            }
        }
    }
}
