//
//  SoundCategoryView.swift
//  TheNoiseClock
//
//  Created by Matt Bruce on 9/7/25.
//

import SwiftUI
import Bedrock
import AudioPlaybackKit

/// Category-based sound selection view with grid layout
struct SoundCategoryView: View {
    
    // MARK: - Properties
    let sounds: [Sound]
    @Binding var selectedSound: Sound?
    @State private var selectedCategory: SoundCategory = .all
    @State private var searchText: String = ""
    @State private var viewModel = SoundViewModel()
    
    // MARK: - Computed Properties
    private var filteredSounds: [Sound] {
        let nonAlarmSounds = sounds.filter { $0.category != SoundCategory.alarm.rawValue }
        
        let categoryFiltered = selectedCategory == .all 
            ? nonAlarmSounds 
            : nonAlarmSounds.filter { $0.category == selectedCategory.rawValue }
        
        let searchFiltered = if searchText.isEmpty {
            categoryFiltered
        } else {
            categoryFiltered.filter { sound in
                sound.name.localizedCaseInsensitiveContains(searchText) ||
                sound.description.localizedCaseInsensitiveContains(searchText)
            }
        }
        
        // Sort sounds alphabetically by name
        return searchFiltered.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending }
    }
    
    // MARK: - Helper Methods
    private func getCategoryCount(for category: SoundCategory) -> Int {
        let nonAlarmSounds = sounds.filter { $0.category != SoundCategory.alarm.rawValue }
        
        if category == .all {
            return nonAlarmSounds.count
        } else {
            return nonAlarmSounds.filter { $0.category == category.rawValue }.count
        }
    }
    
    private var categories: [SoundCategory] {
        let nonAlarmSounds = sounds.filter { $0.category != SoundCategory.alarm.rawValue }
        let uniqueCategoryStrings = Set(nonAlarmSounds.map { $0.category })
        
        // Convert string categories to enum cases and filter out invalid ones
        let validCategories = uniqueCategoryStrings.compactMap { SoundCategory(from: $0) }
        
        // Always include "All" and filter other categories based on available sounds
        let allCategories = [SoundCategory.all] + validCategories
        
        // Return sorted categories using the enum's sort order
        return SoundCategory.sortedNoiseCategories.filter { allCategories.contains($0) }
    }
    
    
    // MARK: - Body
    var body: some View {
        VStack(spacing: Design.Spacing.medium) {
            // Search Bar
            searchBar
            
            // Category Tabs
            categoryTabs
            
            // Scrollable Sound Grid
            ScrollView {
                soundGrid
            }
        }
        .padding(.top, Design.Spacing.medium)
    }
    
    // MARK: - Subviews
    private var searchBar: some View {
        HStack {
            Image(systemName: "magnifyingglass")
                .foregroundColor(.secondary)
            
            TextField("Search sounds...", text: $searchText)
                .textFieldStyle(.plain)
                .foregroundColor(.primary)
                .autocorrectionDisabled()
                .textInputAutocapitalization(.never)
        }
        .padding(.horizontal, Design.Spacing.medium)
        .padding(.vertical, Design.Spacing.small)
        .background(Color(.systemGray6))
        .cornerRadius(10)
    }
    
    private var categoryTabs: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            HStack(spacing: Design.Spacing.small) {
                ForEach(categories) { category in
                    CategoryTab(
                        title: category.displayName,
                        isSelected: selectedCategory == category,
                        count: getCategoryCount(for: category)
                    ) {
                        selectedCategory = category
                    }
                }
            }
            .padding(.horizontal, Design.Spacing.medium)
        }
    }
    
    private var soundGrid: some View {
        LazyVStack(spacing: Design.Spacing.small) {
            ForEach(filteredSounds) { sound in
                SoundCard(
                    sound: sound,
                    isSelected: selectedSound?.id == sound.id,
                    isPreviewing: viewModel.isPreviewing && viewModel.previewSound?.id == sound.id,
                    onSelect: {
                        viewModel.selectSound(sound)
                        selectedSound = sound
                    },
                    onPreview: {
                        viewModel.previewSound(sound)
                    }
                )
            }
        }
        .padding(.horizontal, Design.Spacing.medium)
    }
}

// MARK: - Supporting Views
struct CategoryTab: View {
    let title: String
    let isSelected: Bool
    let count: Int
    let action: () -> Void
    
    var body: some View {
        Button(action: action) {
            HStack(spacing: 4) {
                Text(title)
                    .font(.subheadline.weight(.medium))
                
                if count > 0 {
                    Text("(\(count))")
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
            }
            .padding(.horizontal, Design.Spacing.medium)
            .padding(.vertical, Design.Spacing.small)
            .background(isSelected ? AppAccent.primary : Color(.systemGray6))
            .foregroundColor(isSelected ? .white : AppTextColors.primary)
            .cornerRadius(20)
        }
        .buttonStyle(.plain)
    }
}

struct SoundCard: View {
    let sound: Sound
    let isSelected: Bool
    let isPreviewing: Bool
    let onSelect: () -> Void
    let onPreview: () -> Void
    
    var body: some View {
        HStack(spacing: Design.Spacing.medium) {
            // Sound Icon (Left)
            ZStack {
                Circle()
                    .fill(isSelected ? AppAccent.primary : Color(.systemGray5))
                    .frame(width: 50, height: 50)
                
                Image(systemName: soundIcon)
                    .font(.title3)
                    .foregroundColor(isSelected ? .white : AppTextColors.primary)
                
                if isPreviewing {
                    Circle()
                        .stroke(AppAccent.primary, lineWidth: 2)
                        .frame(width: 58, height: 58)
                        .scaleEffect(1.02)
                        .animation(.easeInOut(duration: 0.5).repeatForever(autoreverses: true), value: isPreviewing)
                }
            }
            
            // Sound Info (Right)
            VStack(alignment: .leading, spacing: 4) {
                // Sound Name
                Text(sound.name)
                    .font(.subheadline.weight(.medium))
                    .foregroundColor(AppTextColors.primary)
                    .lineLimit(1)
                
                // Description
                Text(sound.description)
                    .font(.caption)
                    .foregroundColor(.secondary)
                    .lineLimit(2)
                
                // Category Badge
                HStack {
                    Text(sound.category.capitalized)
                        .font(.caption2.weight(.medium))
                        .foregroundColor(.white)
                        .padding(.horizontal, 6)
                        .padding(.vertical, 2)
                        .background(AppAccent.primary, in: Capsule())
                    
                    Spacer()
                }
            }
            
            Spacer()
        }
        .padding(.horizontal, Design.Spacing.medium)
        .padding(.vertical, Design.Spacing.small)
        .background(
            RoundedRectangle(cornerRadius: 12)
                .fill(isSelected ? AppAccent.primary.opacity(0.1) : Color(.systemBackground))
                .overlay(
                    RoundedRectangle(cornerRadius: 12)
                        .stroke(isSelected ? AppAccent.primary : Color.clear, lineWidth: 2)
                )
        )
        .onTapGesture {
            onSelect()
        }
        .onLongPressGesture {
            onPreview()
        }
    }
    
    private var soundIcon: String {
        return SoundCategory(from: sound.category)?.icon ?? "speaker.wave.2"
    }
}

// MARK: - Preview
#Preview {
    SoundCategoryView(
        sounds: [
            Sound(name: "White Noise", fileName: "white-noise.mp3", category: "ambient", description: "Classic white noise"),
            Sound(name: "Heavy Rain", fileName: "heavy-rain.mp3", category: "nature", description: "Heavy rainfall sounds"),
            Sound(name: "Fan Noise", fileName: "fan-noise.mp3", category: "mechanical", description: "Fan sounds"),
            Sound(name: "Digital Alarm", fileName: "digital-alarm.mp3", category: "alarm", description: "Alarm sound")
        ],
        selectedSound: .constant(nil)
    )
    .padding()
}
