import APIClient
import ComponentLibrary
import ComposableArchitecture
import FeatureClipDetail
import SwiftUI

@Reducer
public struct ProfileListItem {
    @ObservableState
    public struct State: Identifiable, Equatable {
        public var id: String { profile.id }
        var profile: SimpleProfile
        var position: Int
        public init(profile: SimpleProfile, position: Int) {
            self.profile = profile
            self.position = position
        }
    }

    public enum Action {
        case authorTapped(String)
    }

    public init() {}

    public var body: some ReducerOf<Self> {
        Reduce { _, action in
            switch action {
            case .authorTapped:
                return .none
            }
        }
    }
}

public struct ProfileListItemView: View {
    let store: StoreOf<ProfileListItem>

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

    public var body: some View {
        itemView
            .listRowInsets(.init())
            .listRowBackground(Color.clear)
            .alignmentGuide(.listRowSeparatorLeading) { d in
                d[.leading] + 24
            }
            .onTapGesture {
                store.send(.authorTapped(store.profile.handle))
            }
    }

    private var itemView: some View {
        HStack(spacing: 16) {
            RemoteImage(url: store.profile.avatarImageUrl, fallbackId: nil)
                .clipShape(.circle)
                .frame(width: 48, height: 48)

            VStack(alignment: .leading, spacing: 0) {
                Text(store.profile.displayName.isEmpty ? store.profile.handle : store.profile.displayName)
                    .typographyV1(.body3)
                    .foregroundColor(.SemanticV1.textPrimary)
                    .lineLimit(1)

                Text("@" + store.profile.handle)
                    .typographyV1(.caption)
                    .foregroundColor(.SemanticV1.textTertiary)
                    .lineLimit(1)

                infoView(icon: Image.Icon.userFilled, text: (store.profile.stats.followersCount ?? 0).formatted())
            }
            .multilineTextAlignment(.leading)
            .frame(maxWidth: .infinity, alignment: .leading)
        }
        .contentShape(.rect)
        .padding(.vertical, 8)
    }

    private func infoView(icon: Image, text: String, isNumberStyle: Bool = false) -> some View {
        HStack(spacing: 4) {
            icon
                .resizable()
                .frame(width: 15, height: 15, alignment: .center)
                .foregroundStyle(Color.SemanticV1.iconPrimary)

            Text(text)
                .lineLimit(1)
                .typographyV1(isNumberStyle ? .monospace : .caption2)
                .foregroundStyle(Color.SemanticV1.textPrimary.opacity(0.5))
        }
    }
}
