package com.example.notesai.presentation.screens.ai.components

import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.*
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.notesai.util.AppColors
import com.example.notesai.util.Constants
import com.example.notesai.util.FileParser
import com.example.notesai.util.FileParseResult
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

@Composable
fun FileUploadButton(
    onFileSelected: (FileParseResult.Success) -> Unit,
    onError: (String) -> Unit,
    modifier: Modifier = Modifier
) {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    var isProcessing by remember { mutableStateOf(false) }
    var selectedFileName by remember { mutableStateOf<String?>(null) }

    // File picker launcher
    val filePicker = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent()
    ) { uri: Uri? ->
        uri?.let {
            scope.launch {
                isProcessing = true
                try {
                    // Get file info
                    val fileSize = FileParser.getFileSize(context, uri)

                    // Check file size (max 10MB)
                    if (fileSize > 10 * 1024 * 1024) {
                        onError("File terlalu besar. Maksimal 10MB")
                        isProcessing = false
                        return@launch
                    }

                    // Parse file
                    val result = withContext(Dispatchers.IO) {
                        FileParser.parseFile(context, uri)
                    }

                    when (result) {
                        is FileParseResult.Success -> {
                            selectedFileName = result.fileName
                            onFileSelected(result)
                        }
                        is FileParseResult.Error -> {
                            onError(result.message)
                        }
                    }
                } catch (e: Exception) {
                    onError("Gagal memproses file: ${e.message}")
                } finally {
                    isProcessing = false
                }
            }
        }
    }

    Button(
        onClick = {
            // Launch file picker untuk PDF, TXT, DOCX
            filePicker.launch("*/*")
        },
        enabled = !isProcessing,
        colors = ButtonDefaults.buttonColors(
            containerColor = AppColors.Secondary.copy(alpha = 0.15f),
            contentColor = AppColors.Secondary,
            disabledContainerColor = AppColors.SurfaceVariant,
            disabledContentColor = AppColors.OnSurfaceVariant
        ),
        shape = RoundedCornerShape(Constants.Radius.Medium.dp),
        modifier = modifier,
        contentPadding = PaddingValues(
            horizontal = Constants.Spacing.Medium.dp,
            vertical = Constants.Spacing.Small.dp
        )
    ) {
        if (isProcessing) {
            CircularProgressIndicator(
                modifier = Modifier.size(20.dp),
                color = AppColors.Secondary,
                strokeWidth = 2.dp
            )
            Spacer(modifier = Modifier.width(8.dp))
            Text("Memproses...")
        } else {
            Icon(
                Icons.Default.AttachFile,
                contentDescription = "Upload File",
                modifier = Modifier.size(20.dp)
            )
            Spacer(modifier = Modifier.width(8.dp))
            Text(
                "Upload File",
                fontSize = 14.sp,
                fontWeight = FontWeight.SemiBold
            )
        }
    }
}

@Composable
fun FilePreviewCard(
    fileResult: FileParseResult.Success,
    onDismiss: () -> Unit,
    modifier: Modifier = Modifier
) {
    Surface(
        modifier = modifier,
        color = AppColors.SurfaceVariant,
        shape = RoundedCornerShape(Constants.Radius.Large.dp),
        shadowElevation = 4.dp
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            // Header
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Row(
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Icon(
                        when (fileResult.fileType) {
                            "PDF" -> Icons.Default.PictureAsPdf
                            "Word" -> Icons.Default.Description
                            else -> Icons.Default.TextSnippet
                        },
                        contentDescription = null,
                        tint = AppColors.Secondary,
                        modifier = Modifier.size(24.dp)
                    )

                    Column {
                        Text(
                            fileResult.fileName,
                            fontWeight = FontWeight.Bold,
                            fontSize = 14.sp,
                            color = AppColors.OnSurface
                        )
                        Text(
                            "${fileResult.fileType} • ${fileResult.wordCount} kata",
                            fontSize = 12.sp,
                            color = AppColors.OnSurfaceTertiary
                        )
                    }
                }

                IconButton(
                    onClick = onDismiss,
                    modifier = Modifier.size(32.dp)
                ) {
                    Icon(
                        Icons.Default.Close,
                        contentDescription = "Close",
                        tint = AppColors.OnSurfaceVariant
                    )
                }
            }

            Spacer(modifier = Modifier.height(12.dp))

            // Content Preview
            Surface(
                color = AppColors.Surface,
                shape = RoundedCornerShape(8.dp)
            ) {
                Text(
                    fileResult.content.take(200) + if (fileResult.content.length > 200) "..." else "",
                    modifier = Modifier.padding(12.dp),
                    fontSize = 12.sp,
                    color = AppColors.OnSurfaceVariant,
                    lineHeight = 18.sp
                )
            }
        }
    }
}