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

import SwiftUI
import SwiftData

struct MainView: View {
    @Environment(\.modelContext) private var modelContext
    @Query private var items: [OCProject]
    
    @State private var newProjectName = ""
    @State private var addNewProject = false

    var body: some View {
        NavigationSplitView {
            List {
                ForEach(items) { project in
                    NavigationLink {
                        CardsView(project: project)
                    } label: {
                        VStack(alignment: .leading) {
                            Text("\(project.name)")
                                .bold()
                                .font(.title2)
                                .foregroundStyle(Color(hex: project.color) ?? .white)
                            Text("\(project.cards.count) Cards")
                        }
                    }
                    .padding(.horizontal, 8)
                    .padding(.vertical, 3)
                }
                .onDelete(perform: deleteItems)
                
            }
            .toolbar {
//                ToolbarItem(placement: .navigationBarTrailing) {
//                    EditButton()
//                }
                ToolbarItem {
                    Button(action: { addNewProject.toggle() }) {
                        Label("Add Item", systemImage: "plus")
                    }
                }
            }
            .navigationTitle("Projects")
        } detail: {
            Text("Select an item")
        }
        .sheet(isPresented: $addNewProject) {
            NewProjectForm(completionHandler: addItem)
        }
    }

    private func addItem(name: String, color: String) {
        withAnimation {
            let newProject = OCProject(name: name, color: color)
            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: OCProject.self, configurations: config)
    
    container.mainContext.insert(PreviewData.project)
    
    return MainView()
            .modelContainer(container)
}
