import SwiftUI

/// Окно выбора пар для виджета.
struct SettingsView: View {
    @State private var model = SettingsModel()

    var body: some View {
        VStack(spacing: 0) {
            header
            searchField
            Divider()
            content
        }
        .frame(width: 420, height: 560)
        .background(Color(.windowBackgroundColor))
        .task { await model.load() }
    }

    // MARK: - Шапка

    private var header: some View {
        HStack {
            Text("Rapira Crypto")
                .font(.system(size: 16, weight: .bold))

            Text("\(model.selection.count)/\(model.maxSelection)")
                .font(.system(size: 12, weight: .medium, design: .rounded))
                .foregroundStyle(.secondary)
                .padding(.horizontal, 8)
                .padding(.vertical, 3)
                .background(.quaternary, in: Capsule())

            Spacer()

            saveButton
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 12)
    }

    private var saveButton: some View {
        Button {
            withAnimation(.easeInOut(duration: 0.2)) {
                model.save()
            }
        } label: {
            HStack(spacing: 4) {
                if model.isSaved {
                    Image(systemName: "checkmark")
                        .font(.system(size: 11, weight: .bold))
                    Text("Сохранено")
                } else {
                    Text("Сохранить")
                }
            }
            .font(.system(size: 12, weight: .semibold))
        }
        .buttonStyle(.borderedProminent)
        .tint(model.isSaved ? .green : .accentColor)
        .controlSize(.small)
    }

    // MARK: - Поиск

    private var searchField: some View {
        HStack(spacing: 6) {
            Image(systemName: "magnifyingglass")
                .foregroundStyle(.tertiary)
                .font(.system(size: 12))
            TextField("Поиск пары...", text: $model.searchText)
                .textFieldStyle(.plain)
                .font(.system(size: 13))
        }
        .padding(8)
        .background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 8, style: .continuous))
        .padding(.horizontal, 16)
        .padding(.bottom, 8)
    }

    // MARK: - Список

    @ViewBuilder
    private var content: some View {
        switch model.phase {
        case .loading:
            Spacer()
            ProgressView()
                .scaleEffect(0.8)
            Spacer()

        case .failed:
            Spacer()
            VStack(spacing: 10) {
                Text("Не удалось загрузить список пар")
                    .font(.system(size: 13))
                    .foregroundStyle(.secondary)
                Button("Повторить") {
                    Task { await model.load() }
                }
                .controlSize(.small)
            }
            Spacer()

        case .loaded:
            ScrollView {
                LazyVStack(spacing: 0) {
                    ForEach(model.filtered) { thumb in
                        PairRow(
                            thumb: thumb,
                            isSelected: model.isSelected(thumb.symbol),
                            isEnabled: model.canToggle(thumb.symbol)
                        ) {
                            model.toggle(thumb.symbol)
                        }
                        Divider().padding(.leading, 56).opacity(0.4)
                    }
                }
                .padding(.vertical, 4)
            }
        }
    }
}

// MARK: - Строка пары

private struct PairRow: View {
    let thumb: SymbolThumb
    let isSelected: Bool
    let isEnabled: Bool
    let onToggle: () -> Void

    var body: some View {
        Button(action: onToggle) {
            HStack(spacing: 10) {
                Circle()
                    .fill(isSelected ? Color.accentColor : Color.clear)
                    .frame(width: 8, height: 8)
                    .overlay(
                        Circle().strokeBorder(
                            isSelected ? Color.clear : Color.secondary.opacity(0.3),
                            lineWidth: 1
                        )
                    )

                RemoteCoinIcon(currency: thumb.quoteCurrency, size: 30)

                VStack(alignment: .leading, spacing: 1) {
                    Text(thumb.symbol)
                        .font(.system(size: 13, weight: .semibold))
                    Text(thumb.quoteCurrencyName)
                        .font(.system(size: 11))
                        .foregroundStyle(.secondary)
                        .lineLimit(1)
                }

                Spacer(minLength: 4)

                Text(thumb.priceFormatted)
                    .font(.system(size: 13, weight: .semibold, design: .rounded))
                    .lineLimit(1)
                    .minimumScaleFactor(0.7)

                Text(thumb.changePercent)
                    .font(.system(size: 11, weight: .semibold, design: .rounded))
                    .foregroundStyle(.white)
                    .padding(.horizontal, 7)
                    .padding(.vertical, 3)
                    .background(
                        thumb.isPositive ? RapiraPalette.accent : RapiraPalette.negative,
                        in: RoundedRectangle(cornerRadius: 5, style: .continuous)
                    )
            }
            .padding(.horizontal, 16)
            .padding(.vertical, 7)
            .contentShape(Rectangle())
            .opacity(isEnabled || isSelected ? 1.0 : 0.35)
        }
        .buttonStyle(.plain)
        .disabled(!isEnabled)
    }
}

// MARK: - Превью

#Preview {
    SettingsView()
}
