import ComponentLibrary
import ComposableArchitecture
import SwiftUI

@Reducer
public struct ForYou {
    @ObservableState
    public struct State: Equatable {
        var selectedIndex: Int = 0
        public init() {}
    }

    public enum Action: BindableAction {
        case dismiss
        case binding(BindingAction<State>)
    }

    @Dependency(\.dismiss) var dismiss

    public init() {}

    public var body: some ReducerOf<Self> {
        BindingReducer()
        Reduce { state, action in
            switch action {
            case .dismiss:
                return .run { _ in await dismiss() }

            case .binding(\.selectedIndex):
                print("selected index =>", state.selectedIndex)
                return .none

            case .binding:
                // Catch-all
                return .none
            }
        }
    }
}

public struct ForYouScreen: View {
    @Bindable var store: StoreOf<ForYou>

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

    public var body: some View {
        PagingView(direction: .vertical, spacing: 4, page: $store.selectedIndex) {
            ForEach(0 ... 100, id: \.self) { index in
                RoundedRectangle(cornerRadius: 16)
                    .fill(color(for: index))
                    .containerRelativeFrame(.vertical)
            }
        }
        .background(Color.SemanticV1.backgroundSecondary)
        .environment(\.colorScheme, .dark)
        .overlay(alignment: .topTrailing) {
            ToolbarButton(.close) {
                store.send(.dismiss)
            }
            .padding(16)
        }
    }

    func color(for index: Int) -> Color {
        switch index % 3 {
        case 0: .orange
        case 1: .blue
        default: .red
        }
    }
}
