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

import android.app.DatePickerDialog
import android.app.TimePickerDialog
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.material.icons.filled.Schedule
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.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.domain.model.Subject
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

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

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

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

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

        viewModel.onEvent(CreateEventEvent.OnHideDatePicker)
    }

    if (state.showStartTimePicker) {
        val calendar = Calendar.getInstance().apply {
            timeInMillis = state.startTime
        }

        TimePickerDialog(
            context,
            { _, hourOfDay, minute ->
                calendar.set(Calendar.HOUR_OF_DAY, hourOfDay)
                calendar.set(Calendar.MINUTE, minute)
                viewModel.onEvent(CreateEventEvent.OnStartTimeSelect(calendar.timeInMillis))
            },
            calendar.get(Calendar.HOUR_OF_DAY),
            calendar.get(Calendar.MINUTE),
            true
        ).show()

        viewModel.onEvent(CreateEventEvent.OnHideStartTimePicker)
    }

    if (state.showEndTimePicker) {
        val calendar = Calendar.getInstance().apply {
            timeInMillis = state.endTime
        }

        TimePickerDialog(
            context,
            { _, hourOfDay, minute ->
                calendar.set(Calendar.HOUR_OF_DAY, hourOfDay)
                calendar.set(Calendar.MINUTE, minute)
                viewModel.onEvent(CreateEventEvent.OnEndTimeSelect(calendar.timeInMillis))
            },
            calendar.get(Calendar.HOUR_OF_DAY),
            calendar.get(Calendar.MINUTE),
            true
        ).show()

        viewModel.onEvent(CreateEventEvent.OnHideEndTimePicker)
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(stringResource(R.string.e_c_view_new_event)) },
                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(CreateEventEvent.OnTitleChange(it)) },
                label = { Text(stringResource(R.string.text_title)) },
                modifier = Modifier.fillMaxWidth(),
                isError = state.error?.contains("título") == true
            )

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

            OutlinedTextField(
                value = state.description,
                onValueChange = { viewModel.onEvent(CreateEventEvent.OnDescriptionChange(it)) },
                label = { Text(stringResource(R.string.text_description)) },
                modifier = Modifier.fillMaxWidth(),
                minLines = 3
            )

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

            val dateFormat = SimpleDateFormat("dd 'de' MMMM, yyyy", Locale("es", "ES"))
            OutlinedTextField(
                value = dateFormat.format(Date(state.date)),
                onValueChange = { },
                readOnly = true,
                label = { Text(stringResource(R.string.e_c_view_date)) },
                trailingIcon = {
                    Icon(
                        Icons.Default.CalendarToday,
                        contentDescription = stringResource(R.string.e_c_view_date),
                        modifier = Modifier.clickable {
                            viewModel.onEvent(CreateEventEvent.OnShowDatePicker)
                        }
                    )
                },
                modifier = Modifier.fillMaxWidth()
            )

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

            val timeFormat = SimpleDateFormat("HH:mm", Locale("es", "ES"))
            OutlinedTextField(
                value = timeFormat.format(Date(state.startTime)),
                onValueChange = { },
                readOnly = true,
                label = { Text(stringResource(R.string.e_c_view_start_time)) },
                trailingIcon = {
                    Icon(
                        Icons.Default.Schedule,
                        contentDescription = stringResource(R.string.e_c_view_start_time),
                        modifier = Modifier.clickable {
                            viewModel.onEvent(CreateEventEvent.OnShowStartTimePicker)
                        }
                    )
                },
                modifier = Modifier.fillMaxWidth()
            )

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

            OutlinedTextField(
                value = timeFormat.format(Date(state.endTime)),
                onValueChange = { },
                readOnly = true,
                label = { Text(stringResource(R.string.e_c_view_end_time)) },
                trailingIcon = {
                    Icon(
                        Icons.Default.Schedule,
                        contentDescription = stringResource(R.string.e_c_view_end_time),
                        modifier = Modifier.clickable {
                            viewModel.onEvent(CreateEventEvent.OnShowEndTimePicker)
                        }
                    )
                },
                modifier = Modifier.fillMaxWidth()
            )

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

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

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

            Button(
                onClick = { viewModel.onEvent(CreateEventEvent.OnCreateEvent) },
                modifier = Modifier.fillMaxWidth(),
                enabled = !state.isLoading && state.isFormValid
            ) {
                if (state.isLoading) {
                    CircularProgressIndicator(
                        modifier = Modifier.padding(end = 8.dp),
                        strokeWidth = 2.dp
                    )
                }
                Text(stringResource(R.string.e_c_view_create_event))
            }

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

@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
                    }
                )
            }
        }
    }
} 