import SwiftUI

// MARK: - Add Feed Sheet

struct AddFeedSheet: View {
    @Bindable var vm: ReaderViewModel
    @Environment(\.dismiss) private var dismiss
    @State private var feedURL = ""
    @State private var selectedCategoryId: Int?
    @State private var isAdding = false
    @State private var error: String?

    var body: some View {
        NavigationStack {
            VStack(spacing: 20) {
                VStack(alignment: .leading, spacing: 8) {
                    Text("Feed URL")
                        .font(.subheadline.weight(.medium))
                        .foregroundStyle(Color.textSecondary)

                    TextField("https://example.com/feed.xml", text: $feedURL)
                        .textFieldStyle(.roundedBorder)
                        .keyboardType(.URL)
                        .autocorrectionDisabled()
                        .textInputAutocapitalization(.never)
                }

                if !vm.categories.isEmpty {
                    VStack(alignment: .leading, spacing: 8) {
                        Text("Category (optional)")
                            .font(.subheadline.weight(.medium))
                            .foregroundStyle(Color.textSecondary)

                        Picker("Category", selection: $selectedCategoryId) {
                            Text("None").tag(nil as Int?)
                            ForEach(vm.categories) { cat in
                                Text(cat.title).tag(cat.id as Int?)
                            }
                        }
                        .pickerStyle(.menu)
                    }
                }

                if let error {
                    Text(error)
                        .font(.caption)
                        .foregroundStyle(.red)
                }

                Spacer()
            }
            .padding()
            .background(Color.canvas)
            .navigationTitle("Add Feed")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("Cancel") { dismiss() }
                }
                ToolbarItem(placement: .confirmationAction) {
                    Button {
                        addFeed()
                    } label: {
                        if isAdding {
                            ProgressView().controlSize(.small)
                        } else {
                            Text("Add")
                                .font(.headline)
                        }
                    }
                    .disabled(feedURL.trimmingCharacters(in: .whitespaces).isEmpty || isAdding)
                }
            }
        }
    }

    private func addFeed() {
        isAdding = true
        error = nil
        Task {
            do {
                try await vm.addFeed(url: feedURL.trimmingCharacters(in: .whitespaces), categoryId: selectedCategoryId)
                dismiss()
            } catch {
                self.error = error.localizedDescription
            }
            isAdding = false
        }
    }
}

// MARK: - Feed Management Sheet

struct FeedManagementSheet: View {
    @Bindable var vm: ReaderViewModel
    @Environment(\.dismiss) private var dismiss
    @State private var feedToDelete: ReaderFeed?
    @State private var showAddCategory = false
    @State private var newCategoryTitle = ""
    @State private var refreshingFeedId: Int?

    var body: some View {
        NavigationStack {
            List {
                ForEach(vm.feedsByCategory, id: \.0?.id) { category, feeds in
                    Section(header: Text(category?.title ?? "Uncategorized")) {
                        ForEach(feeds) { feed in
                            feedRow(feed)
                        }
                    }
                }

                Section {
                    Button {
                        showAddCategory = true
                    } label: {
                        Label("New Category", systemImage: "folder.badge.plus")
                            .foregroundStyle(Color.accentWarm)
                    }
                }
            }
            .navigationTitle("Manage Feeds")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .confirmationAction) {
                    Button("Done") { dismiss() }
                }
            }
            .alert("Delete Feed?", isPresented: .init(
                get: { feedToDelete != nil },
                set: { if !$0 { feedToDelete = nil } }
            )) {
                Button("Delete", role: .destructive) {
                    if let feed = feedToDelete {
                        Task {
                            try? await vm.deleteFeed(id: feed.id)
                        }
                    }
                }
                Button("Cancel", role: .cancel) {}
            } message: {
                if let feed = feedToDelete {
                    Text("This will remove \"\(feed.title)\" and all its articles.")
                }
            }
            .alert("New Category", isPresented: $showAddCategory) {
                TextField("Category name", text: $newCategoryTitle)
                Button("Create") {
                    let title = newCategoryTitle.trimmingCharacters(in: .whitespaces)
                    guard !title.isEmpty else { return }
                    Task {
                        try? await vm.addCategory(title: title)
                        newCategoryTitle = ""
                    }
                }
                Button("Cancel", role: .cancel) { newCategoryTitle = "" }
            }
        }
    }

    private func feedRow(_ feed: ReaderFeed) -> some View {
        HStack {
            VStack(alignment: .leading, spacing: 2) {
                Text(feed.title)
                    .font(.subheadline.weight(.medium))
                    .foregroundStyle(Color.textPrimary)
                    .lineLimit(1)

                Text(feed.feedUrl)
                    .font(.caption)
                    .foregroundStyle(Color.textTertiary)
                    .lineLimit(1)
            }

            Spacer()

            if let count = vm.counters?.count(forFeed: feed.id), count > 0 {
                Text("\(count)")
                    .font(.caption.weight(.bold))
                    .foregroundStyle(.white)
                    .padding(.horizontal, 8)
                    .padding(.vertical, 2)
                    .background(Color.accentWarm)
                    .clipShape(Capsule())
            }
        }
        .swipeActions(edge: .trailing) {
            Button(role: .destructive) {
                feedToDelete = feed
            } label: {
                Image(systemName: "trash")
            }
        }
        .swipeActions(edge: .leading) {
            Button {
                Task {
                    refreshingFeedId = feed.id
                    try? await vm.refreshFeed(id: feed.id)
                    refreshingFeedId = nil
                }
            } label: {
                Image(systemName: "arrow.clockwise")
            }
            .tint(Color.accentWarm)
        }
    }
}
