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

import SwiftUI
import SwiftData

struct CardsView: View {
    let project: OCProject
    @State private var addNewCard = false
    @State private var newCardText = ""
    @Environment(\.modelContext) private var ctx
    
    @State private var showNoTextInNewCardError = false
    
    var body: some View {
        List {
            Section {
                TextEditor(text: $newCardText)
            } header: {
                Text("Add new card")
            }
            Section {
                ForEach(project.sortedCards) { card in
                    Text(card.content)
                }
                .onDelete(perform: deleteItems)
            } header: {
                Text("\(project.cards.count) \(project.cards.count == 1 ? "Card" : "Cards")")
            }

        }
        .navigationTitle(project.name)
        .navigationBarTitleDisplayMode(.inline)
        .toolbar {
            ToolbarItem(placement: .topBarTrailing) {
                Button(action: { addNewCard(txt: newCardText) }) {
                    Label("Add Item", systemImage: "plus")
                }
            }
            ToolbarItem(placement: .topBarTrailing) {
                Menu {
                    NavigationLink(destination: {ProjectSlideshowView(project: project)}) {
                        Label(title: { Text("Cue Cards")}, icon: {Image(systemName: "rectangle.stack") })
                    }
                    NavigationLink(destination: {TeleprompterView(project: project)}) {
                        Label(title: { Text("Teleprompter")}, icon: {Image(systemName: "note.text") })
                    }
                } label: {
                    Image(systemName: "play.fill")
                }
                
            }
        }
        .sheet(isPresented: $addNewCard) {
            AddNewCardView(completionHandler: addNewCard)
        }
        .alert("No Text In Card", isPresented: $showNoTextInNewCardError) {
            Button("OK", role: .cancel) {}
        } message: {
            Text("Add some text in the New Card field, then press + again.")
        }

    }
    
    func addNewCard(txt: String) {
        guard txt != "" else {
            showNoTextInNewCardError.toggle()
            return
        }
        
        let card = OCCard(content: txt, index: (project.sortedCards.last?.index ?? -1) + 1) // adds one to the index, unless there arent any cards in which case default to 0
        project.cards.append(card)
        try! ctx.save()
        newCardText = ""
    }
    
    func deleteItems(offsets: IndexSet) {
        withAnimation {
            for i in offsets {
                let cardToRemove = project.sortedCards[i]
                project.removeCard(cardToRemove)
            }
            try! ctx.save()
        }
    }
}

#Preview {
    let config = ModelConfiguration(isStoredInMemoryOnly: true)
    let container = try! ModelContainer(for: OCProject.self, configurations: config)
    
    container.mainContext.insert(PreviewData.project)
    
    return NavigationView {
        CardsView(project: PreviewData.project)
            .modelContainer(container)
    }
}
