import SwiftUI
import SFSafeSymbols

struct PostDetailView: View {

    @Environment(\.language)
    private var language

    @EnvironmentObject
    private var content: Content

    @EnvironmentObject
    private var selection: SelectedContent

    @ObservedObject
    private var post: Post

    @State
    private var showLinkedPagePicker = false

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

    private var transferImage: (language: ContentLanguage, image: FileResource)? {
        post.localized(in: language.next).linkPreview.image.map { (language.next, $0) }
    }

    var body: some View {
        ScrollView {
            VStack(alignment: .leading) {
                DetailTitle(
                    title: "Post",
                    text: "Posts capture quick updates and can link to pages")

                if let page = post.linkedPage {
                    ColoredButton(
                        icon: .document,
                        text: "Show page",
                        fillColor: .blue,
                        textColor: .white,
                        action: { showPage(page) })

                } else {
                    ColoredButton(
                        icon: .documentBadgePlus,
                        text: "Create page",
                        fillColor: .blue,
                        textColor: .white,
                        action: createPageFromPost)
                }

                IdPropertyView(
                    id: $post.identifier,
                    footer: "The id is used to link to post and store them",
                    validation: post.isValid,
                    update: { post.update(id: $0) })
                .id(post.id)

                BoolPropertyView(
                    title: "Draft",
                    value: $post.isDraft,
                    footer: "Indicate a post as a draft to hide it from the website")

                DatePropertyView(
                    title: "Start date",
                    value: $post.startDate,
                    footer: "The date when the post content started")

                OptionalDatePropertyView(
                    title: "End date",
                    isEnabled: $post.hasEndDate,
                    date: $post.potentialEndDate,
                    footer: "The date when the post content ended")

                PagePropertyView(
                    title: "Linked page",
                    selectedPage: $post.linkedPage,
                    footer: "The page to open when clicking on the post")
                .onChange(of: post.linkedPage) { oldValue, newValue in

                    if newValue != nil {
                        post.tags = []
                    } else {
                        // Link removed, so copy tags from previous link
                        if let oldValue {
                            post.tags = oldValue.tags
                        }
                    }
                }

                FilesPropertyView(
                    title: "Associated workout",
                    footer: "The workout file to display with this post",
                    selectedFiles: $post.associatedWorkouts,
                    allowedType: .route)

                LocalizedPostDetailView(
                    post: post.localized(in: language),
                    transferImage: transferImage)
                ColoredButton(delete: deletePost)
            }
            .padding()
        }
    }

    private func createPageFromPost() {
        let page = post.makePage()
        DispatchQueue.main.async {
            content.pages.insert(page, at: 0)
            post.linkedPage = page
            selection.page = page
            selection.tab = .pages
        }
    }

    private func showPage(_ page: Page) {
        selection.page = page
        selection.tab = .pages
    }

    private func deletePost() {
        guard content.storage.delete(post: post.identifier) else {
            print("Post '\(post.identifier)': Failed to delete file in content folder")
            return
        }
        content.remove(post)
        selection.remove(post)
    }
}

extension PostDetailView: MainContentView {

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

    static let itemDescription = "a post"
}


#Preview(traits: .fixedLayout(width: 270, height: 500)) {
    PostDetailView(post: .Mock.hike2)
}
