import AppKit
import SwiftUI

private let playPanelBackground = Color(red: 0.05, green: 0.09, blue: 0.08)
private let playAccent = Color(red: 0.0, green: 0.53, blue: 0.38)

/// Medium: search the Play Store for apps; open the store home in-app.
struct GooglePlayDesktopWidgetView: View {
    let app: LauncherApp
    let mode: GooglePlayWidgetMode
    var isPreview: Bool = false

    @State private var searchText: String = ""

    private var baseURL: URL { app.webURL ?? URL(string: "https://play.google.com")! }

    var body: some View {
        Group {
            switch mode {
            case .searchBar:
                searchBarRoot
            }
        }
        .clipShape(RoundedRectangle(cornerRadius: 22, style: .continuous))
    }

    private var searchBarRoot: some View {
        Group {
            if isPreview {
                playPreviewChrome
            } else {
                searchBarLive
            }
        }
    }

    private var playPreviewChrome: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 22, style: .continuous)
                .fill(
                    LinearGradient(
                        colors: [playAccent.opacity(0.85), playPanelBackground],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    )
                )
            VStack(spacing: 12) {
                AppIconView(app: app, size: 48, showAppBackground: false, iconPaddingFactor: 0.08)
                Text("Play Store search")
                    .font(.system(size: 15, weight: .bold))
                    .foregroundStyle(.white.opacity(0.95))
                Text("Search apps and games; open the full Play Store in the in-app browser.")
                    .font(.system(size: 11, weight: .medium))
                    .foregroundStyle(.white.opacity(0.75))
                    .multilineTextAlignment(.center)
                    .padding(.horizontal, 8)
            }
            .padding(16)
        }
    }

    private var searchBarLive: some View {
        VStack(alignment: .leading, spacing: 10) {
            HStack(spacing: 8) {
                AppIconView(app: app, size: 28, showAppBackground: false, iconPaddingFactor: 0.08)
                Text("Google Play")
                    .font(.system(size: 14, weight: .bold))
                    .foregroundStyle(.white.opacity(0.95))
                Spacer(minLength: 0)
            }

            HStack(spacing: 8) {
                TextField("Search apps & games", text: $searchText)
                    .textFieldStyle(.plain)
                    .font(.system(size: 13, weight: .medium))
                    .padding(.horizontal, 12)
                    .padding(.vertical, 8)
                    .background(
                        RoundedRectangle(cornerRadius: 12, style: .continuous)
                            .fill(Color.white.opacity(0.1))
                    )
                    .foregroundStyle(.white.opacity(0.95))
                    .onSubmit { submitSearch() }
                Button("Search", action: submitSearch)
                    .font(.system(size: 12, weight: .semibold))
                    .buttonStyle(.borderedProminent)
                    .tint(playAccent)
                    .controlSize(.regular)
            }

            Button(action: openPlayStoreHome) {
                HStack(spacing: 6) {
                    Image(systemName: "bag.fill")
                        .font(.system(size: 13, weight: .semibold))
                    Text("Open Play Store")
                        .font(.system(size: 12, weight: .bold))
                }
                .foregroundStyle(.white.opacity(0.95))
                .frame(maxWidth: .infinity)
                .padding(.vertical, 10)
                .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(Color.white.opacity(0.14)))
            }
            .buttonStyle(.plain)
        }
        .padding(14)
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(
            RoundedRectangle(cornerRadius: 22, style: .continuous)
                .fill(playPanelBackground)
        )
        .preferredColorScheme(.dark)
    }

    private func submitSearch() {
        let q = searchText.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !q.isEmpty else { return }
        NSApp.activate(ignoringOtherApps: true)
        guard var c = URLComponents(url: baseURL, resolvingAgainstBaseURL: false) else { return }
        c.path = "/store/search"
        c.queryItems = [
            URLQueryItem(name: "q", value: q),
            URLQueryItem(name: "c", value: "apps"),
        ]
        guard let url = c.url else { return }
        InAppBrowserWindowManager.shared.open(url: url, title: app.name)
    }

    private func openPlayStoreHome() {
        NSApp.activate(ignoringOtherApps: true)
        let url = WidgetDeepLinkURL.resolved(base: baseURL, actionPath: "/store/apps", accountSlot: 0)
        InAppBrowserWindowManager.shared.open(url: url, title: app.name)
    }
}
