import SwiftUI
import ComposeApp

/// Full-screen browser for all task templates from backend
struct TaskTemplatesBrowserView: View {
    @Environment(\.dismiss) private var dismiss
    @ObservedObject private var dataManager = DataManagerObservable.shared
    let onSelect: (TaskTemplate) -> Void

    @State private var searchText: String = ""
    @State private var expandedCategories: Set<String> = []

    private var filteredTemplates: [TaskTemplate] {
        if searchText.isEmpty {
            return []
        }
        return dataManager.searchTaskTemplates(query: searchText)
    }

    private var isSearching: Bool {
        !searchText.isEmpty
    }

    var body: some View {
        NavigationStack {
            List {
                if isSearching {
                    // Search results
                    searchResultsSection
                } else {
                    // Browse by category
                    categorySections
                }
            }
            .standardFormStyle()
            .background(WarmGradientBackground())
            .searchable(text: $searchText, prompt: "Search templates...")
            .accessibilityHint("Search task templates by name")
            .navigationTitle("Task Templates")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .confirmationAction) {
                    Button(L10n.Common.done) {
                        dismiss()
                    }
                }
            }
        }
    }

    // MARK: - Search Results

    @ViewBuilder
    private var searchResultsSection: some View {
        if filteredTemplates.isEmpty {
            Section {
                VStack(spacing: 12) {
                    Image(systemName: "magnifyingglass")
                        .font(.system(size: 40))
                        .foregroundColor(Color.appTextSecondary.opacity(0.5))

                    Text("No Templates Found")
                        .font(.headline)
                        .foregroundColor(Color.appTextPrimary)

                    Text("Try a different search term")
                        .font(.subheadline)
                        .foregroundColor(Color.appTextSecondary)
                }
                .frame(maxWidth: .infinity)
                .padding(.vertical, 40)
            }
            .listRowBackground(Color.clear)
        } else {
            Section {
                ForEach(filteredTemplates, id: \.id) { template in
                    taskRow(template)
                }
            } header: {
                Text("\(filteredTemplates.count) \(filteredTemplates.count == 1 ? "result" : "results")")
            }
            .listRowBackground(Color.appBackgroundSecondary)
        }
    }

    // MARK: - Category Sections

    @ViewBuilder
    private var categorySections: some View {
        if let grouped = dataManager.taskTemplatesGrouped {
            ForEach(grouped.categories, id: \.categoryName) { categoryGroup in
                let categoryKey = categoryGroup.categoryName
                let isExpanded = expandedCategories.contains(categoryKey)

                Section {
                    // Category header (tappable to expand/collapse)
                    Button {
                        withAnimation(.easeInOut(duration: 0.2)) {
                            if isExpanded {
                                expandedCategories.remove(categoryKey)
                            } else {
                                expandedCategories.insert(categoryKey)
                            }
                        }
                    } label: {
                        HStack {
                            // Category icon
                            Image(systemName: categoryIcon(for: categoryGroup.categoryName))
                                .font(.system(size: 18))
                                .foregroundColor(Color.taskCategoryColor(for: categoryGroup.categoryName))
                                .frame(width: 28, height: 28)

                            // Category name
                            Text(categoryGroup.categoryName)
                                .font(.headline)
                                .foregroundColor(Color.appTextPrimary)

                            Spacer()

                            // Count badge
                            Text("\(categoryGroup.count)")
                                .font(.caption)
                                .foregroundColor(Color.appTextSecondary)
                                .padding(.horizontal, 8)
                                .padding(.vertical, 4)
                                .background(Color.appBackgroundPrimary)
                                .clipShape(Capsule())

                            // Expand/collapse indicator
                            Image(systemName: isExpanded ? "chevron.down" : "chevron.right")
                                .font(.caption)
                                .foregroundColor(Color.appTextSecondary)
                        }
                        .padding(.vertical, 4)
                        .contentShape(Rectangle())
                    }
                    .buttonStyle(.plain)

                    // Tasks (shown when expanded)
                    if isExpanded {
                        ForEach(categoryGroup.templates, id: \.id) { template in
                            taskRow(template)
                                .padding(.leading, 16)
                        }
                    }
                }
                .sectionBackground()
            }
        } else {
            // Empty state
            Section {
                VStack(spacing: 12) {
                    Image(systemName: "checklist")
                        .font(.system(size: 40))
                        .foregroundColor(Color.appTextSecondary.opacity(0.5))

                    Text("No Templates Available")
                        .font(.headline)
                        .foregroundColor(Color.appTextPrimary)

                    Text("Templates will appear here once loaded")
                        .font(.subheadline)
                        .foregroundColor(Color.appTextSecondary)
                }
                .frame(maxWidth: .infinity)
                .padding(.vertical, 40)
            }
            .listRowBackground(Color.clear)
        }
    }

    // MARK: - Task Row

    @ViewBuilder
    private func taskRow(_ template: TaskTemplate) -> some View {
        Button {
            onSelect(template)
            dismiss()
        } label: {
            HStack(spacing: 12) {
                // Icon
                Image(systemName: template.iconIos.isEmpty ? "checklist" : template.iconIos)
                    .font(.system(size: 16))
                    .foregroundColor(Color.taskCategoryColor(for: template.categoryName))
                    .frame(width: 24, height: 24)

                // Task info
                VStack(alignment: .leading, spacing: 2) {
                    Text(template.title)
                        .font(.subheadline)
                        .foregroundColor(Color.appTextPrimary)
                        .lineLimit(2)

                    Text(template.frequencyDisplay)
                        .font(.caption)
                        .foregroundColor(Color.appTextSecondary)
                }

                Spacer()

                // Add indicator
                Image(systemName: "plus.circle")
                    .font(.system(size: 18))
                    .foregroundColor(Color.appPrimary)
            }
            .padding(.vertical, 6)
            .contentShape(Rectangle())
        }
        .buttonStyle(.plain)
        .accessibilityLabel("\(template.title), \(template.frequencyDisplay)")
        .accessibilityHint("Double tap to use this template")
    }

    // MARK: - Helpers

    private func categoryIcon(for categoryName: String) -> String {
        switch categoryName.lowercased() {
        case "plumbing": return "drop.fill"
        case "safety": return "shield.checkered"
        case "electrical": return "bolt.fill"
        case "hvac": return "thermometer.medium"
        case "appliances": return "refrigerator.fill"
        case "exterior": return "house.fill"
        case "lawn & garden": return "leaf.fill"
        case "interior": return "sofa.fill"
        case "general", "seasonal": return "calendar"
        default: return "checklist"
        }
    }

}

#Preview {
    TaskTemplatesBrowserView { template in
        print("Selected: \(template.title)")
    }
}
