package com.example.notesai.presentation.screens.note

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.relocation.BringIntoViewRequester
import androidx.compose.foundation.relocation.bringIntoViewRequester
import androidx.compose.foundation.layout.imeNestedScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.*
import androidx.compose.material.icons.outlined.StarBorder
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.*
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.*
import com.example.notesai.data.model.Note
import com.example.notesai.presentation.screens.note.components.DraggableMiniMarkdownToolbar
import com.example.notesai.presentation.screens.note.editor.RichEditorState
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*
import kotlin.math.roundToInt
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner


@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@Composable
fun EditableFullScreenNoteView(
    note: Note,
    onBack: () -> Unit,
    onSave: (String, String) -> Unit,
    onArchive: () -> Unit,
    onDelete: () -> Unit,
    onPinToggle: () -> Unit
) {
    var title by remember { mutableStateOf(note.title) }
    var isContentFocused by remember { mutableStateOf(false) }

    val editorState = remember(note.id) {
        RichEditorState(
            AnnotatedStringSerializer.fromJson(note.content)
        )
    }

    val focusRequester = remember { FocusRequester() }
    val bringIntoViewRequester = remember { BringIntoViewRequester() }
    val scrollState = rememberScrollState()
    val scope = rememberCoroutineScope()
    val keyboard = LocalSoftwareKeyboardController.current

    fun ensureFocus() {
        focusRequester.requestFocus()
        keyboard?.show()
    }

    fun saveNote() {
        if (title.isNotBlank()) {
            onSave(
                title,
                AnnotatedStringSerializer.toJson(editorState.value.annotatedString)
            )
        }
    }

    // AUTO SAVE SAAT APP BACKGROUND / KELUAR
    val lifecycleOwner = LocalLifecycleOwner.current

    DisposableEffect(lifecycleOwner) {
        val observer = LifecycleEventObserver { _, event ->
            if (event == Lifecycle.Event.ON_STOP) {
                saveNote()
            }
        }

        lifecycleOwner.lifecycle.addObserver(observer)

        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
        }
    }

    val dateFormat = remember {
        SimpleDateFormat("dd MMMM yyyy, HH:mm", Locale("id", "ID"))
    }

    val density = LocalDensity.current
    val config = LocalConfiguration.current

    val screenWidthPx = with(density) { config.screenWidthDp.dp.toPx() }
    val screenHeightPx = with(density) { config.screenHeightDp.dp.toPx() }
    val marginPx = with(density) { 16.dp.toPx() }

    val imeBottomPx = with(density) {
        WindowInsets.ime.getBottom(this).toFloat()
    }

    var toolbarSizePx by remember {
        mutableStateOf(androidx.compose.ui.geometry.Size.Zero)
    }

    var toolbarOffset by remember {
        mutableStateOf(Offset(marginPx, screenHeightPx * 0.6f))
    }

    fun moveToolbar(dx: Float, dy: Float) {
        toolbarOffset = toolbarOffset.copy(
            x = toolbarOffset.x + dx,
            y = toolbarOffset.y + dy
        )
    }

    Box(modifier = Modifier.fillMaxSize()) {

        Scaffold(
            topBar = {
                TopAppBar(
                    navigationIcon = {
                        IconButton(onClick = {
                            saveNote()
                            onBack()
                        }) {
                            Icon(Icons.AutoMirrored.Filled.ArrowBack, null)
                        }
                    },
                    title = {},
                    actions = {
                        IconButton(onClick = {
                            saveNote()
                            onPinToggle()
                        }) {
                            Icon(
                                if (note.isPinned) Icons.Filled.Star
                                else Icons.Outlined.StarBorder,
                                contentDescription = null,
                                tint = if (note.isPinned) Color(0xFFFFB300) else MaterialTheme.colorScheme.onSurface
                            )
                        }
                        IconButton(onClick = onArchive) {
                            Icon(
                                Icons.Default.Archive,
                                contentDescription = null,
                                tint = Color(0xFF4CAF50)
                            )
                        }
                        IconButton(onClick = onDelete) {
                            Icon(
                                Icons.Default.Delete,
                                contentDescription = null,
                                tint = Color(0xFFF44336)
                            )
                        }
                    }
                )
            },
            contentWindowInsets = WindowInsets(0)
        ) { paddingValues ->

            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues)
                    .imeNestedScroll()
                    .verticalScroll(scrollState)
                    .padding(horizontal = 20.dp)
                    .padding(
                        bottom = WindowInsets.ime
                            .asPaddingValues()
                            .calculateBottomPadding()
                    )
            ) {

                // FIXED: BasicTextField untuk judul agar sejajar dengan konten
                BasicTextField(
                    value = title,
                    onValueChange = { title = it },
                    textStyle = MaterialTheme.typography.headlineLarge.copy(
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.onBackground
                    ),
                    cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 8.dp),
                    decorationBox = { innerTextField ->
                        Box {
                            if (title.isEmpty()) {
                                Text(
                                    "Judul",
                                    style = MaterialTheme.typography.headlineLarge.copy(
                                        fontWeight = FontWeight.Bold,
                                        color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.4f)
                                    )
                                )
                            }
                            innerTextField()
                        }
                    }
                )

                Spacer(Modifier.height(12.dp))

                Text(
                    "Terakhir diubah: ${dateFormat.format(Date(note.timestamp))}",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.6f)
                )

                HorizontalDivider(Modifier.padding(vertical = 20.dp))

                // Konten editor
                BasicTextField(
                    value = editorState.value,
                    onValueChange = {
                        editorState.onValueChange(it)
                        scope.launch {
                            bringIntoViewRequester.bringIntoView()
                        }
                    },
                    cursorBrush = SolidColor(Color(0xFFA855F7)),
                    textStyle = MaterialTheme.typography.bodyLarge.copy(
                        color = MaterialTheme.colorScheme.onBackground,
                        lineHeight = 28.sp
                    ),
                    modifier = Modifier
                        .fillMaxWidth()
                        .defaultMinSize(minHeight = 400.dp)
                        .focusRequester(focusRequester)
                        .bringIntoViewRequester(bringIntoViewRequester)
                        .onFocusChanged {
                            isContentFocused = it.isFocused
                            if (it.isFocused) {
                                scope.launch { bringIntoViewRequester.bringIntoView() }
                            }
                        },
                    decorationBox = { innerTextField ->
                        Box {
                            if (editorState.value.text.isEmpty()) {
                                Text(
                                    "Mulai menulis...",
                                    color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.4f)
                                )
                            }
                            innerTextField()
                        }
                    }
                )

                Spacer(Modifier.height(180.dp))
            }
        }

        // GANTI SELURUH bagian DraggableMiniMarkdownToolbar di EditableFullScreenNoteView.kt
// Letakkan kode ini di dalam Box setelah Scaffold, sebelum closing bracket

        if (isContentFocused) {
            DraggableMiniMarkdownToolbar(
                modifier = Modifier
                    .align(Alignment.TopStart)
                    .offset {
                        val maxX =
                            (screenWidthPx - toolbarSizePx.width - marginPx)
                                .coerceAtLeast(marginPx)

                        val maxY =
                            (screenHeightPx - imeBottomPx - toolbarSizePx.height)
                                .coerceAtLeast(marginPx)

                        IntOffset(
                            toolbarOffset.x.coerceIn(marginPx, maxX).roundToInt(),
                            toolbarOffset.y.coerceIn(marginPx, maxY).roundToInt()
                        )
                    }
                    .onSizeChanged {
                        toolbarSizePx = androidx.compose.ui.geometry.Size(
                            it.width.toFloat(),
                            it.height.toFloat()
                        )
                    },

                isBoldActive = editorState.isBoldActive(),
                isItalicActive = editorState.isItalicActive(),
                isUnderlineActive = editorState.isUnderlineActive(),
                canUndo = editorState.canUndo(),
                canRedo = editorState.canRedo(),

                onDrag = ::moveToolbar,
                onBold = {
                    ensureFocus()
                    editorState.toggleBold()
                },
                onItalic = {
                    ensureFocus()
                    editorState.toggleItalic()
                },
                onUnderline = {
                    ensureFocus()
                    editorState.toggleUnderline()
                },
                onUndo = {
                    editorState.undo()
                },
                onRedo = {
                    editorState.redo()
                }
            )
        }
    }
}