package com.diegocayo.organizame.presentation.features.main.tasks.create

import android.app.DatePickerDialog
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.CalendarToday
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
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.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.diegocayo.organizame.R
import com.diegocayo.organizame.data.local.entity.TaskPriority
import com.diegocayo.organizame.domain.model.Subject
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CreateTaskScreen(
    onNavigateBack: () -> Unit,
    viewModel: CreateTaskViewModel = hiltViewModel()
) {
    val state by viewModel.state.collectAsState()
    val context = LocalContext.current

    LaunchedEffect(state.isTaskCreated) {
        if (state.isTaskCreated) {
            onNavigateBack()
        }
    }

    if (state.showDatePicker) {
        val calendar = Calendar.getInstance().apply {
            timeInMillis = state.scheduledDate
        }

        DatePickerDialog(
            context,
            { _, year, month, dayOfMonth ->
                calendar.set(year, month, dayOfMonth)
                viewModel.onEvent(CreateTaskEvent.OnDateSelect(calendar.timeInMillis))
            },
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
        ).show()

        viewModel.onEvent(CreateTaskEvent.OnHideDatePicker)
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(stringResource(R.string.t_c_view_new_task)) },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(
                            Icons.Default.ArrowBack,
                            contentDescription = stringResource(R.string.text_back)
                        )
                    }
                }
            )
        }
    ) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .padding(16.dp)
                .verticalScroll(rememberScrollState())
        ) {
            OutlinedTextField(
                value = state.title,
                onValueChange = { viewModel.onEvent(CreateTaskEvent.OnTitleChange(it)) },
                label = { Text(stringResource(R.string.text_title)) },
                modifier = Modifier.fillMaxWidth(),
                isError = state.error?.contains("título") == true,
                supportingText = {
                    if (state.error?.contains("título") == true) {
                        Text(stringResource(R.string.info_title_compulsory))
                    }
                }
            )

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

            OutlinedTextField(
                value = state.description,
                onValueChange = { viewModel.onEvent(CreateTaskEvent.OnDescriptionChange(it)) },
                label = { Text(stringResource(R.string.text_description)) },
                modifier = Modifier.fillMaxWidth(),
                minLines = 3,
                isError = state.error?.contains("descripción") == true,
                supportingText = {
                    if (state.error?.contains("descripción") == true) {
                        Text("La descripción es obligatoria")
                    }
                }
            )

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

            OutlinedTextField(
                value = formatDate(state.scheduledDate),
                onValueChange = { },
                readOnly = true,
                label = { Text(stringResource(R.string.t_c_view_scheduled_date)) },
                trailingIcon = {
                    Icon(
                        Icons.Default.CalendarToday,
                        contentDescription = stringResource(R.string.t_c_view_scheduled_date),
                        modifier = Modifier.clickable {
                            viewModel.onEvent(CreateTaskEvent.OnShowDatePicker)
                        }
                    )
                },
                modifier = Modifier.fillMaxWidth()
            )

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

            SubjectDropdown(
                selectedSubject = state.selectedSubject,
                subjects = state.subjects,
                onSubjectSelected = { viewModel.onEvent(CreateTaskEvent.OnSubjectSelect(it)) }
            )

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

            Text(
                text = stringResource(R.string.t_c_view_priority),
                style = MaterialTheme.typography.titleMedium
            )

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

            PrioritySelector(
                selectedPriority = state.priority,
                onPrioritySelected = { viewModel.onEvent(CreateTaskEvent.OnPrioritySelect(it)) }
            )

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

            Button(
                onClick = { viewModel.onEvent(CreateTaskEvent.OnCreateTask) },
                modifier = Modifier.fillMaxWidth(),
                enabled = !state.isLoading && state.isFormValid
            ) {
                if (state.isLoading) {
                    CircularProgressIndicator(
                        modifier = Modifier.padding(end = 8.dp)
                    )
                }
                Text(stringResource(R.string.t_c_view_create_task))
            }

            state.error?.let { error ->
                Spacer(modifier = Modifier.height(16.dp))
                Text(
                    text = error,
                    color = MaterialTheme.colorScheme.error,
                    style = MaterialTheme.typography.bodyMedium
                )
            }
        }
    }
}

private fun formatDate(timestamp: Long): String {
    val sdf = SimpleDateFormat("dd/MM/yyyy", Locale("es", "ES"))
    return sdf.format(Date(timestamp))
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SubjectDropdown(
    selectedSubject: Subject?,
    subjects: List<Subject>,
    onSubjectSelected: (Subject?) -> Unit
) {
    var expanded by remember { mutableStateOf(false) }

    ExposedDropdownMenuBox(
        expanded = expanded,
        onExpandedChange = { expanded = it }
    ) {
        OutlinedTextField(
            value = selectedSubject?.name ?: stringResource(R.string.text_no_subject),
            onValueChange = {},
            readOnly = true,
            trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
            modifier = Modifier
                .fillMaxWidth()
                .menuAnchor(),
            label = { Text(stringResource(R.string.subjects)) }
        )

        ExposedDropdownMenu(
            expanded = expanded,
            onDismissRequest = { expanded = false }
        ) {
            DropdownMenuItem(
                text = { Text("Sin asignatura") },
                onClick = {
                    onSubjectSelected(null)
                    expanded = false
                }
            )
            subjects.forEach { subject ->
                DropdownMenuItem(
                    text = { Text(subject.name) },
                    onClick = {
                        onSubjectSelected(subject)
                        expanded = false
                    }
                )
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PrioritySelector(
    selectedPriority: TaskPriority,
    onPrioritySelected: (TaskPriority) -> Unit
) {
    SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
        TaskPriority.values().forEach { priority ->
            SegmentedButton(
                selected = selectedPriority == priority,
                onClick = { onPrioritySelected(priority) },
                shape = MaterialTheme.shapes.small,
                modifier = Modifier.weight(1f)
            ) {
                Text(
                    text = when (priority) {
                        TaskPriority.HIGH -> stringResource(R.string.t_c_pri_high)
                        TaskPriority.MEDIUM -> stringResource(R.string.t_c_pri_medium)
                        TaskPriority.LOW -> stringResource(R.string.t_c_pri_low)
                    }
                )
            }
        }
    }
} 