import SwiftUI
import HighlightedTextEditor
import SFSafeSymbols

struct PostContentView: View {

    @ObservedObject
    var post: Post

    @Environment(\.language)
    private var language

    init(post: Post) {
        self.post = post
    }

    var body: some View {
        LocalizedPostContentView(post: post)
    }
}

extension PostContentView: MainContentView {

    init(item: Post) {
        self.post = item
    }

    static let itemDescription = "a post"
}

private struct LocalizedTitle: View {

    @ObservedObject
    private var post: LocalizedPost

    init(post: LocalizedPost) {
        self.post = post
    }

    var body: some View {
        TextField("", text: $post.title)
            .font(.system(size: 24, weight: .bold))
            .foregroundStyle(Color.primary)
            .textFieldStyle(.plain)
            .lineLimit(2)
            .frame(minHeight: 30)
    }
}

private struct LocalizedContentEditor: View {

    @ObservedObject
    private var post: LocalizedPost

    init(post: LocalizedPost) {
        self.post = post
    }

    var body: some View {
        TextEditor(text: $post.text)
            .font(.body)
            .frame(minHeight: 150)
            .textEditorStyle(.plain)
            .padding(.vertical, 8)
            .padding(.leading, 3)
            .background(Color.gray.opacity(0.1))
            .cornerRadius(8)
    }
}

private struct LinkedPageTagView: View {

    @ObservedObject
    var page: Page

    var body: some View {
        TagDisplayView(tags: $page.tags)
    }
}

struct LocalizedPostContentView: View {

    @ObservedObject
    var post: Post

    @Environment(\.language)
    private var language

    @EnvironmentObject
    private var content: Content

    init(post: Post) {
        self.post = post
    }

    var body: some View {
        VStack(alignment: .leading) {
            HStack {
                Text("Images")
                    .font(.headline)
                Button("Transfer from \(language.next.text)", action: copyImagesFromOtherLanguage)
            }
            PostImagesView(post: post.localized(in: language))
            LocalizedTitle(post: post.localized(in: language))
            if let page = post.linkedPage {
                LinkedPageTagView(page: page)
            } else {
                TagDisplayView(tags: $post.tags)
            }
            LocalizedContentEditor(post: post.localized(in: language))
        }
        .padding()
    }

    private func copyImagesFromOtherLanguage() {
        let images = post.localized(in: language.next).images
        post.localized(in: language).images = images
    }
}

#Preview(traits: .fixedLayout(width: 450, height: 600)) {
    List {
        PostContentView(post: .fullMock)
            .listRowSeparator(.hidden)
            .environment(\.language, ContentLanguage.german)
        PostContentView(post: .mock)
            .listRowSeparator(.hidden)
    }
    .environmentObject(Content.mock)
    //.listStyle(.plain)
}
