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

import SwiftUI

struct CardsView: View {
    let project: OCProject
    @State private var addNewCard = false
    @State private var newCardText = ""
    @Environment(\.modelContext) private var ctx
    
    var body: some View {
        List {
            ForEach(project.cards) { card in
                CardView(proj: project, card: card)
            }
            .onDelete(perform: deleteItems)
        }
        .listStyle(.inset)
        .navigationTitle(project.name)
        .navigationBarTitleDisplayMode(.inline)
        .toolbar {
            ToolbarItem(placement: .topBarTrailing) {
                Button(action: { addNewCard.toggle() }) {
                    Label("Add Item", systemImage: "plus")
                }
            }
        }
        .sheet(isPresented: $addNewCard) {
            AddNewCardView(completionHandler: addNewCard)
        }
    }
    
    func addNewCard(txt: String) {
        let card = OCCard(content: txt, index: (project.cards.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()
    }
    
    func deleteItems(offsets: IndexSet) {
        withAnimation {
            project.cards.remove(atOffsets: offsets)
            try! ctx.save()
        }
    }
    
}

struct CardView: View {
    let proj: OCProject
    let card: OCCard
    
    var body: some View {
        VStack(alignment: .trailing) {
            Text(card.content)
        }
        .frame(minHeight: 80)
//        .padding()
//        .background(Color(hex: proj.color) ?? .blue)
//        .clipShape(.rect(cornerRadius: 12))
//        .padding(.horizontal)
//        .padding(.vertical)
    }
}

#Preview {
    return CardsView(project: OCProject(name: "Test", color: "FF00FF"))
}
