package com.tt.honeyDue.ui.screens

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import com.tt.honeyDue.testing.AccessibilityIds
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.tt.honeyDue.ui.components.AddContractorDialog
import com.tt.honeyDue.ui.components.ApiResultHandler
import com.tt.honeyDue.ui.components.HandleErrors
import com.tt.honeyDue.viewmodel.ContractorViewModel
import com.tt.honeyDue.models.ContractorSummary
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.repository.LookupsRepository
import com.tt.honeyDue.ui.subscription.UpgradeFeatureScreen
import com.tt.honeyDue.utils.SubscriptionHelper
import com.tt.honeyDue.analytics.PostHogAnalytics
import com.tt.honeyDue.analytics.AnalyticsEvents
import com.tt.honeyDue.ui.theme.*
import honeydue.composeapp.generated.resources.*
import org.jetbrains.compose.resources.stringResource

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ContractorsScreen(
    onNavigateBack: () -> Unit,
    onNavigateToContractorDetail: (Int) -> Unit,
    viewModel: ContractorViewModel = viewModel { ContractorViewModel() }
) {
    val contractorsState by viewModel.contractorsState.collectAsStateWithLifecycle()
    val deleteState by viewModel.deleteState.collectAsStateWithLifecycle()
    val toggleFavoriteState by viewModel.toggleFavoriteState.collectAsStateWithLifecycle()
    val contractorSpecialties by LookupsRepository.contractorSpecialties.collectAsStateWithLifecycle()

    // Check if screen should be blocked (limit=0)
    val isBlocked = SubscriptionHelper.isContractorsBlocked()
    // Get current count for checking when adding
    val currentCount = (contractorsState as? ApiResult.Success)?.data?.size ?: 0

    var showAddDialog by remember { mutableStateOf(false) }
    var showUpgradeDialog by remember { mutableStateOf(false) }
    var selectedFilter by remember { mutableStateOf<String?>(null) }
    var showFavoritesOnly by remember { mutableStateOf(false) }
    var searchQuery by remember { mutableStateOf("") }
    var showFiltersMenu by remember { mutableStateOf(false) }
    var isRefreshing by remember { mutableStateOf(false) }

    LaunchedEffect(Unit) {
        PostHogAnalytics.screen(AnalyticsEvents.CONTRACTOR_SCREEN_SHOWN)
        viewModel.loadContractors()
    }

    // Handle refresh state
    LaunchedEffect(contractorsState) {
        if (contractorsState !is ApiResult.Loading) {
            isRefreshing = false
        }
    }

    // Client-side filtering since backend doesn't support search/filter params
    val filteredContractors = remember(contractorsState, searchQuery, selectedFilter, showFavoritesOnly) {
        val contractors = (contractorsState as? ApiResult.Success)?.data ?: emptyList()
        contractors.filter { contractor ->
            val matchesSearch = searchQuery.isBlank() ||
                contractor.name.contains(searchQuery, ignoreCase = true) ||
                (contractor.company?.contains(searchQuery, ignoreCase = true) == true)
            val matchesSpecialty = selectedFilter == null ||
                contractor.specialties.any { it.name == selectedFilter }
            val matchesFavorite = !showFavoritesOnly || contractor.isFavorite
            matchesSearch && matchesSpecialty && matchesFavorite
        }
    }

    // Handle errors for delete contractor
    deleteState.HandleErrors(
        onRetry = { /* Handled in UI */ },
        errorTitle = stringResource(Res.string.contractors_failed_to_delete)
    )

    // Handle errors for toggle favorite
    toggleFavoriteState.HandleErrors(
        onRetry = { /* Handled in UI */ },
        errorTitle = stringResource(Res.string.contractors_failed_to_update_favorite)
    )

    LaunchedEffect(deleteState) {
        if (deleteState is ApiResult.Success) {
            viewModel.loadContractors()
            viewModel.resetDeleteState()
        }
    }

    LaunchedEffect(toggleFavoriteState) {
        if (toggleFavoriteState is ApiResult.Success) {
            viewModel.loadContractors()
            viewModel.resetToggleFavoriteState()
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(stringResource(Res.string.contractors_title), fontWeight = FontWeight.Bold) },
                actions = {
                    // Favorites filter toggle
                    IconButton(onClick = { showFavoritesOnly = !showFavoritesOnly }) {
                        Icon(
                            if (showFavoritesOnly) Icons.Default.Star else Icons.Default.StarOutline,
                            stringResource(Res.string.contractors_filter_favorites),
                            tint = if (showFavoritesOnly) MaterialTheme.colorScheme.tertiary else LocalContentColor.current
                        )
                    }

                    // Specialty filter menu
                    Box {
                        IconButton(onClick = { showFiltersMenu = true }) {
                            Icon(
                                Icons.Default.FilterList,
                                stringResource(Res.string.contractors_filter_specialty),
                                tint = if (selectedFilter != null) MaterialTheme.colorScheme.primary else LocalContentColor.current
                            )
                        }

                        DropdownMenu(
                            expanded = showFiltersMenu,
                            onDismissRequest = { showFiltersMenu = false }
                        ) {
                            DropdownMenuItem(
                                text = { Text(stringResource(Res.string.contractors_all_specialties)) },
                                onClick = {
                                    selectedFilter = null
                                    showFiltersMenu = false
                                },
                                leadingIcon = {
                                    if (selectedFilter == null) {
                                        Icon(Icons.Default.Check, null, tint = MaterialTheme.colorScheme.secondary)
                                    }
                                }
                            )
                            HorizontalDivider()
                            contractorSpecialties.forEach { specialty ->
                                DropdownMenuItem(
                                    text = { Text(specialty.name) },
                                    onClick = {
                                        selectedFilter = specialty.name
                                        showFiltersMenu = false
                                    },
                                    leadingIcon = {
                                        if (selectedFilter == specialty.name) {
                                            Icon(Icons.Default.Check, null, tint = MaterialTheme.colorScheme.secondary)
                                        }
                                    }
                                )
                            }
                        }
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.surface
                )
            )
        },
        floatingActionButton = {
            // Don't show FAB if screen is blocked (limit=0)
            if (!isBlocked.allowed) {
                Box(modifier = Modifier.padding(bottom = 80.dp)) {
                    FloatingActionButton(
                        onClick = {
                            // Check if user can add based on current count
                            val canAdd = SubscriptionHelper.canAddContractor(currentCount)
                            if (canAdd.allowed) {
                                showAddDialog = true
                            } else {
                                PostHogAnalytics.capture(
                                    AnalyticsEvents.CONTRACTOR_PAYWALL_SHOWN,
                                    mapOf("current_count" to currentCount)
                                )
                                showUpgradeDialog = true
                            }
                        },
                        containerColor = MaterialTheme.colorScheme.primary,
                        contentColor = MaterialTheme.colorScheme.onPrimary,
                        modifier = Modifier.testTag(AccessibilityIds.Contractor.addButton)
                    ) {
                        Icon(Icons.Default.Add, stringResource(Res.string.contractors_add_button))
                    }
                }
            }
        }
    ) { padding ->
        // Show upgrade prompt for the entire screen if blocked (limit=0)
        if (isBlocked.allowed) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(padding)
            ) {
                UpgradeFeatureScreen(
                    triggerKey = isBlocked.triggerKey ?: "view_contractors",
                    icon = Icons.Default.People,
                    onNavigateBack = onNavigateBack
                )
            }
        } else {
            WarmGradientBackground {
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(padding)
                        .imePadding()
                ) {
                    // Search bar
                    OutlinedTextField(
                        value = searchQuery,
                        onValueChange = { searchQuery = it },
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(horizontal = OrganicSpacing.medium, vertical = OrganicSpacing.small),
                        placeholder = { Text(stringResource(Res.string.contractors_search)) },
                        leadingIcon = { Icon(Icons.Default.Search, stringResource(Res.string.common_search)) },
                        trailingIcon = {
                            if (searchQuery.isNotEmpty()) {
                                IconButton(onClick = { searchQuery = "" }) {
                                    Icon(Icons.Default.Close, stringResource(Res.string.contractors_clear_search))
                                }
                            }
                        },
                        singleLine = true,
                        shape = OrganicShapes.medium,
                        colors = OutlinedTextFieldDefaults.colors(
                            focusedContainerColor = MaterialTheme.colorScheme.surface,
                            unfocusedContainerColor = MaterialTheme.colorScheme.surface,
                            focusedBorderColor = MaterialTheme.colorScheme.primary,
                            unfocusedBorderColor = MaterialTheme.colorScheme.outline
                        )
                    )

                    // Active filters display
                    if (selectedFilter != null || showFavoritesOnly) {
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(horizontal = OrganicSpacing.medium, vertical = OrganicSpacing.extraSmall),
                            horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.small)
                        ) {
                            if (showFavoritesOnly) {
                                FilterChip(
                                    selected = true,
                                    onClick = { showFavoritesOnly = false },
                                    label = { Text(stringResource(Res.string.contractors_favorites)) },
                                    leadingIcon = { Icon(Icons.Default.Star, null, modifier = Modifier.size(16.dp)) }
                                )
                            }
                            if (selectedFilter != null) {
                                FilterChip(
                                    selected = true,
                                    onClick = { selectedFilter = null },
                                    label = { Text(selectedFilter!!) },
                                    trailingIcon = { Icon(Icons.Default.Close, null, modifier = Modifier.size(16.dp)) }
                                )
                            }
                        }
                    }

                    ApiResultHandler(
                        state = contractorsState,
                        onRetry = {
                            viewModel.loadContractors()
                        },
                        errorTitle = stringResource(Res.string.contractors_failed_to_load),
                        loadingContent = {
                            if (!isRefreshing) {
                                CircularProgressIndicator(color = MaterialTheme.colorScheme.primary)
                            }
                        }
                    ) { _ ->
                        // Use filteredContractors for client-side filtering
                        if (filteredContractors.isEmpty()) {
                            // Empty state with organic styling
                            Box(
                                modifier = Modifier
                                    .fillMaxSize()
                                    .testTag(AccessibilityIds.Contractor.emptyStateView),
                                contentAlignment = Alignment.Center
                            ) {
                                Column(
                                    horizontalAlignment = Alignment.CenterHorizontally,
                                    verticalArrangement = Arrangement.spacedBy(OrganicSpacing.small)
                                ) {
                                    OrganicIconContainer(
                                        icon = Icons.Default.PersonAdd,
                                        size = 80.dp,
                                        iconSize = 40.dp,
                                        containerColor = MaterialTheme.colorScheme.primaryContainer,
                                        iconTint = MaterialTheme.colorScheme.onPrimaryContainer
                                    )
                                    Spacer(modifier = Modifier.height(OrganicSpacing.small))
                                    Text(
                                        if (searchQuery.isNotEmpty() || selectedFilter != null || showFavoritesOnly)
                                            stringResource(Res.string.contractors_no_results)
                                        else
                                            stringResource(Res.string.contractors_empty_title),
                                        style = MaterialTheme.typography.titleMedium,
                                        fontWeight = FontWeight.SemiBold,
                                        color = MaterialTheme.colorScheme.onSurface
                                    )
                                    if (searchQuery.isEmpty() && selectedFilter == null && !showFavoritesOnly) {
                                        Text(
                                            stringResource(Res.string.contractors_empty_subtitle_first),
                                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                                            style = MaterialTheme.typography.bodyMedium
                                        )
                                    }
                                }
                            }
                        } else {
                            PullToRefreshBox(
                                isRefreshing = isRefreshing,
                                onRefresh = {
                                    isRefreshing = true
                                    viewModel.loadContractors()
                                },
                                modifier = Modifier.fillMaxSize()
                            ) {
                                LazyColumn(
                                    modifier = Modifier
                                        .fillMaxSize()
                                        .testTag(AccessibilityIds.Contractor.contractorsList),
                                    contentPadding = PaddingValues(OrganicSpacing.medium),
                                    verticalArrangement = Arrangement.spacedBy(OrganicSpacing.medium)
                                ) {
                                    items(filteredContractors, key = { it.id }) { contractor ->
                                        ContractorCard(
                                            contractor = contractor,
                                            onToggleFavorite = { viewModel.toggleFavorite(it) },
                                            onClick = { onNavigateToContractorDetail(it) }
                                        )
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    if (showAddDialog) {
        AddContractorDialog(
            onDismiss = { showAddDialog = false },
            onContractorSaved = {
                showAddDialog = false
                viewModel.loadContractors()
            }
        )
    }

    // Show upgrade dialog when user hits limit
    if (showUpgradeDialog) {
        AlertDialog(
            onDismissRequest = { showUpgradeDialog = false },
            title = { Text(stringResource(Res.string.contractors_upgrade_required)) },
            text = {
                Text(stringResource(Res.string.contractors_upgrade_message))
            },
            confirmButton = {
                TextButton(onClick = { showUpgradeDialog = false }) {
                    Text(stringResource(Res.string.common_ok))
                }
            }
        )
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun ContractorCard(
    contractor: ContractorSummary,
    onToggleFavorite: (Int) -> Unit,
    onClick: (Int) -> Unit,
    onLongPressEdit: ((Int) -> Unit)? = null,
    onLongPressDelete: ((Int) -> Unit)? = null
) {
    var showContextMenu by remember { mutableStateOf(false) }
    OrganicCard(
        modifier = Modifier
            .fillMaxWidth()
            .testTag(AccessibilityIds.withId(AccessibilityIds.Contractor.contractorCard, contractor.id))
            .combinedClickable(
                onClick = { onClick(contractor.id) },
                onLongClick = {
                    if (onLongPressEdit != null || onLongPressDelete != null) {
                        showContextMenu = true
                    }
                }
            )
    ) {
        // Long-press context menu
        DropdownMenu(
            expanded = showContextMenu,
            onDismissRequest = { showContextMenu = false },
            modifier = Modifier.testTag(AccessibilityIds.Contractor.contextMenu)
        ) {
            onLongPressEdit?.let { handler ->
                DropdownMenuItem(
                    text = { Text(stringResource(Res.string.common_edit)) },
                    leadingIcon = { Icon(Icons.Default.Edit, contentDescription = null) },
                    onClick = {
                        handler(contractor.id)
                        showContextMenu = false
                    }
                )
            }
            onLongPressDelete?.let { handler ->
                DropdownMenuItem(
                    text = { Text(stringResource(Res.string.common_delete)) },
                    leadingIcon = {
                        Icon(
                            Icons.Default.Delete,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.error
                        )
                    },
                    onClick = {
                        handler(contractor.id)
                        showContextMenu = false
                    }
                )
            }
        }
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(OrganicSpacing.medium),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // Avatar/Icon
            OrganicIconContainer(
                icon = Icons.Default.Person,
                size = 56.dp,
                iconSize = 32.dp,
                containerColor = MaterialTheme.colorScheme.primaryContainer,
                iconTint = MaterialTheme.colorScheme.onPrimaryContainer
            )

            Spacer(modifier = Modifier.width(OrganicSpacing.medium))

            Column(modifier = Modifier.weight(1f)) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Text(
                        text = contractor.name,
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.SemiBold,
                        color = MaterialTheme.colorScheme.onSurface,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                    if (contractor.isFavorite) {
                        Spacer(modifier = Modifier.width(OrganicSpacing.extraSmall))
                        Icon(
                            Icons.Default.Star,
                            contentDescription = stringResource(Res.string.contractors_favorite),
                            modifier = Modifier.size(16.dp),
                            tint = MaterialTheme.colorScheme.tertiary
                        )
                    }
                }

                if (contractor.company != null) {
                    Text(
                        text = contractor.company,
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                }

                Spacer(modifier = Modifier.height(OrganicSpacing.small))

                Row(
                    horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.medium),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    if (contractor.specialties.isNotEmpty()) {
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            Icon(
                                Icons.Default.WorkOutline,
                                contentDescription = null, // decorative
                                modifier = Modifier.size(14.dp),
                                tint = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                            Spacer(modifier = Modifier.width(OrganicSpacing.extraSmall))
                            Text(
                                text = contractor.specialties.first().name,
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }

                    if (contractor.rating != null && contractor.rating > 0) {
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            Icon(
                                Icons.Default.Star,
                                contentDescription = null, // decorative
                                modifier = Modifier.size(14.dp),
                                tint = MaterialTheme.colorScheme.tertiary
                            )
                            Spacer(modifier = Modifier.width(OrganicSpacing.extraSmall))
                            Text(
                                text = "${(contractor.rating * 10).toInt() / 10.0}",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant,
                                fontWeight = FontWeight.Medium
                            )
                        }
                    }

                    if (contractor.taskCount > 0) {
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            Icon(
                                Icons.Default.CheckCircle,
                                contentDescription = null, // decorative
                                modifier = Modifier.size(14.dp),
                                tint = MaterialTheme.colorScheme.secondary
                            )
                            Spacer(modifier = Modifier.width(OrganicSpacing.extraSmall))
                            Text(
                                text = stringResource(Res.string.contractors_tasks_count, contractor.taskCount),
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }
                }
            }

            // Favorite toggle button
            IconButton(
                onClick = { onToggleFavorite(contractor.id) }
            ) {
                Icon(
                    if (contractor.isFavorite) Icons.Default.Star else Icons.Default.StarOutline,
                    contentDescription = if (contractor.isFavorite) stringResource(Res.string.contractors_remove_from_favorites) else stringResource(Res.string.contractors_add_to_favorites),
                    tint = if (contractor.isFavorite) MaterialTheme.colorScheme.tertiary else MaterialTheme.colorScheme.onSurfaceVariant
                )
            }

            // Arrow icon
            Icon(
                Icons.Default.ChevronRight,
                contentDescription = stringResource(Res.string.contractors_view_details),
                tint = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}
