package app.closer.ui.questions

import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.tooling.preview.Preview
import androidx.hilt.navigation.compose.hiltViewModel
import app.closer.core.navigation.AppRoute
import app.closer.domain.model.Question

@Composable
fun QuestionThreadScreen(
    coupleId: String,
    questionId: String,
    previousQuestionId: String? = null,
    nextQuestionId: String? = null,
    onNavigate: (String) -> Unit = {},
    onBack: () -> Unit = {},
    viewModel: QuestionDetailViewModel = hiltViewModel()
) {
    val state by viewModel.uiState.collectAsState()

    LocalQuestionContent(
        state = state,
        title = "Answer with care",
        subtitle = "Save your answer privately first. From there, choose whether to keep moving or revisit what you have opened.",
        primaryRouteLabel = nextQuestionId?.let { "Next prompt" } ?: "Saved answers",
        onPrimaryRoute = {
            if (nextQuestionId != null) {
                onNavigate(
                    AppRoute.questionThread(
                        coupleId = coupleId,
                        questionId = nextQuestionId,
                        prevId = questionId
                    )
                )
            } else {
                onNavigate(AppRoute.ANSWER_HISTORY)
            }
        },
        onSecondaryRoute = previousQuestionId?.let {
            {
                onNavigate(
                    AppRoute.questionThread(
                        coupleId = coupleId,
                        questionId = previousQuestionId,
                        nextId = questionId
                    )
                )
            }
        } ?: onBack,
        secondaryRouteLabel = previousQuestionId?.let { "Previous" } ?: "Back",
        onWrittenTextChanged = viewModel::updateWrittenText,
        onOptionToggled = viewModel::toggleOption,
        onScaleChanged = viewModel::updateScale,
        onSubmit = viewModel::submitAnswer,
        canSubmit = viewModel.canSubmit()
    )
}

@Preview
@Composable
fun QuestionThreadScreenPreview() {
    LocalQuestionContent(
        state = LocalQuestionUiState(
            isLoading = false,
            question = Question(
                id = "demo",
                text = "What is one conversation you want us to handle more gently?",
                category = "communication",
                depthLevel = 3,
                type = "written"
            )
        ),
        title = "Answer with care",
        subtitle = "Save your answer privately first.",
        primaryRouteLabel = "Saved answers",
        onPrimaryRoute = {},
        onSecondaryRoute = {},
        secondaryRouteLabel = "Back",
        onWrittenTextChanged = {},
        onOptionToggled = {},
        onScaleChanged = {},
        onSubmit = {},
        canSubmit = false
    )
}
