package club.clubk.ktag.apps.medic.ui

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import club.clubk.ktag.apps.core.DeviceModel
import club.clubk.ktag.apps.core.ui.RenameDeviceDialog
import club.clubk.ktag.apps.medic.MedicViewModel
import club.clubk.ktag.apps.medic.ui.theme.MedicGrey

@Composable
fun MedicScreen(
    viewModel: MedicViewModel,
    modifier: Modifier = Modifier
) {
    val devices = viewModel.devices
    val kothPossessionText = viewModel.kothPossessionText
    val kothPossessionColor = viewModel.kothPossessionColor
    val backgroundColor = viewModel.backgroundColorForAutoHeal

    // Rename dialog state
    var deviceToRename by remember { mutableStateOf<DeviceModel?>(null) }

    // Rename dialog
    deviceToRename?.let { device ->
        RenameDeviceDialog(
            macAddress = device.bleAddress,
            currentName = device.name,
            onDismiss = { deviceToRename = null },
            onSave = { newName ->
                viewModel.renameDevice(device.bleAddress, newName)
                deviceToRename = null
            }
        )
    }

    Column(
        modifier = modifier
            .fillMaxSize()
            .background(MedicGrey)
    ) {
        // KOTH Status Bar
        KothStatusBar(
            possessionText = kothPossessionText,
            possessionColor = kothPossessionColor
        )

        // Device list
        LazyColumn(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
                .background(backgroundColor)
        ) {
            items(
                items = devices,
                key = { it.bleAddress }
            ) { device ->
                DeviceCard(
                    device = device,
                    onClick = { viewModel.onDeviceClicked(device) },
                    onLongClick = { deviceToRename = device }
                )
            }
        }
    }
}
