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

import androidx.compose.animation.*
import androidx.compose.animation.core.*
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
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.LocalClipboardManager
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.AnnotatedString
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 androidx.compose.ui.zIndex
import com.example.notesai.config.APIKey
import com.example.notesai.data.local.DataStoreManager
import com.example.notesai.data.model.*
import com.example.notesai.util.Constants
import com.google.ai.client.generativeai.GenerativeModel
import com.google.ai.client.generativeai.type.generationConfig
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.*
import com.example.notesai.presentation.screens.ai.components.*
import com.example.notesai.util.AppColors
import com.example.notesai.util.FileParseResult

private const val MAX_CHAT_TITLE_LENGTH = 30

private fun String.toSafeChatPreview(maxLength: Int = MAX_CHAT_TITLE_LENGTH): String {
    return if (this.length > maxLength) {
        this.take(maxLength).trim() + "..."
    } else {
        this.trim()
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AIHelperScreen(
    categories: List<Category>,
    notes: List<Note>,
    onShowDrawer: () -> Unit = {}
) {
    val context = LocalContext.current
    val dataStoreManager = remember { DataStoreManager(context) }

    var prompt by remember { mutableStateOf("") }
    var isLoading by remember { mutableStateOf(false) }
    var selectedCategory by remember { mutableStateOf<Category?>(null) }
    var errorMessage by remember { mutableStateOf("") }
    var chatMessages by remember { mutableStateOf(listOf<ChatMessage>()) }
    var showCopiedMessage by remember { mutableStateOf(false) }
    var copiedMessageId by remember { mutableStateOf("") }
    var showHistoryDrawer by remember { mutableStateOf(false) }
    var currentChatId by remember { mutableStateOf<String?>(null) }

    // File Upload States
    var uploadedFile by remember { mutableStateOf<FileParseResult.Success?>(null) }
    var isGeneratingSummary by remember { mutableStateOf(false) }

    val scope = rememberCoroutineScope()
    val clipboardManager = LocalClipboardManager.current
    val scrollState = rememberScrollState()

    // Load chat histories
    val chatHistories by dataStoreManager.chatHistoryFlow.collectAsState(initial = emptyList())

    // Inisialisasi Gemini Model
    val generativeModel = remember {
        GenerativeModel(
            modelName = "gemini-2.5-flash",
            apiKey = APIKey.GEMINI_API_KEY,
            generationConfig = generationConfig {
                temperature = 0.8f
                topK = 40
                topP = 0.95f
                maxOutputTokens = 4096
                candidateCount = 1
            }
        )
    }

    // Auto scroll ke bawah saat ada pesan baru
    LaunchedEffect(chatMessages.size) {
        if (chatMessages.isNotEmpty()) {
            delay(100)
            scrollState.animateScrollTo(scrollState.maxValue)
        }
    }

    // Function to save chat history
    fun saveChatHistory() {
        if (chatMessages.isNotEmpty()) {
            scope.launch {
                val lastMessage = chatMessages.lastOrNull()?.message ?: ""
                val preview = lastMessage.toSafeChatPreview()

                val chatHistory = ChatHistory(
                    id = currentChatId ?: UUID.randomUUID().toString(),
                    categoryId = selectedCategory?.id,
                    categoryName = selectedCategory?.name ?: "Semua Kategori",
                    messages = chatMessages.map { it.toSerializable() },
                    lastMessagePreview = preview,
                    customTitle = null,
                    timestamp = System.currentTimeMillis()
                )

                dataStoreManager.addChatHistory(chatHistory)
                currentChatId = chatHistory.id
            }
        }
    }

    // Function to load chat history
    fun loadChatHistory(history: ChatHistory) {
        chatMessages = history.messages.map { it.toChatMessage() }
        currentChatId = history.id
        selectedCategory = categories.find { it.id == history.categoryId }
        showHistoryDrawer = false
    }

    // Function to start new chat
    fun startNewChat() {
        chatMessages = emptyList()
        currentChatId = null
        errorMessage = ""
        showHistoryDrawer = false
        uploadedFile = null
        isGeneratingSummary = false
    }

    Box(
        modifier = Modifier.fillMaxSize()
    ) {
        // MAIN CONTENT - Layer 1 (paling bawah)
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(AppColors.Background)
        ) {
            // UPDATED: Floating Top Bar
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp, vertical = 8.dp)
            ) {
                Surface(
                    color = AppColors.SurfaceElevated,
                    shape = RoundedCornerShape(Constants.Radius.ExtraLarge.dp),
                    shadowElevation = Constants.Elevation.Large.dp
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(horizontal = 12.dp, vertical = 8.dp),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        // History Drawer Button
                        IconButton(
                            onClick = {
                                onShowDrawer() // Panggil callback ke parent
                            },
                            modifier = Modifier
                                .size(40.dp)
                                .background(
                                    AppColors.Primary.copy(alpha = 0.1f),
                                    CircleShape
                                )
                        ) {
                            Icon(
                                Icons.Default.Menu,
                                contentDescription = "Menu",
                                tint = AppColors.Primary,
                                modifier = Modifier.size(20.dp)
                            )
                        }

                        // Category Badge
                        Surface(
                            color = AppColors.Primary.copy(alpha = 0.1f),
                            shape = RoundedCornerShape(Constants.Radius.Medium.dp)
                        ) {
                            Row(
                                modifier = Modifier.padding(
                                    horizontal = Constants.Spacing.Medium.dp,
                                    vertical = Constants.Spacing.Small.dp
                                ),
                                horizontalArrangement = Arrangement.spacedBy(6.dp),
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Icon(
                                    Icons.Default.Folder,
                                    contentDescription = null,
                                    tint = AppColors.Primary,
                                    modifier = Modifier.size(16.dp)
                                )
                                Text(
                                    selectedCategory?.name ?: "Semua Kategori",
                                    color = AppColors.Primary,
                                    fontSize = 13.sp,
                                    fontWeight = FontWeight.SemiBold
                                )
                            }
                        }

                        // New Chat Button
                        if (chatMessages.isNotEmpty()) {
                            Button(
                                onClick = { startNewChat() },
                                colors = ButtonDefaults.buttonColors(
                                    containerColor = AppColors.Primary
                                ),
                                shape = RoundedCornerShape(Constants.Radius.Medium.dp),
                                contentPadding = PaddingValues(
                                    horizontal = Constants.Spacing.Medium.dp,
                                    vertical = Constants.Spacing.Small.dp
                                )
                            ) {
                                Icon(
                                    Icons.Default.Add,
                                    contentDescription = null,
                                    modifier = Modifier.size(18.dp)
                                )
                                Spacer(modifier = Modifier.width(6.dp))
                                Text(
                                    "Baru",
                                    fontSize = 14.sp,
                                    fontWeight = FontWeight.SemiBold
                                )
                            }
                        }
                    }
                }
            }

            // Chat Area
            Box(
                modifier = Modifier
                    .weight(1f)
                    .fillMaxWidth()
            ) {
                if (chatMessages.isEmpty()) {
                    // Welcome State - Optimized Layout
                    Column(
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(horizontal = 24.dp, vertical = 16.dp)
                            .verticalScroll(rememberScrollState()),
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.spacedBy(16.dp)
                    ) {
                        Spacer(modifier = Modifier.weight(0.5f))

                        Box(
                            modifier = Modifier
                                .size(64.dp)
                                .background(
                                    color = AppColors.Primary.copy(alpha = 0.1f),
                                    shape = CircleShape
                                ),
                            contentAlignment = Alignment.Center
                        ) {
                            Icon(
                                Icons.Default.AutoAwesome,
                                contentDescription = null,
                                modifier = Modifier.size(32.dp),
                                tint = AppColors.Primary
                            )
                        }

                        Text(
                            "AI Assistant",
                            style = MaterialTheme.typography.headlineMedium,
                            color = AppColors.OnBackground,
                            fontWeight = FontWeight.Bold,
                            fontSize = 24.sp
                        )

                        Text(
                            "Tanyakan apa saja tentang catatan Anda",
                            style = MaterialTheme.typography.bodyMedium,
                            color = AppColors.OnSurfaceVariant,
                            textAlign = TextAlign.Center,
                            fontSize = 14.sp
                        )

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

                        // Suggestion Chips - Lebih besar
                        Column(
                            horizontalAlignment = Alignment.CenterHorizontally,
                            verticalArrangement = Arrangement.spacedBy(10.dp),
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            Text(
                                "Contoh pertanyaan:",
                                style = MaterialTheme.typography.labelMedium,
                                color = AppColors.OnSurfaceTertiary,
                                fontSize = 13.sp
                            )
                            SuggestionChip("Analisis catatan saya") { prompt = it }
                            SuggestionChip("Buat ringkasan") { prompt = it }
                            SuggestionChip("Berikan saran organisasi") { prompt = it }
                        }

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

                        // File Upload Button - PENTING: Jangan dihapus!
                        FileUploadButton(
                            onFileSelected = { fileResult ->
                                uploadedFile = fileResult

                                // Auto-generate summary
                                scope.launch {
                                    isGeneratingSummary = true

                                    try {
                                        val summaryPrompt = """
                                        Buatkan ringkasan dari dokumen berikut dalam bahasa Indonesia:
                                        
                                        Judul File: ${fileResult.fileName}
                                        Tipe: ${fileResult.fileType}
                                        Jumlah Kata: ${fileResult.wordCount}
                                        
                                        Konten:
                                        ${fileResult.content}
                                        
                                        Buat ringkasan yang:
                                        1. Mencakup poin-poin utama
                                        2. Terstruktur dengan baik (gunakan markdown)
                                        3. Mudah dipahami
                                        4. Maksimal 300 kata
                                        """.trimIndent()

                                        // Add user message
                                        chatMessages = chatMessages + ChatMessage(
                                            message = "📄 Upload file: ${fileResult.fileName}\n\nMohon buatkan ringkasan dari file ini.",
                                            isUser = true
                                        )

                                        // Scroll to bottom to show loading
                                        delay(100)
                                        scrollState.animateScrollTo(scrollState.maxValue)

                                        // Generate summary dengan Gemini
                                        val response =
                                            generativeModel.generateContent(summaryPrompt)
                                        val summary = response.text ?: "Gagal membuat ringkasan"

                                        // Add AI response
                                        chatMessages = chatMessages + ChatMessage(
                                            message = summary,
                                            isUser = false
                                        )

                                        saveChatHistory()
                                    } catch (e: Exception) {
                                        errorMessage = "⚠️ Gagal membuat ringkasan: ${e.message}"
                                    } finally {
                                        isGeneratingSummary = false
                                        uploadedFile = null
                                    }
                                }
                            },
                            onError = { error ->
                                errorMessage = error
                            },
                            modifier = Modifier.fillMaxWidth()
                        )

                        Spacer(modifier = Modifier.weight(0.5f))
                    }
                } else {
                    // Chat Messages - UPDATED: Bottom padding dari 100dp ke 120dp
                    Column(
                        modifier = Modifier
                            .fillMaxSize()
                            .verticalScroll(scrollState)
                            .padding(start = 16.dp, end = 16.dp, top = 16.dp, bottom = 120.dp)
                    ) {
                        chatMessages.forEach { message ->
                            ChatBubble(
                                message = message,
                                onCopy = { textToCopy ->
                                    clipboardManager.setText(AnnotatedString(textToCopy))
                                    copiedMessageId = message.id
                                    showCopiedMessage = true
                                    scope.launch {
                                        delay(2000)
                                        showCopiedMessage = false
                                    }
                                },
                                showCopied = showCopiedMessage && copiedMessageId == message.id
                            )
                            Spacer(modifier = Modifier.height(12.dp))
                        }

                        // Loading Indicator
                        if (isLoading || isGeneratingSummary) {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(vertical = 8.dp),
                                horizontalArrangement = Arrangement.Start
                            ) {
                                Surface(
                                    color = AppColors.SurfaceVariant,
                                    shape = RoundedCornerShape(16.dp)
                                ) {
                                    Row(
                                        modifier = Modifier.padding(16.dp),
                                        verticalAlignment = Alignment.CenterVertically,
                                        horizontalArrangement = Arrangement.spacedBy(12.dp)
                                    ) {
                                        CircularProgressIndicator(
                                            modifier = Modifier.size(20.dp),
                                            color = if (isGeneratingSummary) AppColors.Secondary else AppColors.Primary,
                                            strokeWidth = 2.dp
                                        )
                                        Text(
                                            if (isGeneratingSummary) "Membuat ringkasan..." else "AI sedang berpikir...",
                                            color = AppColors.OnSurfaceVariant,
                                            style = MaterialTheme.typography.bodyMedium
                                        )
                                    }
                                }
                            }
                        }

                        // Error Message
                        if (errorMessage.isNotEmpty()) {
                            Surface(
                                modifier = Modifier.fillMaxWidth(),
                                color = AppColors.Error.copy(alpha = 0.1f),
                                shape = RoundedCornerShape(12.dp)
                            ) {
                                Row(
                                    modifier = Modifier.padding(12.dp),
                                    verticalAlignment = Alignment.CenterVertically,
                                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                                ) {
                                    Icon(
                                        Icons.Default.Warning,
                                        contentDescription = null,
                                        tint = AppColors.Error,
                                        modifier = Modifier.size(20.dp)
                                    )
                                    Text(
                                        errorMessage,
                                        color = AppColors.Error,
                                        style = MaterialTheme.typography.bodySmall
                                    )
                                }
                            }
                        }
                    }
                }
            }

            // Input Area - Layer 2 (di atas chat, tapi di bawah drawer)
            Surface(
                color = AppColors.Surface,
                shadowElevation = 8.dp,
                shape = RoundedCornerShape(topStart = 20.dp, topEnd = 20.dp)
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    // Upload File Button (di atas input text)
                    if (chatMessages.isNotEmpty() && !isGeneratingSummary && !isLoading) {
                        FileUploadButton(
                            onFileSelected = { fileResult ->
                                uploadedFile = fileResult

                                scope.launch {
                                    isGeneratingSummary = true

                                    try {
                                        val summaryPrompt = """
                                        Buatkan ringkasan dari dokumen berikut dalam bahasa Indonesia:
                                        
                                        Judul File: ${fileResult.fileName}
                                        Tipe: ${fileResult.fileType}
                                        Jumlah Kata: ${fileResult.wordCount}
                                        
                                        Konten:
                                        ${fileResult.content}
                                        
                                        Buat ringkasan yang:
                                        1. Mencakup poin-poin utama
                                        2. Terstruktur dengan baik (gunakan markdown)
                                        3. Mudah dipahami
                                        4. Maksimal 300 kata
                                        """.trimIndent()

                                        chatMessages = chatMessages + ChatMessage(
                                            message = "📄 Upload file: ${fileResult.fileName}\n\nMohon buatkan ringkasan dari file ini.",
                                            isUser = true
                                        )

                                        delay(100)
                                        scrollState.animateScrollTo(scrollState.maxValue)

                                        val response =
                                            generativeModel.generateContent(summaryPrompt)
                                        val summary = response.text ?: "Gagal membuat ringkasan"

                                        chatMessages = chatMessages + ChatMessage(
                                            message = summary,
                                            isUser = false
                                        )

                                        saveChatHistory()
                                    } catch (e: Exception) {
                                        errorMessage = "⚠️ Gagal membuat ringkasan: ${e.message}"
                                    } finally {
                                        isGeneratingSummary = false
                                        uploadedFile = null
                                    }
                                }
                            },
                            onError = { error ->
                                errorMessage = error
                            },
                            modifier = Modifier.fillMaxWidth()
                        )
                    }

                    // Text Input & Send Button
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        verticalAlignment = Alignment.Bottom,
                        horizontalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        OutlinedTextField(
                            value = prompt,
                            onValueChange = { prompt = it },
                            placeholder = {
                                Text(
                                    "Ketik pesan...",
                                    color = AppColors.OnSurfaceTertiary
                                )
                            },
                            modifier = Modifier
                                .weight(1f)
                                .heightIn(min = 48.dp, max = 120.dp),
                            colors = OutlinedTextFieldDefaults.colors(
                                focusedTextColor = AppColors.OnBackground,
                                unfocusedTextColor = AppColors.OnSurface,
                                focusedContainerColor = AppColors.SurfaceVariant,
                                unfocusedContainerColor = AppColors.SurfaceVariant,
                                cursorColor = AppColors.Primary,
                                focusedBorderColor = AppColors.Primary,
                                unfocusedBorderColor = Color.Transparent
                            ),
                            shape = RoundedCornerShape(24.dp),
                            maxLines = 4
                        )

                        // Send Button
                        FloatingActionButton(
                            onClick = {
                                if (prompt.isNotBlank() && !isLoading) {
                                    scope.launch {
                                        chatMessages = chatMessages + ChatMessage(
                                            message = prompt,
                                            isUser = true
                                        )

                                        val userPrompt = prompt
                                        prompt = ""
                                        isLoading = true
                                        errorMessage = ""

                                        try {
                                            val filteredNotes = if (selectedCategory != null) {
                                                notes.filter { it.categoryId == selectedCategory!!.id && !it.isArchived }
                                            } else {
                                                notes.filter { !it.isArchived }
                                            }

                                            val notesContext = buildString {
                                                appendLine("Data catatan pengguna:")
                                                appendLine("Total catatan: ${filteredNotes.size}")
                                                appendLine("Kategori: ${selectedCategory?.name ?: "Semua"}")
                                                appendLine()
                                                appendLine("Daftar catatan:")
                                                filteredNotes.take(10).forEach { note ->
                                                    appendLine("- Judul: ${note.title}")
                                                    appendLine("  Isi: ${note.content.take(100)}")
                                                    appendLine()
                                                }
                                            }

                                            val fullPrompt =
                                                "$notesContext\n\nPertanyaan: $userPrompt\n\nBerikan jawaban dalam bahasa Indonesia yang natural dan membantu."
                                            val result = generativeModel.generateContent(fullPrompt)
                                            val response =
                                                result.text ?: "Tidak ada respons dari AI"

                                            chatMessages = chatMessages + ChatMessage(
                                                message = response,
                                                isUser = false
                                            )

                                            saveChatHistory()
                                        } catch (e: Exception) {
                                            errorMessage = when {
                                                e.message?.contains(
                                                    "quota",
                                                    ignoreCase = true
                                                ) == true ->
                                                    "⚠️ Kuota API habis. Silakan coba lagi nanti atau hubungi developer."

                                                e.message?.contains(
                                                    "404",
                                                    ignoreCase = true
                                                ) == true ||
                                                        e.message?.contains(
                                                            "not found",
                                                            ignoreCase = true
                                                        ) == true ->
                                                    "⚠️ Model AI tidak ditemukan. Silakan hubungi developer."

                                                e.message?.contains(
                                                    "401",
                                                    ignoreCase = true
                                                ) == true ||
                                                        e.message?.contains(
                                                            "API key",
                                                            ignoreCase = true
                                                        ) == true ->
                                                    "⚠️ API key tidak valid. Silakan hubungi developer."

                                                e.message?.contains(
                                                    "timeout",
                                                    ignoreCase = true
                                                ) == true ->
                                                    "⚠️ Koneksi timeout. Periksa koneksi internet Anda."

                                                e.message?.contains(
                                                    "network",
                                                    ignoreCase = true
                                                ) == true ->
                                                    "⚠️ Tidak ada koneksi internet. Silakan periksa koneksi Anda."

                                                else ->
                                                    "⚠️ Terjadi kesalahan: ${e.message?.take(100) ?: "Unknown error"}"
                                            }
                                        } finally {
                                            isLoading = false
                                        }
                                    }
                                }
                            },
                            containerColor = AppColors.Primary,
                            modifier = Modifier.size(48.dp)
                        ) {
                            Icon(
                                Icons.Default.Send,
                                contentDescription = "Send",
                                tint = Color.White,
                                modifier = Modifier.size(20.dp)
                            )
                        }
                    }
                }
            }
        }
    }
}