package com.example.elva.ui.calendar

import android.app.DatePickerDialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import com.example.elva.R
import com.example.elva.data.models.health.FlowIntensity
import com.example.elva.data.models.health.Period
import com.example.elva.databinding.DialogEditPeriodBinding
import java.time.LocalDate
import java.time.format.DateTimeFormatter

class EditPeriodDialogFragment : DialogFragment() {

    private var _binding: DialogEditPeriodBinding? = null
    private val binding get() = _binding!!

    private var startDate: LocalDate = LocalDate.now()
    private var endDate: LocalDate? = null
    private var selectedFlow: FlowIntensity = FlowIntensity.MEDIUM

    private var onSaveListener: ((Period) -> Unit)? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = DialogEditPeriodBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        setupListeners()
        updateUI()
    }

    private fun setupListeners() {
        binding.apply {
            // Выбор даты начала
            cardStartDate.setOnClickListener {
                showDatePicker(startDate) { date ->
                    startDate = date
                    updateUI()
                }
            }

            // Выбор даты окончания
            cardEndDate.setOnClickListener {
                showDatePicker(endDate ?: startDate.plusDays(5)) { date ->
                    endDate = date
                    updateUI()
                }
            }

            // Интенсивность
            radioGroupFlow.setOnCheckedChangeListener { _, checkedId ->
                selectedFlow = when (checkedId) {
                    R.id.rbLight -> FlowIntensity.LIGHT
                    R.id.rbMedium -> FlowIntensity.MEDIUM
                    R.id.rbHeavy -> FlowIntensity.HEAVY
                    else -> FlowIntensity.MEDIUM
                }
            }

            // Кнопки
            btnCancel.setOnClickListener {
                dismiss()
            }

            btnSave.setOnClickListener {
                savePeriod()
            }
        }
    }

    private fun showDatePicker(currentDate: LocalDate, onDateSelected: (LocalDate) -> Unit) {
        val picker = DatePickerDialog(
            requireContext(),
            { _, year, month, dayOfMonth ->
                onDateSelected(LocalDate.of(year, month + 1, dayOfMonth))
            },
            currentDate.year,
            currentDate.monthValue - 1,
            currentDate.dayOfMonth
        )
        picker.show()
    }

    private fun updateUI() {
        val formatter = DateTimeFormatter.ofPattern("dd MMMM yyyy")

        binding.apply {
            tvStartDate.text = startDate.format(formatter)
            endDate?.let {
                tvEndDate.text = it.format(formatter)
            } ?: run {
                tvEndDate.text = getString(R.string.select_date)
            }
        }
    }

    private fun savePeriod() {
        val period = Period(
            startDate = startDate,
            endDate = endDate,
            flow = selectedFlow,
            notes = binding.etNotes.text?.toString()
        )

        onSaveListener?.invoke(period)
        dismiss()
    }

    fun setOnSaveListener(listener: (Period) -> Unit) {
        onSaveListener = listener
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    companion object {
        fun newInstance() = EditPeriodDialogFragment()
    }
}

