import SwiftUI

struct WebsitePreviewSheet: View {

    @EnvironmentObject
    private var content: Content

    @EnvironmentObject
    private var server: WebServer

    @Environment(\.dismiss)
    private var dismiss

    var body: some View {
        VStack {
            HStack {
                Button(action: { server.loadHomeUrl() }) {
                    Image(systemSymbol: .house)
                }
                .disabled(server.isNotReady)
                Button(action: { server.reloadPage() }) {
                    Image(systemSymbol: .arrowClockwise)
                }
                .disabled(server.isNotReady)
                TextField("", text: $server.currentUrl)
                    .disabled(true)
                    .textFieldStyle(.roundedBorder)
                Spacer()
                Button("Close", action: dismissSheet)
            }
            .padding()
            if server.isRunning {
                WebView(viewModel: server)
            } else if server.isStarting {
                Spacer()
                ProgressView()
                Text("Loading preview...")
                    .font(.title)
                    .foregroundStyle(.secondary)
                Spacer()
            } else {
                Spacer()
                Text("Webserver disabled")
                    .font(.title)
                    .foregroundStyle(.secondary)
                Text("Enable it to check out the generated content")
                    .foregroundStyle(.secondary)
                Spacer()
            }
        }
        .frame(minWidth: 500, idealWidth: 600, idealHeight: 600)
        .onAppear(perform: startWebServer)
    }

    private func dismissSheet() {
        if server.isRunning {
            server.stopServer()
        }
        dismiss()
    }

    private func startWebServer() {
        guard !server.isRunning else {
            server.stopServer()
            return
        }
        guard let folder = content.storage.outputScope?.url.path() else {
            print("No output folder to start server")
            return
        }

        server.startServer(in: folder)
    }
}
