import SwiftUI

struct TagEditView: View {
    let tag: Tag
    @Environment(\.presentationMode) var presentationMode
    @Environment(\.managedObjectContext) private var viewContext
    @EnvironmentObject var linkViewModel: LinkViewModel

    @State private var tagDescription: String = ""
    @State private var saveErrorMessage: String = ""
    @State private var showingSaveError: Bool = false

    var body: some View {
        NavigationView {
            Form {
                Section {
                    VStack(alignment: .leading, spacing: 8) {
                        Text("tag_name")
                            .font(.headline)

                        Text(tag.name)
                            .font(.body)
                            .foregroundColor(.secondary)
                            .padding()
                            .frame(maxWidth: .infinity, alignment: .leading)
                            .background(Color(.systemGray6))
                            .cornerRadius(8)
                    }
                } header: {
                    Text("tag_information")
                } footer: {
                    Text("tag_name_cannot_be_changed")
                        .font(.caption)
                        .foregroundColor(.secondary)
                }

                Section {
                    VStack(alignment: .leading, spacing: 8) {
                        Text("description")
                            .font(.headline)

                        TextEditor(text: $tagDescription)
                            .frame(minHeight: 100)
                            .background(Color(.systemBackground))
                    }
                } header: {
                    Text("tag_description")
                } footer: {
                    Text("add_description_to_help_organize_links")
                        .font(.caption)
                        .foregroundColor(.secondary)
                }

                Section {
                    HStack {
                        VStack(alignment: .leading) {
                            Text("associated_links")
                                .font(.headline)
                            Text("\(tag.linkCount) links")
                                .font(.body)
                                .foregroundColor(.secondary)
                        }

                        Spacer()

                        VStack(alignment: .trailing) {
                            Text("created")
                                .font(.headline)
                            Text(tag.createdAt, format: .dateTime.year().month().day())
                                .font(.body)
                                .foregroundColor(.secondary)
                        }
                    }
                } header: {
                    Text("statistics")
                }
            }
            .navigationTitle("edit_tag")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("cancel") {
                        presentationMode.wrappedValue.dismiss()
                    }
                }

                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("save") {
                        saveTag()
                    }
                }
            }
            .onAppear {
                tagDescription = tag.tagDescription ?? ""
            }
            .alert("error", isPresented: $showingSaveError) {
                Button("ok") { }
            } message: {
                Text(saveErrorMessage)
            }
        }
    }

    private func saveTag() {
        // Update the tag description
        tag.tagDescription = tagDescription.isEmpty ? nil : tagDescription

        do {
            try viewContext.save()
            linkViewModel.fetchLinks() // Refresh if needed
            presentationMode.wrappedValue.dismiss()
        } catch {
            saveErrorMessage = error.localizedDescription
            showingSaveError = true
        }
    }
}

#Preview {
    let context = PersistenceController.preview.container.viewContext
    let tag = Tag(context: context)
    tag.name = "Sample Tag"
    tag.tagDescription = "This is a sample tag description."
    tag.createdAt = Date()

    return TagEditView(tag: tag)
        .environment(\.managedObjectContext, context)
        .environmentObject(LinkViewModel())
}
