import SwiftUI
import SFSafeSymbols
import HighlightedTextEditor

struct LocalizedPageContentView: View {

    @EnvironmentObject
    var content: Content

    let pageId: String

    let language: ContentLanguage

    @ObservedObject
    var page: LocalizedPage

    @State
    private var pageContent: String = ""

    @State
    private var pageContentUsedForGeneration: String = ""

    @State
    private var generationResults: PageGenerationResults?

    @State
    private var didChangeContent = false

    init(pageId: String, page: LocalizedPage, language: ContentLanguage) {
        self.pageId = pageId
        self.page = page
        self.language = language
    }

    var body: some View {
        VStack(alignment: .leading) {
            TextField("", text: $page.title)
                .font(.title)
                .textFieldStyle(.plain)

            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()
            }
            if let generationResults {
                PageContentResultsView(results: generationResults)
            }
            HighlightedTextEditor(
                text: $pageContent,
                highlightRules: .markdown)
            .onChange(of: pageContent) {
                didChangeContent = true
            }
        }
        .onAppear(perform: loadContent)
        .onDisappear(perform: saveContent)
    }

    private func loadContent() {
        let language = language
        guard page.content.storage.hasPageContent(for: pageId, language: language) else {
            pageContent = "New file"
            DispatchQueue.main.async {
                didChangeContent = false
            }
            return
        }
        guard let content = page.content.storage.pageContent(for: pageId, language: 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.content.storage.save(pageContent: pageContent, for: pageId, language: language) else {
            print("Failed to save content")
            return
        }
        didChangeContent = false
    }

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