package com.example.libary

import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.AbsoluteRoundedCornerShape
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.libary.theme.AccentColor
import com.example.libary.theme.BlackColor
import com.example.libary.theme.CaptionColor
import com.example.libary.theme.InputBGColor
import com.example.libary.theme.InputStroke

@Composable
fun SearchInput(
    modifier: Modifier = Modifier,
    value: String = "",
    onValueChange: (String) -> Unit,
) {
    var focus by remember { mutableStateOf(false) }

    OutlinedTextField(
        value = value,
        modifier = modifier.onFocusChanged {
            focus = it.hasFocus
        },
        onValueChange = onValueChange,
        placeholder = {
            Text(
                text = "Искать описание",
                color = CaptionColor,
                fontWeight = FontWeight.W400,
                fontSize = 16.sp
            )
        },
        leadingIcon = {
            Image(
                painter = painterResource(R.drawable.icon_search),
                contentDescription = null
            )
        },
        trailingIcon = {
            if (focus) {
                Image(
                    painter = painterResource(R.drawable.delete),
                    contentDescription = null
                )
            }
        },
        shape = AbsoluteRoundedCornerShape(10.dp),
        colors = TextFieldDefaults.colors(
            cursorColor = AccentColor,
            focusedPlaceholderColor = CaptionColor,
            unfocusedPlaceholderColor = CaptionColor,
            focusedTextColor = BlackColor,
            unfocusedTextColor = BlackColor,
            focusedIndicatorColor = InputStroke,
            unfocusedIndicatorColor = InputStroke,
            focusedContainerColor = InputBGColor,
            unfocusedContainerColor = InputBGColor
        )
    )
}

@Preview
@Composable
private fun SearchInputPrev() {
    var value by remember { mutableStateOf("") }

    SearchInput(
        value = value,
        modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp, vertical = 7.dp),
        onValueChange = {
            value = it
        }
    )
}
