import ComponentLibrary
import ComposableArchitecture
import FeatureOnboardingModels
import Localization
import SwiftUI

public struct UsernameEntryScreen: View {
    @Bindable var store: StoreOf<UsernameEntry>

    public init(store: StoreOf<UsernameEntry>) {
        self.store = store
    }

    public var body: some View {
        DataEntryScreen(
            title: L10n.FeatureOnboarding.usernameEntryNavigationTitle,
            buttonTitle: L10n.FeatureOnboarding.loveIt,
            placeholder: L10n.FeatureOnboarding.usernameEntryPlaceholder,
            autofillContentType: .nickname,
            isWorking: store.isWorking,
            value: $store.value,
            focused: $store.isFocused.sending(\.setFocus),
            action: { store.send(.updateUsernameTapped) },
            cancel: { store.send(.delegate(.backTapped)) },
            showSkip: true,
            isDisabled: store.isCheckingOrPending || !(store.isUsernameAvailable ?? false),
            caption: AnyView(
                UsernameStatusView(
                    isInputEmpty: store.value.isEmpty,
                    isChecking: store.isCheckingOrPending,
                    isAvailable: store.isUsernameAvailable,
                    errorMessage: store.errorMessage,
                    wasLastCheckSuccessful: store.wasLastCheckSuccessful
                )
            )
        )
        .onAppear {
            store.send(.onAppear)

            // Trigger validation if there's already a value
            if !store.value.isEmpty {
                store.send(.internal(.validateUsername(store.value)))
            }
        }
    }
}
