Android. Kotlin. Запоминай код, который я тебе сейчас скину. package ru.maxi.mobile.feature.delivery.order.ui

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.text.SpannableString
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.util.Log
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import androidx.activity.addCallback
import androidx.annotation.StringRes
import androidx.appcompat.widget.AppCompatRadioButton
import androidx.core.view.MenuProvider
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doAfterTextChanged
import androidx.fragment.app.setFragmentResultListener
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import by.kirich1409.viewbindingdelegate.viewBinding
import com.axmor.maxi.Constants
import com.google.android.material.radiobutton.MaterialRadioButton
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import ru.maxi.mobile.R
import ru.maxi.mobile.app
import ru.maxi.mobile.base.ui.MvvmBaseFragment
import ru.maxi.mobile.base.ui.manager.hideKeyboardOnOutEditableTouch
import ru.maxi.mobile.base.ui.manager.showDialog
import ru.maxi.mobile.base.ui.manager.showSnackbar
import ru.maxi.mobile.core.data.LoadableData
import ru.maxi.mobile.core.data.Money
import ru.maxi.mobile.core.navigation.parentRouter
import ru.maxi.mobile.databinding.FragmentDeliveryMakeOrderBinding
import ru.maxi.mobile.entity.delivery.order.NoProductAction
import ru.maxi.mobile.entity.delivery.order.onlinepayment.OnlinePaymentFormType
import ru.maxi.mobile.feature.analytics.model.eventsource.SbpBankChooserEventSource
import ru.maxi.mobile.feature.delivery.latestComments.Comment
import ru.maxi.mobile.feature.delivery.latestComments.LatestCommentsViewState
import ru.maxi.mobile.feature.delivery.model.MakeOrderFieldsData
import ru.maxi.mobile.feature.sbp.SbpScreens
import ru.maxi.mobile.feature.sbp.model.SbpSourceType
import ru.maxi.mobile.presentation.auth.AuthScreens
import ru.maxi.mobile.presentation.common.NegativeButton
import ru.maxi.mobile.presentation.common.PositiveButton
import ru.maxi.mobile.presentation.delivery.DeliveryScreens
import ru.maxi.mobile.ui.common.utils.formatCount
import ru.maxi.mobile.ui.common.utils.scrollToView
import ru.maxi.mobile.ui.delivery.order.MakeOrderPaymentTypeBlockAdapter
import ru.maxi.mobile.uikit.utils.lifecycleAwareLazy
import ru.maxi.mobile.utils.formatToMonthDate
import ru.maxi.mobile.utils.formatToTime
import ru.maxi.mobile.utils.formatWithCurrency
import ru.tinkoff.decoro.MaskImpl
import ru.tinkoff.decoro.parser.PhoneNumberUnderscoreSlotsParser
import ru.tinkoff.decoro.watchers.FormatWatcher
import ru.tinkoff.decoro.watchers.MaskFormatWatcher
import java.time.LocalDate
import javax.inject.Inject
import ru.maxi.mobile.uikit.R as UIKitR

/**
 * [Fragment] для функционала оформления заказа
 */
class MakeOrderFragment : MvvmBaseFragment(R.layout.fragment_delivery_make_order) {
    override val analyticsName: String = "_SendOrder"

    @Inject
    lateinit var viewModelFactory: ViewModelProvider.Factory

    private val viewModel by viewModels<MakeOrderViewModel> { viewModelFactory }

    private val viewBinding by viewBinding(FragmentDeliveryMakeOrderBinding::bind)

    private val menuProvider by lifecycleAwareLazy {
        MakeOrderMenuProvider()
    }

    private val paymentTypeBlockAdapter by lifecycleAwareLazy {
        MakeOrderPaymentTypeBlockAdapter(viewModel)
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        app.deliveryComponent.inject(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requireActivity().onBackPressedDispatcher.addCallback(this) {
            dialogManager.showConfirmDialog(
                message = getString(R.string.delivery_makeorder_dialog_description),
                positiveButton = PositiveButton(getString(R.string.delivery_makeorder_dialog_positive)) {
                    parentRouter.exit()
                },
                negativeButton = NegativeButton(getString(R.string.delivery_makeorder_dialog_negative)),
            )
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        activity?.addMenuProvider(menuProvider, viewLifecycleOwner, Lifecycle.State.STARTED)
        actionBarManager.setTitle(resources.getString(R.string.delivery_makeorder_page_title))
        actionBarManager.showBackButton()
        with(viewBinding) {
            keyboardManager.hideKeyboardOnOutEditableTouch(contentContainer)
            paymentTypeBlock.paymentTypeList.adapter = paymentTypeBlockAdapter
            setupPhoneField()
            prepareRulesText()
            prepareNoProductActions()
            paymentTypeBlock.root.setOnTitleButtonClickListener {
                viewModel.onOnlinePaymentChooseCardClick()
            }
            addressIntervalBlock.root.setOnTitleButtonClickListener {
                viewModel.onChangeAddressIntervalClick()
            }

            summaryBlock.sendOrderButton.setOnClickListener {
                viewModel.onMakeOrderButtonClick()
            }

            noConnectionView.setOnActionButtonClickListener {
                viewModel.loadData()
            }

            summaryBlock.overWeightDetails.overWeightConditions.setOnClickListener {
                viewModel.onOverWeightConditionsClick()
            }

            anonymousUserView.setOnActionButtonClickListener(viewModel::onAuthButtonClick)

            commentBlock.latestCommentsButton.setOnClickListener {
                viewModel.onLatestCommentsButtonClick()
            }

            keyboardManager.hideKeyboardOnOutEditableTouch(contentContainer)

            commentBlock.commentField.setOnTouchListener { v, event ->
                if (commentBlock.commentField.isFocused &&
                    commentBlock.commentField.lineCount > commentBlock.commentField.maxLines
                ) {
                    v.parent.requestDisallowInterceptTouchEvent(true)
                    val action = event.action and MotionEvent.ACTION_MASK
                    if (action == MotionEvent.ACTION_SCROLL) {
                        v.parent.requestDisallowInterceptTouchEvent(false)
                        return@setOnTouchListener true
                    }
                }
                return@setOnTouchListener false
            }
        }

        with(viewLifecycleOwner) {
            lifecycleScope.launch {
                repeatOnLifecycle(Lifecycle.State.STARTED) {
                    launch {
                        viewModel.fieldsState.collect {
                            viewBinding.updateState(it)
                        }
                    }
                    launch { viewModel.fieldsErrorsState.collect(viewBinding::updateFieldsErrors) }
                    launch { viewModel.navigationEvent.collect(::onNavigationEvent) }
                    launch { viewModel.messageEvent.collect(notificationManager::showSnackbar) }
                    launch { viewModel.latestCommentsListState.collect {
                        if (comments != null) {
                            if (comments.isEmpty()) {
                                viewBinding.commentBlock.latestCommentsButton.isVisible = false
                                Log.d("TESTING", "TYT TO}I{E PYSTO")
                            }
                        }
                        Log.d("TESTING", "makeOrder $comments")
                    } }
                }
            }
        }
    }

    private fun onNavigationEvent(event: MakeOrderNavigationEvent) {
        when (event) {
            MakeOrderNavigationEvent.OpenOfferRules -> {
                parentRouter.navigateTo(DeliveryScreens.OfferRules())
            }

            MakeOrderNavigationEvent.OpenPersonalDataRules -> {
                parentRouter.navigateTo(DeliveryScreens.PersonalDataRules())
            }

            MakeOrderNavigationEvent.OpenOnlinePaymentChooseCard -> {
                parentRouter.navigateTo(DeliveryScreens.OnlinePaymentChooseCardScreen())
            }

            MakeOrderNavigationEvent.OpenAuth -> {
                parentRouter.navigateTo(AuthScreens.AuthContainerScreen())
            }

            MakeOrderNavigationEvent.OpenFaqScreen -> {
                parentRouter.navigateTo(DeliveryScreens.FaqScreen())
            }

            is MakeOrderNavigationEvent.ShowErrorMinSaveDialog -> {
                dialogManager.showDialog(
                    message = event.message,
                    PositiveButton(resources.getString(R.string.delivery_makeorder_min_cart_error_dialog_pos_btn)) {
                        parentRouter.exit()
                    },
                )
            }

            MakeOrderNavigationEvent.Exit -> {
                parentRouter.finishChain()
            }

            is MakeOrderNavigationEvent.OpenBankChooserScreen -> {
                parentRouter.setResultListener(event.resultKey, event.onBankChooserResult)
                parentRouter.navigateTo(
                    SbpScreens.BankChooserScreen(
                        paymentUri = event.paymentUri,
                        sbpSourceType = SbpSourceType.QR,
                        resultKey = event.resultKey,
                        eventSource = SbpBankChooserEventSource.OnlineSBP,
                        merchantName = event.merchantName,
                    ),
                )
            }

            is MakeOrderNavigationEvent.OpenOnlinePaymentForm -> {
                if (event.resultKey != null) {
                    setFragmentResultListener(event.resultKey) { key, data ->
                        if (key == OnlinePaymentFormType.AddNewCard.ADD_NEW_CARD_REQUEST_KEY) {
                            viewModel.loadOnlinePaymentCardList()
                        }

                        if (key == OnlinePaymentFormType.OrderPayment.RESULT_REQUEST_KEY) {
                            val orderId = data.getLong(
                                OnlinePaymentFormType.OrderPayment.RESULT_DATA_ORDER_ID_KEY,
                                -1,
                            )
                            if (orderId != -1L) {
                                viewModel.finishAndOpenOrderList(orderId)
                            }
                        }
                    }
                }
                parentRouter.navigateTo(DeliveryScreens.OnlinePaymentFormScreen(event.paymentData))
            }

            MakeOrderNavigationEvent.ShowEmptyFieldsErrorDialog -> dialogManager.showConfirmDialog(
                message = resources.getString(R.string.delivery_makeorder_empty_fields_dialog_message),
                positiveButton = PositiveButton(
                    resources.getString(R.string.delivery_makeorder_empty_fields_dialog_pos_btn),
                ) {
                    viewModel.onMakeOrderButtonClick(true)
                },
                negativeButton = NegativeButton(
                    resources.getString(R.string.delivery_makeorder_empty_fields_dialog_neg_btn),
                ) {
                    viewBinding.addressIntervalBlock.apartmentField.requestFocus()
                    lifecycleScope.launch {
                        // Во время закрытия диалога не срабатывает отображение клавиатуры
                        delay(150)
                        keyboardManager.showKeyboard()
                    }
                },
            )

            MakeOrderNavigationEvent.OpenMapIntervalsAddresses -> {
                setFragmentResultListener(CHANGE_ADDRESS_REQUEST_KEY) { key, data ->
                    if (key == CHANGE_ADDRESS_REQUEST_KEY) {
                        viewModel.onChangeAddressInterval()
                    }
                }
                parentRouter.navigateTo(DeliveryScreens.MapIntervalsAddressesScreen())
            }

            MakeOrderNavigationEvent.ShowChangeAddressIntervalDialog -> {
                dialogManager.showConfirmDialog(
                    message = resources.getString(R.string.delivery_makeorder_change_address_interval_dialog_message),
                    positiveButton = PositiveButton(
                        resources.getString(R.string.delivery_makeorder_change_address_interval_dialog_pos_btn),
                    ) {
                        viewModel.onConfirmChangeAddressInterval()
                    },
                    negativeButton = NegativeButton(),
                )
            }

            MakeOrderNavigationEvent.OpenOverWeightConditions ->
                parentRouter.navigateTo(DeliveryScreens.OrderOverWeightConditionsScreen())

            MakeOrderNavigationEvent.OpenLatestCommentsChooserScreen -> {
                parentRouter.setResultListener(LATEST_COMMENTS_RESULT_KEY) { data ->
                    val state = data as? Comment ?: return@setResultListener
                    Log.d("TESTING", "setResultListener ${state.text}")
                    viewBinding.commentBlock.commentField.setTextKeepState(state.text)
                }

                parentRouter.navigateTo(DeliveryScreens.LatestCommentsScreen(
                    resultKey = LATEST_COMMENTS_RESULT_KEY,
                ))
            }

        }
    }

    private fun FragmentDeliveryMakeOrderBinding.setupPhoneField() {
        val slots = PhoneNumberUnderscoreSlotsParser().parseSlots(Constants.PHONE_MASK)
        val mask = MaskImpl.createNonTerminated(slots)
        mask.isForbidInputWhenFilled = true
        val formatWatcher: FormatWatcher = MaskFormatWatcher(mask)
        formatWatcher.installOnAndFill(contactsBlock.phoneField)

        contactsBlock.phoneField.doAfterTextChanged {
            val rawPhone = formatWatcher.mask.toUnformattedString()
            val number = rawPhone.drop(2)
            if (number.startsWith("7") || number.startsWith("8")) {
                val formattedNumber = number.drop(1).take(10)
                formatWatcher.refreshMask(formattedNumber)
                viewModel.onPhoneTextChanged(contactsBlock.phoneField.text.toString())
                return@doAfterTextChanged
            }
            viewModel.onPhoneTextChanged(contactsBlock.phoneField.text.toString())
            val cursorPosition = contactsBlock.phoneField.selectionStart
            if (it != null && cursorPosition < 3) {
                contactsBlock.phoneField.setSelection(3)
            }
        }

        contactsBlock.nameField.doAfterTextChanged {
            viewModel.onNameTextChanged(it.toString())
        }

        paymentTypeBlock.emailField.doAfterTextChanged {
            viewModel.onEmailTextChanged(it.toString())
        }

        addressIntervalBlock.apartmentField.doAfterTextChanged {
            viewModel.onApartmentTextChanged(it.toString())
        }
        addressIntervalBlock.entranceField.doAfterTextChanged {
            viewModel.onEntranceTextChanged(it.toString())
        }
        addressIntervalBlock.floorField.doAfterTextChanged {
            viewModel.onFloorTextChanged(it.toString())
        }

        commentBlock.commentField.doAfterTextChanged {
            viewModel.onCommentTextChanged(it.toString())
        }
    }

    private fun FragmentDeliveryMakeOrderBinding.prepareNoProductActions() {
        with(noProductBlock) {
            NoProductAction.entries
                .map { action ->
                    MaterialRadioButton(noProductAction.context).apply {
                        id = action.ordinal
                        tag = action.name
                        text = resources.getString(action.stringResId)
                    }
                }
                .forEach { button ->
                    noProductAction.addView(
                        button,
                        ViewGroup.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT,
                        ),
                    )
                }

            noProductAction.setOnCheckedChangeListener { group, radioId ->
                val radioButton = group.findViewById<AppCompatRadioButton>(radioId)
                val action = NoProductAction.valueOf(radioButton.tag.toString())
                viewModel.onNoProductActionChange(action)
            }
        }
    }

    private fun FragmentDeliveryMakeOrderBinding.prepareRulesText() {
        val rulesText = SpannableString(getString(R.string.delivery_makeorder_accept_rules))
        val offerSpan = object : ClickableSpan() {
            override fun onClick(textView: View) {
                viewModel.onOfferClick()
            }

            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.isUnderlineText = false
            }
        }

        val personalDataSpan = object : ClickableSpan() {
            override fun onClick(textView: View) {
                viewModel.onPersonalDataClick()
            }

            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.isUnderlineText = false
            }
        }
        rulesText.setSpan(offerSpan, 51, 57, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        rulesText.setSpan(personalDataSpan, 64, 106, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        summaryBlock.rulesText.text = rulesText
        summaryBlock.rulesText.movementMethod = LinkMovementMethod.getInstance()
    }

    private fun FragmentDeliveryMakeOrderBinding.updateState(
        state: LoadableData<MakeOrderFieldsData>,
    ) {
        when (state) {
            is LoadableData.Error -> {
                contentContainer.isVisible = false
                noConnectionView.isVisible = true
                loaderView.hide()
            }

            is LoadableData.Loading -> {
                contentContainer.isGone = true
                noConnectionView.isGone = true
                loaderView.show()
            }

            is LoadableData.Success -> {
                contentContainer.isVisible = true
                noConnectionView.isGone = true
                loaderView.hide()
                updateFields(state.value)
            }
        }
    }

    private fun FragmentDeliveryMakeOrderBinding.updateFields(
        state: MakeOrderFieldsData,
    ) {
        if (state is MakeOrderFieldsData.AnonymousUserData) {
            contentContainer.isGone = true
            anonymousUserView.isVisible = true
        }

        if (state is MakeOrderFieldsData.Fields) {
            contentContainer.isVisible = true
            anonymousUserView.isGone = true

            if (contactsBlock.phoneField.text?.toString() != state.contactsBlock.phone) {
                contactsBlock.phoneField.setTextKeepState(state.contactsBlock.phone)
            }

            contactsBlock.nameField.setTextKeepState(state.contactsBlock.name)

            if (paymentTypeBlock.emailField.text?.toString() != state.orderInitData?.email) {
                paymentTypeBlock.emailField.setTextKeepState(state.orderInitData?.email ?: "")
            }

            state.noProductAction?.ordinal?.let { noProductBlock.noProductAction.check(it) }
            commentBlock.commentField.setTextKeepState(state.comment)

            with(addressIntervalBlock) {
                root.isVisible = true
                if (state.orderInitData?.clientAddress != null) {
                    addressText.text = state.orderInitData.clientAddress
                    customAddressBlock.isVisible = false
                } else {
                    state.orderInitData?.deliveryAddress?.let { addressText.text = state.orderInitData.deliveryAddress }
                    customAddressBlock.isVisible = true
                    entranceField.setTextKeepState(state.customAddressBlock.entrance)
                    floorField.setTextKeepState(state.customAddressBlock.floor)
                    apartmentField.setTextKeepState(state.customAddressBlock.apartment)
                }
                val date = when (state.orderInitData?.deliveryDate) {
                    LocalDate.now() -> resources.getString(R.string.delivery_makeorder_interval_block_date_now)
                    LocalDate.now().plusDays(1) ->
                        resources.getString(R.string.delivery_makeorder_interval_block_date_tomorrow)

                    else -> state.orderInitData?.deliveryDate?.formatToMonthDate()
                }
                intervalText.text =
                    this.root.resources.getString(
                        R.string.delivery_makeorder_address_interval_block_interval_text,
                        date,
                        state.orderInitData?.intervalBegin?.formatToTime(),
                        state.orderInitData?.intervalEnd?.formatToTime(),
                    )

                if (state.orderInitData?.freeDeliveryProgress != null) {
                    freeDeliveryProgress.apply {
                        isVisible = true
                        with(state.orderInitData.freeDeliveryProgress) {
                            setProgress(currentSum.toInt(), startSum.toInt(), finishSum.toInt())
                            setStartValue(startSumTitle)
                            setFinishValue(finishSumTitle)
                            setCurrentValue(message)
                        }
                    }
                    freeDeliveryProgressDivider.isVisible = true
                } else {
                    freeDeliveryProgress.isVisible = false
                    freeDeliveryProgressDivider.isVisible = false
                }
                Log.d("TESTING", "${state.orderInitData?.hasSavedComments}")
                commentBlock.latestCommentsButton.isVisible = state.orderInitData?.hasSavedComments ?: false
            }

            paymentTypeBlockAdapter.submitList(state.paymentBlock.paymentTypes)
            paymentTypeBlock.root.setTitleButtonVisibility(state.paymentBlock.needShowMyCardsBtn)

            with(summaryBlock) {
                orderAmountText.setCaptionText(state.summaryBlock.orderAmount.formatWithCurrency())

                val summaryBlock = state.summaryBlock
                val weightData = summaryBlock.weightData

                val deliveryAmount = if (weightData.overWeightData == null) {
                    overWeightDetails.root.isVisible = false
                    dropdownMenu.isVisible = false
                    summaryBlock.deliveryAmount
                } else {
                    overWeightDetails.weightPaymentTitle.text = getString(
                        R.string.delivery_order_delivery_sum_details_weight_payment,
                        weightData.overWeightData.overWeight.formatCount(),
                    )
                    overWeightDetails.weightPaymentSum.text =
                        weightData.overWeightData.overWeightAmount.formatWithCurrency()

                    val deliveryAmountText = if (summaryBlock.deliveryAmount == Money.ZERO) {
                        getString(R.string.delivery_order_delivery_amount_free)
                    } else {
                        summaryBlock.deliveryAmount.formatWithCurrency()
                    }
                    overWeightDetails.deliverySum.text = deliveryAmountText
                    overWeightDetails.orderWeight.text = getString(
                        R.string.delivery_order_delivery_sum_details_weight_order,
                        weightData.totalWeight.formatCount(),
                    )
                    deliverySumContainer.setOnClickListener {
                        if (overWeightDetails.root.isVisible) {
                            overWeightDetails.root.isVisible = false
                            dropdownMenu.setBackgroundResource(UIKitR.drawable.ic_down_dropdown_menu_arrow)
                        } else {
                            overWeightDetails.root.isVisible = true
                            dropdownMenu.setBackgroundResource(UIKitR.drawable.ic_up_dropdown_menu_arrow)
                        }
                    }
                    summaryBlock.deliveryAmount + weightData.overWeightData.overWeightAmount
                }

                val deliveryAmountText = if (deliveryAmount == Money.ZERO) {
                    getString(R.string.delivery_order_delivery_amount_free)
                } else {
                    deliveryAmount.formatWithCurrency()
                }
                deliverySum.text = deliveryAmountText

                val bonusesAmount = summaryBlock.bonusesAmount
                if (bonusesAmount > Money.ZERO) {
                    bonusesAmountText.apply {
                        isVisible = true
                        setCaptionText("-${bonusesAmount.formatWithCurrency()}")
                    }
                }
                val promoCodeDiscount = summaryBlock.promoCodeDiscountAmount
                if (promoCodeDiscount > Money.ZERO) {
                    promoCodeAmountText.apply {
                        isVisible = true
                        setCaptionText("-${promoCodeDiscount.formatWithCurrency()}")
                    }
                }
                totalAmount.setCaptionText(summaryBlock.totalAmount.formatWithCurrency())
                sendOrderButton.text =
                    getString(
                        R.string.delivery_makeorder_start_order_button,
                        summaryBlock.totalAmount.formatWithCurrency(),
                    )
            }
        }
    }

    private inner class MakeOrderMenuProvider : MenuProvider {

        override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
            menuInflater.inflate(R.menu.delivery_make_order_menu, menu)
        }

        override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
            if (menuItem.itemId == R.id.action_faq) {
                viewModel.onGoToFaqClick()
                return true
            }
            return false
        }
    }

    companion object {
        const val CHANGE_ADDRESS_REQUEST_KEY = "CHANGE_ADDRESS_REQUEST_KEY"
        const val LATEST_COMMENTS_RESULT_KEY = "latest_comments_result"
    }
}

@get:StringRes
private val NoProductAction.stringResId: Int
    get() = when (this) {
        NoProductAction.RECALL -> R.string.delivery_makeorder_no_product_action_recall
        NoProductAction.CHANGE_ANALOG -> R.string.delivery_makeorder_no_product_action_change_analog
        NoProductAction.IGNORE -> R.string.delivery_makeorder_no_product_action_ignore
    }

private fun FragmentDeliveryMakeOrderBinding.updateFieldsErrors(
    errors: Set<MakeOrderFieldsData.Fields.FieldError>,
) {
    paymentTypeBlock.emailLayout.error = when {
        errors.isEmailNotValid -> {
            contentContainer.scrollToView(paymentTypeBlock.emailField)
            paymentTypeBlock.emailLayout.context.getString(
                R.string.delivery_makeorder_email_not_valid_error,
            )
        }

        errors.isEmailNotFilled -> {
            contentContainer.scrollToView(paymentTypeBlock.emailField)
            paymentTypeBlock.emailLayout.context.getString(
                R.string.delivery_makeorder_email_not_filled_error,
            )
        }

        else -> null
    }

    contactsBlock.phoneFieldLayout.error = when {
        errors.isPhoneNotValid -> {
            contentContainer.scrollToView(contactsBlock.phoneField)
            contactsBlock.phoneFieldLayout.context.getString(
                R.string.delivery_makeorder_phone_not_valid_error,
            )
        }

        errors.isPhoneNotFilled -> {
            contentContainer.scrollToView(contactsBlock.phoneField)
            contactsBlock.phoneFieldLayout.context.getString(
                R.string.delivery_makeorder_phone_not_filled_error,
            )
        }

        else -> null
    }
}

private val Set<MakeOrderFieldsData.Fields.FieldError>.isEmailNotValid: Boolean
    get() = contains(MakeOrderFieldsData.Fields.FieldError.EmailNotValid)

private val Set<MakeOrderFieldsData.Fields.FieldError>.isEmailNotFilled: Boolean
    get() = contains(MakeOrderFieldsData.Fields.FieldError.EmailNotFilled)

private val Set<MakeOrderFieldsData.Fields.FieldError>.isPhoneNotValid: Boolean
    get() = contains(MakeOrderFieldsData.Fields.FieldError.PhoneNotValid)

private val Set<MakeOrderFieldsData.Fields.FieldError>.isPhoneNotFilled: Boolean
    get() = contains(MakeOrderFieldsData.Fields.FieldError.PhoneNotFilled)