import SwiftUI
import SFSafeSymbols
import HighlightedTextEditor

struct LocalizedPageContentView: View {

    @EnvironmentObject
    var content: Content

    @ObservedObject
    var page: Page

    let language: ContentLanguage

    @State
    private var pageContent: String = ""

    @State
    private var pageContentUsedForGeneration: String = ""

    @State
    private var generationResults: PageGenerationResults?

    @State
    private var didChangeContent = false

    var body: some View {
        VStack(alignment: .leading) {
            HStack(alignment: .firstTextBaseline) {
                Button(action: loadContent) {
                    Text("Load")
                }
                Button(action: saveContent) {
                    Text("Save")
                }
                Button(action: checkContent) {
                    Text("Check")
                }.disabled(content.isGeneratingWebsite)
                if content.isGeneratingWebsite {
                    ProgressView()
                        .frame(height: 15)
                }
                Spacer()
            }

            HStack {
                if let generationResults {
                    PageContentResultsView(results: generationResults)
                }
                let linkingPosts = content.posts.filter { $0.linkedPage == page }
                TextWithPopup(
                    symbol: .ipadAndArrowForward,
                    text: "\(linkingPosts.count) linking posts",
                    items: linkingPosts.map { $0.title(in: language) })
            }.foregroundStyle(.secondary)
            InsertableItemsView()
            HighlightedTextEditor(
                text: $pageContent,
                highlightRules: .markdown)
            .onChange(of: pageContent) {
                didChangeContent = true
            }
        }
        .onAppear(perform: loadContent)
        .onDisappear(perform: saveContent)
    }

    private func loadContent() {
        let language = language
        guard page.localized(in: language).hasContent else {
            pageContent = "New file"
            DispatchQueue.main.async {
                didChangeContent = false
            }
            return
        }
        guard let content = page.pageContent(in: language) else {
            print("Failed to load page content")
            pageContent = "Failed to load"
            DispatchQueue.main.async {
                didChangeContent = false
            }
            return
        }
        guard content != "" else {
            pageContent = "New file"
            DispatchQueue.main.async {
                didChangeContent = false
            }
            return
        }
        pageContent = content
        checkContent()

        DispatchQueue.main.async {
            didChangeContent = false
        }
    }

    private func saveContent() {
        guard pageContent != "New file", pageContent != "" else {
            // TODO: Delete file?
            return
        }
        guard didChangeContent else {
            return
        }
        guard page.save(pageContent: pageContent, in: language) else {
            print("Failed to save content")
            return
        }
        didChangeContent = false
    }

    private func checkContent() {
        let content = self.pageContent
        guard content != pageContentUsedForGeneration else {
            return
        }
        guard !self.content.isGeneratingWebsite else {
            return
        }
        self.content.check(content: content, of: page, for: language) {
            self.generationResults = $0
        }
    }
}
