import ComponentLibrary
import ComposableArchitecture
import Localization
import SwiftUI

@Reducer
public struct ContactSyncBanner {
    @Reducer(state: .equatable)
    public enum Destination {
        case contactsAuthorizationAlert(ContactsAuthorizationAlert)
    }

    @ObservableState
    public struct State: Equatable {
        @Presents public var destination: Destination.State?

        public init() {}
    }

    public enum Action {
        case destination(PresentationAction<Destination.Action>)
        case delegate(Delegate)
        case bannerTapped

        public enum Delegate {
            case dismissTapped
            case bannerTappedAndAuthorized
        }
    }

    public init() {}

    public var body: some ReducerOf<Self> {
        Reduce { state, action in
            switch action {
            case .bannerTapped:
                state.destination = .contactsAuthorizationAlert(ContactsAuthorizationAlert.State())
                return .none

            case .destination(.presented(.contactsAuthorizationAlert(.delegate(.authorized)))):
                return .send(.delegate(.bannerTappedAndAuthorized))

            case .destination:
                return .none

            case .delegate:
                // Catch-all
                return .none
            }
        }
        .ifLet(\.$destination, action: \.destination)

        Analytics()
    }
}

public struct ContactSyncBannerView: View {
    @Bindable var store: StoreOf<ContactSyncBanner>

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

    public var body: some View {
        CTABanner(
            title: L10n.FeatureSocial.contactSyncBannerTitle,
            subtitle: L10n.FeatureSocial.contactSyncBannerSubtitle,
            icon: { Image.Icon.userSearch },
            background: { Image.Assets.contactSyncBannerBackground },
            action: { store.send(.bannerTapped) },
            dismissAction: { store.send(.delegate(.dismissTapped)) }
        )
        .contactsAuthorizationAlert(
            $store.scope(
                state: \.destination?.contactsAuthorizationAlert,
                action: \.destination.contactsAuthorizationAlert
            )
        )
    }
}
