package com.tt.honeyDue.ui.screens.task

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Checklist
import androidx.compose.material.icons.filled.ErrorOutline
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.tt.honeyDue.models.TaskSuggestionResponse
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.ui.components.common.StandardCard
import com.tt.honeyDue.ui.theme.AppRadius
import com.tt.honeyDue.ui.theme.AppSpacing
import com.tt.honeyDue.util.ErrorMessageParser

/**
 * Standalone screen that lets users pick personalized task suggestions
 * outside the onboarding flow. Android port of iOS TaskSuggestionsView as
 * a regular destination (not an inline dropdown).
 *
 * Flow:
 *  1. On entry, loads via APILayer.getTaskSuggestions(residenceId).
 *  2. Each row has an Accept button that fires APILayer.createTask with
 *     template fields + templateId backlink.
 *  3. Non-onboarding analytics event task_suggestion_accepted fires on
 *     each successful accept.
 *  4. Skip is a pop with no task created (handled by onNavigateBack).
 *  5. Supports pull-to-refresh.
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TaskSuggestionsScreen(
    residenceId: Int,
    onNavigateBack: () -> Unit,
    onSuggestionAccepted: (templateId: Int) -> Unit = {},
    viewModel: TaskSuggestionsViewModel = viewModel {
        TaskSuggestionsViewModel(residenceId = residenceId)
    }
) {
    val suggestionsState by viewModel.suggestionsState.collectAsStateWithLifecycle()
    val acceptState by viewModel.acceptState.collectAsStateWithLifecycle()
    var isRefreshing by remember { mutableStateOf(false) }

    LaunchedEffect(Unit) {
        if (suggestionsState is ApiResult.Idle) {
            viewModel.load()
        }
    }

    LaunchedEffect(suggestionsState) {
        if (suggestionsState !is ApiResult.Loading) {
            isRefreshing = false
        }
    }

    LaunchedEffect(acceptState) {
        if (acceptState is ApiResult.Success) {
            val tid = viewModel.lastAcceptedTemplateId
            if (tid != null) onSuggestionAccepted(tid)
            viewModel.resetAcceptState()
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Text(text = "Suggested Tasks", fontWeight = FontWeight.SemiBold)
                },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
                    }
                },
                actions = {
                    OutlinedButton(
                        onClick = onNavigateBack,
                        modifier = Modifier.padding(end = AppSpacing.md)
                    ) { Text("Skip") }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.surface
                )
            )
        }
    ) { paddingValues ->
        PullToRefreshBox(
            isRefreshing = isRefreshing,
            onRefresh = {
                isRefreshing = true
                viewModel.load()
            },
            modifier = Modifier.fillMaxSize().padding(paddingValues)
        ) {
            when (val state = suggestionsState) {
                is ApiResult.Loading, ApiResult.Idle -> {
                    Box(Modifier.fillMaxSize(), Alignment.Center) {
                        CircularProgressIndicator()
                    }
                }
                is ApiResult.Error -> {
                    ErrorView(
                        message = ErrorMessageParser.parse(state.message),
                        onRetry = { viewModel.retry() }
                    )
                }
                is ApiResult.Success -> {
                    if (state.data.suggestions.isEmpty()) {
                        EmptyView()
                    } else {
                        SuggestionsList(
                            suggestions = state.data.suggestions,
                            acceptState = acceptState,
                            onAccept = viewModel::accept
                        )
                    }
                }
            }

            (acceptState as? ApiResult.Error)?.let { err ->
                Box(
                    modifier = Modifier.fillMaxSize().padding(AppSpacing.lg),
                    contentAlignment = Alignment.BottomCenter
                ) {
                    Surface(
                        color = MaterialTheme.colorScheme.errorContainer,
                        shape = RoundedCornerShape(AppRadius.md),
                        tonalElevation = 4.dp
                    ) {
                        Row(
                            modifier = Modifier.padding(AppSpacing.md),
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.spacedBy(AppSpacing.sm)
                        ) {
                            Icon(
                                imageVector = Icons.Default.ErrorOutline,
                                contentDescription = "Error",
                                tint = MaterialTheme.colorScheme.error
                            )
                            Text(
                                text = ErrorMessageParser.parse(err.message),
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.onErrorContainer
                            )
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun SuggestionsList(
    suggestions: List<TaskSuggestionResponse>,
    acceptState: ApiResult<*>,
    onAccept: (TaskSuggestionResponse) -> Unit
) {
    LazyColumn(
        modifier = Modifier.fillMaxSize(),
        contentPadding = PaddingValues(
            start = AppSpacing.lg,
            end = AppSpacing.lg,
            top = AppSpacing.md,
            bottom = AppSpacing.xl
        ),
        verticalArrangement = Arrangement.spacedBy(AppSpacing.sm)
    ) {
        items(suggestions, key = { it.template.id }) { suggestion ->
            SuggestionRow(
                suggestion = suggestion,
                isAccepting = acceptState is ApiResult.Loading,
                onAccept = { onAccept(suggestion) }
            )
        }
    }
}

@Composable
private fun SuggestionRow(
    suggestion: TaskSuggestionResponse,
    isAccepting: Boolean,
    onAccept: () -> Unit
) {
    val template = suggestion.template
    StandardCard(
        modifier = Modifier.fillMaxWidth(),
        contentPadding = AppSpacing.md
    ) {
        Column(verticalArrangement = Arrangement.spacedBy(AppSpacing.sm)) {
            Text(
                text = template.title,
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.SemiBold,
                color = MaterialTheme.colorScheme.onSurface
            )
            if (template.description.isNotBlank()) {
                Text(
                    text = template.description,
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(AppSpacing.sm)
            ) {
                Text(
                    text = template.categoryName,
                    style = MaterialTheme.typography.labelMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                Text(
                    text = "•",
                    style = MaterialTheme.typography.labelMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                Text(
                    text = template.frequencyDisplay,
                    style = MaterialTheme.typography.labelMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
            Button(
                onClick = onAccept,
                enabled = !isAccepting,
                modifier = Modifier.fillMaxWidth().height(44.dp),
                shape = RoundedCornerShape(AppRadius.md)
            ) {
                if (isAccepting) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(18.dp),
                        color = MaterialTheme.colorScheme.onPrimary,
                        strokeWidth = 2.dp
                    )
                } else {
                    Icon(Icons.Default.Check, contentDescription = null) // decorative
                    Spacer(Modifier.width(AppSpacing.sm))
                    Text("Accept", fontWeight = FontWeight.SemiBold)
                }
            }
        }
    }
}

@Composable
private fun ErrorView(message: String, onRetry: () -> Unit) {
    Column(
        modifier = Modifier.fillMaxSize().padding(AppSpacing.xl),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(AppSpacing.md, Alignment.CenterVertically)
    ) {
        Icon(
            imageVector = Icons.Default.ErrorOutline,
            contentDescription = "Error",
            modifier = Modifier.size(48.dp),
            tint = MaterialTheme.colorScheme.error
        )
        Text(text = "Couldn't load suggestions", style = MaterialTheme.typography.titleMedium)
        Text(
            text = message,
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
        OutlinedButton(onClick = onRetry) { Text("Retry") }
    }
}

@Composable
private fun EmptyView() {
    Column(
        modifier = Modifier.fillMaxSize().padding(AppSpacing.xl),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(AppSpacing.md, Alignment.CenterVertically)
    ) {
        Icon(
            imageVector = Icons.Default.Checklist,
            contentDescription = null, // decorative
            modifier = Modifier.size(48.dp),
            tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)
        )
        Text(text = "No suggestions yet", style = MaterialTheme.typography.titleMedium)
        Text(
            text = "Complete your home profile to see personalized recommendations.",
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}
