import SwiftUI

/// Updates screen — desktop + Android parity.
/// Shows app version info, up-to-date status, release notes, and a "Check for Updates" button.
struct UpdatesView: View {
    @Environment(\.dismiss) private var dismiss

    var body: some View {
        ZStack(alignment: .topLeading) {
            ScrollView(showsIndicators: false) {
                VStack(spacing: 0) {
                    statusCard
                    versionCard
                    helpText
                    checkButton
                }
                .padding(.horizontal, 16)
                .padding(.top, 60)
                .padding(.bottom, 100)
            }

            // Inline back button — UIKit ComposeGlassBackButton (SVG chevron, identical to Appearance)
            SettingsGlassBackButton {
                dismiss()
            }
            .frame(width: 44, height: 44)
            .padding(.leading, 8)
            .padding(.top, 4)
        }
        .background(RosettaColors.Adaptive.background)
        .scrollContentBackground(.hidden)
        .navigationBarTitleDisplayMode(.inline)
        .navigationBarBackButtonHidden(true)
        .enableSwipeBack()
        .toolbarBackground(.hidden, for: .navigationBar)
    }

    // MARK: - Status Card

    private var statusCard: some View {
        SettingsCard {
            HStack(spacing: 10) {
                Image(systemName: "checkmark.circle.fill")
                    .font(.system(size: 22))
                    .foregroundStyle(RosettaColors.success)

                VStack(alignment: .leading, spacing: 2) {
                    Text("App is up to date")
                        .font(.system(size: 15, weight: .medium))
                        .foregroundStyle(RosettaColors.success)

                    Text("You're using the latest version")
                        .font(.system(size: 13))
                        .foregroundStyle(RosettaColors.Adaptive.textSecondary)
                }

                Spacer()
            }
            .padding(16)
        }
    }

    // MARK: - Version Card

    private var versionCard: some View {
        SettingsCard {
            VStack(spacing: 0) {
                versionRow(title: "Application Version", value: ReleaseNotes.appVersion)

                Divider()
                    .background(RosettaColors.Adaptive.divider)
                    .padding(.horizontal, 16)

                versionRow(title: "Build Number", value: ReleaseNotes.buildNumber)
            }
        }
        .padding(.top, 16)
    }

    private func versionRow(title: String, value: String) -> some View {
        HStack {
            Text(title)
                .font(.system(size: 15))
                .foregroundStyle(RosettaColors.Adaptive.text)

            Spacer()

            Text(value)
                .font(.system(size: 15, weight: .medium))
                .foregroundStyle(RosettaColors.Adaptive.textSecondary)
        }
        .padding(.horizontal, 16)
        .frame(height: 48)
    }

    // MARK: - Help Text

    private var helpText: some View {
        Text("We recommend always keeping the app up to date to improve visual effects and have the latest features.")
            .font(.system(size: 13))
            .foregroundStyle(RosettaColors.Adaptive.textSecondary)
            .frame(maxWidth: .infinity, alignment: .leading)
            .padding(.horizontal, 16)
            .padding(.top, 12)
            .padding(.bottom, 8)
    }

    // MARK: - Check Button

    private var checkButton: some View {
        Button {} label: {
            Text("Check for Updates")
                .font(.system(size: 17, weight: .medium))
                .foregroundStyle(.white)
                .frame(maxWidth: .infinity)
                .frame(height: 48)
        }
        .buttonStyle(RosettaPrimaryButtonStyle())
        .padding(.top, 16)
    }

    // MARK: - Release Notes

    /// Desktop parity: shows release notes for each version.
    /// Desktop sends these as system messages from the "updates" account;
    /// iOS displays them inline on the Updates settings page.
    private var releaseNotesSection: some View {
        VStack(alignment: .leading, spacing: 16) {
            Text("What's New")
                .font(.system(size: 20, weight: .bold))
                .foregroundStyle(RosettaColors.Adaptive.text)
                .padding(.horizontal, 4)

            ForEach(ReleaseNotes.entries) { entry in
                releaseNoteCard(entry)
            }
        }
        .padding(.top, 28)
    }

    private func releaseNoteCard(_ entry: ReleaseNotes.Entry) -> some View {
        SettingsCard {
            VStack(alignment: .leading, spacing: 12) {
                HStack(spacing: 8) {
                    Image(systemName: "sparkles")
                        .font(.system(size: 14, weight: .semibold))
                        .foregroundStyle(RosettaColors.primaryBlue)

                    Text("Version \(entry.version)")
                        .font(.system(size: 15, weight: .semibold))
                        .foregroundStyle(RosettaColors.Adaptive.text)
                }

                VStack(alignment: .leading, spacing: 6) {
                    ForEach(entry.changes, id: \.self) { change in
                        HStack(alignment: .top, spacing: 8) {
                            Text("\u{2022}")
                                .font(.system(size: 15))
                                .foregroundStyle(RosettaColors.Adaptive.textSecondary)

                            Text(change)
                                .font(.system(size: 14))
                                .foregroundStyle(RosettaColors.Adaptive.textSecondary)
                                .fixedSize(horizontal: false, vertical: true)
                        }
                    }
                }
            }
            .padding(16)
        }
    }
}

// MARK: - Glass Back Button Bridge (UIKit → SwiftUI)

/// Wraps `ComposeGlassBackButton` (UIKit) for use in SwiftUI settings screens.
/// Identical chevron icon to AppearanceViewController's back button.
struct SettingsGlassBackButton: UIViewRepresentable {
    var action: () -> Void

    func makeUIView(context: Context) -> ComposeGlassBackButton {
        let button = ComposeGlassBackButton()
        button.addTarget(context.coordinator, action: #selector(Coordinator.tapped), for: .touchUpInside)
        return button
    }

    func updateUIView(_ uiView: ComposeGlassBackButton, context: Context) {
        context.coordinator.action = action
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(action: action)
    }

    final class Coordinator: NSObject {
        var action: () -> Void
        init(action: @escaping () -> Void) { self.action = action }
        @objc func tapped() { action() }
    }
}
