import SwiftUI

struct PlaylistBarView: View {
    var playlists: [any PlaylistRepresentable]
    var selectedItem: (any PlaylistRepresentable)?
    var isHomeSelected: Bool
    var isRemoteMode: Bool = false
    var onHomeSelect: () -> Void
    var onSelect: (any PlaylistRepresentable) -> Void
    var onDeselect: () -> Void
    var onRename: (any PlaylistRepresentable) -> Void
    var onDelete: (any PlaylistRepresentable) -> Void
    var onEditQuery: (SmartPlaylist) -> Void

    var body: some View {
        FlowLayout(spacing: 6) {
            PlaylistButton(
                name: "Home",
                isSelected: isHomeSelected,
                isSmart: false,
                icon: "house.fill",
                action: onHomeSelect
            )

            ForEach(playlists, id: \.id) { item in
                PlaylistButton(
                    name: item.name,
                    isSelected: selectedItem?.id == item.id,
                    isSmart: item.isSmartPlaylist,
                    action: {
                        if selectedItem?.id == item.id {
                            onDeselect()
                        } else {
                            onSelect(item)
                        }
                    }
                )
                .contextMenu {
                    if !isRemoteMode {
                        Button("Rename...") { onRename(item) }
                        if let smart = item as? SmartPlaylist {
                            Button("Edit Search Query...") { onEditQuery(smart) }
                        }
                        Button("Delete") { onDelete(item) }
                    }
                }
            }
        }
        .padding(.horizontal, 12)
        .padding(.vertical, 6)
    }
}

private struct PlaylistButton: View {
    let name: String
    let isSelected: Bool
    let isSmart: Bool
    var icon: String? = nil
    let action: () -> Void

    private var tintColor: Color {
        isSmart ? .purple : .accentColor
    }

    private var inactiveColor: Color {
        isSmart ? .purple.opacity(0.7) : .secondary
    }

    var body: some View {
        Button(action: action) {
            HStack(spacing: 4) {
                if let icon {
                    Image(systemName: icon)
                        .font(.system(size: 10))
                }
                Text(name)
            }
            .font(.system(size: 11))
            .padding(.horizontal, 10)
            .padding(.vertical, 5)
            .background(isSelected ? tintColor.opacity(0.2) : Color.secondary.opacity(0.1))
            .foregroundStyle(isSelected ? tintColor : inactiveColor)
            .overlay(
                RoundedRectangle(cornerRadius: 4)
                    .stroke(isSelected ? tintColor : Color.secondary.opacity(0.3), lineWidth: 1)
            )
            .cornerRadius(4)
        }
        .buttonStyle(.plain)
    }
}
