package com.doctate.watch.presentation

import android.Manifest
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.wear.compose.material3.EdgeButton
import androidx.wear.compose.material3.MaterialTheme
import androidx.wear.compose.material3.ScreenScaffold
import androidx.wear.compose.material3.Text

@Composable
fun RecordingScreen(
    caseId: String,
    onDone: () -> Unit,
    viewModel: RecordingViewModel = viewModel(
        key = caseId,
        factory = RecordingViewModel.factoryFor(caseId),
    ),
) {
    val state by viewModel.state.collectAsStateWithLifecycle()
    val view = LocalView.current

    val permissionLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestPermission(),
    ) { granted -> viewModel.onPermissionResult(granted) }

    // Auto-start: entering the screen kicks off the record flow. Guard against
    // re-entry — only trigger while VM is still Idle.
    LaunchedEffect(Unit) {
        if (state is UiState.Idle) {
            viewModel.onRecordTap()
        }
    }

    // Request mic permission when the VM flips to RequestingPermission.
    LaunchedEffect(state is UiState.RequestingPermission) {
        if (state is UiState.RequestingPermission) {
            permissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
        }
    }

    // Pop on any post-Recording state: clean stop (Uploading), auto-stop
    // completion (Success), or permission denial / recorder failure (Error).
    val isDone = state is UiState.Uploading ||
        state is UiState.Success ||
        state is UiState.Error
    if (isDone) {
        LaunchedEffect(Unit) { onDone() }
    }

    // Option C: keep display on while this composable is alive.
    // onDispose doubles as the discard trigger for swipe-right / back —
    // discardIfStillRecording() is a no-op when state is already Uploading.
    DisposableEffect(Unit) {
        view.keepScreenOn = true
        onDispose {
            view.keepScreenOn = false
            viewModel.discardIfStillRecording()
        }
    }

    ScreenScaffold { contentPadding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(contentPadding)
                .padding(top = 24.dp, bottom = 72.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center,
        ) {
            val s = state
            if (s is UiState.Recording) {
                Text(
                    text = formatDuration(s.elapsedSeconds),
                    style = MaterialTheme.typography.displayMedium,
                    fontFamily = FontFamily.Monospace,
                    textAlign = TextAlign.Center,
                )
            }
        }
        if (state is UiState.Recording) {
            EdgeButton(
                onClick = { viewModel.onStopTap() },
                modifier = Modifier.align(Alignment.BottomCenter),
            ) {
                Box(
                    modifier = Modifier
                        .size(16.dp)
                        .background(MaterialTheme.colorScheme.onPrimary),
                )
            }
        }
    }
}

private fun formatDuration(seconds: Int): String {
    val m = seconds / 60
    val s = seconds % 60
    return "%d:%02d".format(m, s)
}
