package com.example.notesai.presentation.screens.main

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.lazy.staggeredgrid.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Create
import androidx.compose.material.icons.filled.Search
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.example.notesai.data.model.Category
import com.example.notesai.data.model.Note
import com.example.notesai.presentation.components.EmptyState
import com.example.notesai.presentation.screens.main.components.CategoryCard
import com.example.notesai.presentation.screens.main.components.NoteCard

@Composable
fun MainScreen(
    categories: List<Category>,
    notes: List<Note>,
    selectedCategory: Category?,
    searchQuery: String,
    onCategoryClick: (Category) -> Unit,
    onNoteClick: (Note) -> Unit,
    onPinToggle: (Note) -> Unit,
    onCategoryDelete: (Category) -> Unit,
    onCategoryEdit: (Category, String, Long, Long) -> Unit,
    onCategoryPin: (Category) -> Unit, // NEW: Pin category callback
    onNoteEdit: (Note) -> Unit = {},
    onNoteDelete: (Note) -> Unit = {}
) {
    Column(modifier = Modifier.fillMaxSize()) {
        if (selectedCategory == null) {
            // Beranda: Tampilkan kategori dengan search filtering
            if (categories.isEmpty()) {
                EmptyState(
                    icon = Icons.Default.Create,
                    message = "Buat kategori pertama Anda",
                    subtitle = "Tekan tombol + untuk memulai"
                )
            } else {
                // Filter kategori berdasarkan searchQuery
                val filteredCategories = if (searchQuery.isBlank()) {
                    categories
                } else {
                    categories.filter { category ->
                        // 1. Cek nama kategori cocok
                        val categoryNameMatches = category.name.contains(searchQuery, ignoreCase = true)

                        // 2. Cek ada catatan yang cocok di kategori ini
                        val hasMatchingNotes = notes.any { note ->
                            note.categoryId == category.id &&
                                    !note.isDeleted &&
                                    !note.isArchived &&
                                    (note.title.contains(searchQuery, ignoreCase = true) ||
                                            note.description.contains(searchQuery, ignoreCase = true) ||
                                            note.content.contains(searchQuery, ignoreCase = true))
                        }

                        // Kategori muncul jika salah satu kondisi terpenuhi
                        categoryNameMatches || hasMatchingNotes
                    }
                }

                if (filteredCategories.isEmpty()) {
                    EmptyState(
                        icon = Icons.Default.Search,
                        message = "Kategori tidak ditemukan",
                        subtitle = "Coba kata kunci lain"
                    )
                } else {
                    LazyVerticalStaggeredGrid(
                        columns = StaggeredGridCells.Fixed(2),
                        contentPadding = PaddingValues(
                            start = 16.dp,
                            end = 16.dp,
                            top = 16.dp,
                            bottom = 100.dp
                        ),
                        horizontalArrangement = Arrangement.spacedBy(12.dp),
                        verticalItemSpacing = 12.dp,
                        modifier = Modifier.fillMaxSize()
                    ) {
                        items(filteredCategories) { category ->
                            CategoryCard(
                                category = category,
                                noteCount = notes.count {
                                    it.categoryId == category.id &&
                                            !it.isDeleted &&
                                            !it.isArchived
                                },
                                onClick = { onCategoryClick(category) },
                                onDelete = { onCategoryDelete(category) },
                                onEdit = { name, gradientStart, gradientEnd ->
                                    onCategoryEdit(category, name, gradientStart, gradientEnd)
                                },
                                onPin = { onCategoryPin(category) } // NEW: Pass pin callback
                            )
                        }
                    }
                }
            }
        } else {
            val categoryNotes = notes
                .filter {
                    it.categoryId == selectedCategory.id &&
                            !it.isDeleted &&
                            !it.isArchived &&
                            (searchQuery.isEmpty() ||
                                    it.title.contains(searchQuery, ignoreCase = true) ||
                                    it.content.contains(searchQuery, ignoreCase = true))
                }
                .sortedWith(compareByDescending<Note> { it.isPinned }.thenByDescending { it.timestamp })

            if (categoryNotes.isEmpty()) {
                EmptyState(
                    icon = Icons.Default.Add,
                    message = if (searchQuery.isEmpty()) "Belum ada catatan" else "Tidak ada hasil",
                    subtitle = if (searchQuery.isEmpty()) "Tekan tombol + untuk membuat catatan" else "Coba kata kunci lain"
                )
            } else {
                LazyVerticalStaggeredGrid(
                    columns = StaggeredGridCells.Fixed(2),
                    contentPadding = PaddingValues(
                        start = 16.dp,
                        end = 16.dp,
                        top = 16.dp,
                        bottom = 100.dp
                    ),
                    horizontalArrangement = Arrangement.spacedBy(12.dp),
                    verticalItemSpacing = 12.dp,
                    modifier = Modifier.fillMaxSize()
                ) {
                    items(categoryNotes) { note ->
                        NoteCard(
                            note = note,
                            onClick = { onNoteClick(note) },
                            onPinClick = { onPinToggle(note) },
                            onEdit = { onNoteEdit(note) },
                            onDelete = { onNoteDelete(note) }
                        )
                    }
                }
            }
        }
    }
}