import ComponentLibrary
import Localization
import SwiftUI

public struct UsernameStatusView: View {
    let isInputEmpty: Bool
    let isChecking: Bool
    let isAvailable: Bool?
    let errorMessage: String?
    let wasLastCheckSuccessful: Bool

    public init(
        isInputEmpty: Bool,
        isChecking: Bool,
        isAvailable: Bool?,
        errorMessage: String?,
        wasLastCheckSuccessful: Bool
    ) {
        self.isInputEmpty = isInputEmpty
        self.isChecking = isChecking
        self.isAvailable = isAvailable
        self.errorMessage = errorMessage
        self.wasLastCheckSuccessful = wasLastCheckSuccessful
    }

    public var body: some View {
        HStack(spacing: 8) {
            // Icon
            ZStack {
                if let icon = captionLeadingIcon, !isInputEmpty {
                    ZStack {
                        Circle()
                            .frame(width: 18, height: 18)
                            .foregroundStyle(Color.SemanticV1.textSecondary)
                        icon
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .frame(width: 16, height: 16)
                            .foregroundStyle(Color.SemanticV1.backgroundPrimary)
                    }
                    .transition(.opacity.animation(.easeInOut(duration: 0.2)))
                } else if isChecking {
                    ProgressView()
                        .progressViewStyle(.circular)
                        .foregroundStyle(Color.SemanticV1.textSecondary)
                        .frame(width: 18, height: 18)
                        .transition(.opacity.animation(.easeInOut(duration: 0.2)))
                }
            }

            // Text
            Text(caption)
                .typographyV1(.body2thin)
                .foregroundStyle(Color.SemanticV1.textSecondary)
                .multilineTextAlignment(.center)
                .transition(.opacity.animation(.easeInOut(duration: 0.2)))
        }
        .sensoryFeedbackIfEnabled(.success, trigger: isAvailable == true)
        .sensoryFeedbackIfEnabled(.warning, trigger: errorMessage != nil)
    }

    private var captionLeadingIcon: Image? {
        if errorMessage != nil {
            return Image.Icon.close
        } else if isAvailable == true && !isChecking {
            return Image.Icon.checkV1
        } else {
            return nil
        }
    }

    private var caption: String {
        if isInputEmpty {
            return ""
        } else if let errorMessage {
            return errorMessage
        } else if isAvailable == true || (isChecking && wasLastCheckSuccessful) {
            return L10n.FeatureOnboarding.usernameAvailable
        } else if isChecking {
            return L10n.FeatureOnboarding.usernameChecking
        } else {
            return "" // Empty when no status
        }
    }
}
