//
//  ContentView.swift
//  OnCue
//
//  Created by Pradyun Setti on 22/06/2024.
//

import SwiftUI
import SwiftData

struct ContentView: View {
    @Environment(\.modelContext) private var modelContext
    @Query private var items: [OCProject]

    var body: some View {
        NavigationSplitView {
            List {
                ForEach(items) { item in
                    NavigationLink {
                        Text("\(item.cards)")
                    } label: {
                        VStack(alignment: .leading) {
                            Text("\(item.name)")
                                .font(.system(.title2, design: .default, weight: .medium))
                                .foregroundStyle(.blue)
                            Text("\(item.cards.count) Cards")
                        }
                    }
                    .padding(12)
                }
                .onDelete(perform: deleteItems)
                
            }
            .toolbar {
                
                ToolbarItem(placement: .navigationBarTrailing) {
                    EditButton()
                }
                ToolbarItem {
                    Button(action: addItem) {
                        Label("Add Item", systemImage: "plus")
                    }
                }
            }
            .navigationTitle("Projects")
        } detail: {
            Text("Select an item")
        }
    }

    private func addItem() {
        withAnimation {
            let newProject = OCProject(name: "Gaming!")
            modelContext.insert(newProject)
        }
    }

    private func deleteItems(offsets: IndexSet) {
        withAnimation {
            for index in offsets {
                modelContext.delete(items[index])
            }
        }
    }
}

#Preview {
    
//    let config = ModelConfiguration(isStoredInMemoryOnly: true)
//        let container = try! ModelContainer(for: User.self, configurations: config)
//
//        let user = User(name: "Test User")
//        return EditingView(user: user)
//            .modelContainer(container)
    
    let config = ModelConfiguration(isStoredInMemoryOnly: true)
    let container = try! ModelContainer(for: OCProject.self, configurations: config)
    
    let p = OCProject(name: "test project")
    container.mainContext.insert(p)
    
    return ContentView()
            .modelContainer(container)
}
