import AppKit
import SwiftUI

private enum TravelWebEndpoints {
    static let home = URL(string: "https://www.google.com/travel")!
    /// Resolves `/travel/…` paths to `https://www.google.com/travel/…`.
    static let pathBase = URL(string: "https://www.google.com")!
    static let explorePath = "/travel/explore"
    static let flightsPath = "/travel/flights"
    static let hotelsPath = "/travel/hotels"
    /// Vacation rentals live under Hotels with a search hint (`/travel/vacation-rentals` 404s).
    static let vacationRentalsPath = "/travel/hotels?q=vacation+rentals"
}

/// Large Google Travel: toolbar, search, and four shortcuts (Explore, Flights, Hotels, Vacation rentals). No embedded trip panel.
struct TravelDesktopWidgetView: View {
    let app: LauncherApp
    let mode: TravelWidgetMode
    var isPreview: Bool = false

    @State private var searchText: String = ""

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

    private var interactiveBody: some View {
        Group {
            if isPreview {
                travelPreviewChrome
            } else {
                travelLiveChrome
            }
        }
    }

    private var travelPreviewChrome: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 22, style: .continuous)
                .fill(
                    LinearGradient(
                        colors: [Color(red: 0.12, green: 0.38, blue: 0.42), Color(red: 0.08, green: 0.22, blue: 0.32)],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    )
                )
            VStack(spacing: 12) {
                AppIconView(app: app, size: 48, showAppBackground: false, iconPaddingFactor: 0.08)
                Text("Google Travel")
                    .font(.system(size: 15, weight: .bold))
                    .foregroundStyle(.white.opacity(0.92))
                Text("Search destinations or jump to Explore, Flights, Hotels, and Vacation rentals in the in-app browser.")
                    .font(.system(size: 11, weight: .medium))
                    .foregroundStyle(.white.opacity(0.72))
                    .multilineTextAlignment(.center)
                    .padding(.horizontal, 8)
            }
            .padding(16)
        }
    }

    private var travelLiveChrome: some View {
        travelToolbar
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(
                RoundedRectangle(cornerRadius: 22, style: .continuous)
                    .fill(Color(red: 0.06, green: 0.22, blue: 0.26))
            )
            .preferredColorScheme(.dark)
    }

    private var travelToolbar: some View {
        VStack(alignment: .leading, spacing: 8) {
            HStack(spacing: 8) {
                AppIconView(app: app, size: 28, showAppBackground: false, iconPaddingFactor: 0.08)
                Text("Travel")
                    .font(.system(size: 14, weight: .bold))
                    .foregroundStyle(.white.opacity(0.95))
                Spacer(minLength: 0)
                Button(action: refreshAction) {
                    Image(systemName: "arrow.clockwise")
                        .font(.system(size: 13, weight: .semibold))
                        .foregroundStyle(.white.opacity(0.9))
                        .padding(8)
                        .background(Circle().fill(Color.white.opacity(0.12)))
                }
                .buttonStyle(.plain)
                .help("Repeat search, or open Travel home if the field is empty")
                Button(action: { openInAppBrowser(TravelWebEndpoints.home) }) {
                    Image(systemName: "arrow.up.right.square")
                        .font(.system(size: 13, weight: .semibold))
                        .foregroundStyle(.white.opacity(0.9))
                        .padding(8)
                        .background(Circle().fill(Color.white.opacity(0.12)))
                }
                .buttonStyle(.plain)
                .help("Open Travel in browser")
            }

            HStack(spacing: 6) {
                TextField("Search destinations", text: $searchText)
                    .textFieldStyle(.plain)
                    .font(.system(size: 12, weight: .medium))
                    .padding(.horizontal, 10)
                    .padding(.vertical, 6)
                    .background(
                        RoundedRectangle(cornerRadius: 10, style: .continuous)
                            .fill(Color.white.opacity(0.1))
                    )
                    .foregroundStyle(.white.opacity(0.95))
                    .onSubmit { submitSearch() }
                Button("Go", action: submitSearch)
                    .font(.system(size: 12, weight: .semibold))
                    .buttonStyle(.borderedProminent)
                    .tint(Color(red: 0.1, green: 0.55, blue: 0.52))
                    .controlSize(.small)
            }

            travelCategoryRow
        }
        .padding(.horizontal, 12)
        .padding(.top, 12)
        .padding(.bottom, 10)
        .frame(maxWidth: .infinity)
    }

    private var travelCategoryRow: some View {
        HStack(spacing: 0) {
            travelCategoryButton(title: "Explore", path: TravelWebEndpoints.explorePath) {
                exploreCategoryIcon
            }
            travelCategoryButton(title: "Flights", path: TravelWebEndpoints.flightsPath) {
                Image(systemName: "airplane")
                    .font(.system(size: 20, weight: .medium))
            }
            travelCategoryButton(title: "Hotels", path: TravelWebEndpoints.hotelsPath) {
                Image(systemName: "bed.double.fill")
                    .font(.system(size: 20, weight: .medium))
            }
            travelCategoryButton(title: "Vacation rentals", path: TravelWebEndpoints.vacationRentalsPath) {
                Image(systemName: "house.fill")
                    .font(.system(size: 20, weight: .medium))
            }
        }
        .padding(.top, 6)
    }

    /// Globe + magnifying glass, similar to Google Travel’s Explore affordance.
    private var exploreCategoryIcon: some View {
        ZStack {
            Image(systemName: "globe.americas.fill")
                .font(.system(size: 19, weight: .medium))
            Image(systemName: "magnifyingglass")
                .font(.system(size: 9, weight: .bold))
                .offset(x: 9, y: 7)
        }
        .frame(width: 28, height: 26)
    }

    private func travelCategoryButton<Icon: View>(
        title: String,
        path: String,
        @ViewBuilder icon: () -> Icon
    ) -> some View {
        Button {
            openTravelPath(path)
        } label: {
            VStack(spacing: 5) {
                icon()
                    .foregroundStyle(Color.white.opacity(0.72))
                Text(title)
                    .font(.system(size: 10, weight: .medium))
                    .foregroundStyle(Color.white.opacity(0.78))
                    .multilineTextAlignment(.center)
                    .lineLimit(2)
                    .minimumScaleFactor(0.85)
            }
            .frame(maxWidth: .infinity)
            .padding(.vertical, 6)
            .contentShape(Rectangle())
        }
        .buttonStyle(.plain)
    }

    private func openTravelPath(_ path: String) {
        NSApp.activate(ignoringOtherApps: true)
        let url = WidgetDeepLinkURL.resolved(base: TravelWebEndpoints.pathBase, actionPath: path, accountSlot: 0)
        openInAppBrowser(url)
    }

    private func refreshAction() {
        NSApp.activate(ignoringOtherApps: true)
        let q = searchText.trimmingCharacters(in: .whitespacesAndNewlines)
        if q.isEmpty {
            openInAppBrowser(TravelWebEndpoints.home)
        } else {
            openExplore(query: q)
        }
    }

    private func submitSearch() {
        let q = searchText.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !q.isEmpty else { return }
        NSApp.activate(ignoringOtherApps: true)
        openExplore(query: q)
    }

    private func openExplore(query q: String) {
        var c = URLComponents(string: "https://www.google.com/travel/explore")!
        c.queryItems = [URLQueryItem(name: "q", value: q)]
        if let url = c.url {
            openInAppBrowser(url)
        }
    }

    private func openInAppBrowser(_ url: URL) {
        InAppBrowserWindowManager.shared.open(url: url, title: app.name)
    }
}
