import SwiftUI

// MARK: - Wallpaper Definitions

struct WallpaperOption: Identifiable, Equatable {
    let id: String
    let name: String
    let style: WallpaperStyle

    enum WallpaperStyle: Equatable {
        case none
        case image(String)   // Asset catalog image name (supports light/dark appearance)
    }
}

extension WallpaperOption {
    /// Android parity: 3 wallpaper pairs (light/dark) from mobile-android assets.
    /// Each imageset contains light + dark appearance variants.
    /// "ChatWallpaper" = legacy default (wallpaper_light_02 + wallpaper_dark_03).
    static let allOptions: [WallpaperOption] = [
        WallpaperOption(id: "default", name: "Default", style: .image("ChatWallpaper")),
        WallpaperOption(id: "wallpaper_1", name: "Pair 1", style: .image("Wallpaper1")),
        WallpaperOption(id: "wallpaper_2", name: "Pair 2", style: .image("Wallpaper2")),
        WallpaperOption(id: "wallpaper_3", name: "Pair 3", style: .image("Wallpaper3")),
        WallpaperOption(id: "none", name: "None", style: .none),
    ]
}

// MARK: - Theme Mode

enum ThemeMode: String, CaseIterable {
    case dark = "dark"
    case light = "light"
    case system = "system"

    var label: String {
        switch self {
        case .dark: return "Dark"
        case .light: return "Light"
        case .system: return "System"
        }
    }

    var iconName: String {
        switch self {
        case .dark: return "moon.fill"
        case .light: return "sun.max.fill"
        case .system: return "circle.lefthalf.filled"
        }
    }
}

// MARK: - Appearance View

struct AppearanceView: View {
    @AppStorage("rosetta_wallpaper_id") private var selectedWallpaperId: String = "default"
    @AppStorage("rosetta_theme_mode") private var themeModeRaw: String = "dark"

    private var themeMode: ThemeMode {
        ThemeMode(rawValue: themeModeRaw) ?? .dark
    }

    private let columns = Array(repeating: GridItem(.flexible(), spacing: 10), count: 3)

    var body: some View {
        ScrollView(showsIndicators: false) {
            VStack(spacing: 24) {
                chatPreviewSection
                themeSection
                wallpaperSection
            }
            .padding(.horizontal, 16)
            .padding(.top, 16)
            .padding(.bottom, 100)
        }
        .background(RosettaColors.Adaptive.background)
        .scrollContentBackground(.hidden)
        .navigationBarTitleDisplayMode(.inline)
        .toolbar {
            ToolbarItem(placement: .principal) {
                Text("Appearance")
                    .font(.system(size: 17, weight: .semibold))
                    .foregroundStyle(RosettaColors.Adaptive.text)
            }
        }
        .toolbarBackground(.hidden, for: .navigationBar)
    }

    // MARK: - Chat Preview

    private var chatPreviewSection: some View {
        VStack(spacing: 0) {
            ZStack {
                // Wallpaper background
                wallpaperPreview(for: selectedWallpaperId)
                    .frame(height: 200)
                    .clipShape(RoundedRectangle(cornerRadius: 20, style: .continuous))

                // Sample messages overlay
                VStack(spacing: 6) {
                    Spacer()

                    // Incoming message
                    HStack {
                        Text("Hey! How's it going?")
                            .font(.system(size: 15))
                            .foregroundStyle(.white)
                            .padding(.horizontal, 14)
                            .padding(.vertical, 8)
                            .background(
                                RoundedRectangle(cornerRadius: 18, style: .continuous)
                                    .fill(Color(hex: 0x2A2A2A))
                            )
                        Spacer()
                    }

                    // Outgoing message
                    HStack {
                        Spacer()
                        Text("Great, thanks!")
                            .font(.system(size: 15))
                            .foregroundStyle(.white)
                            .padding(.horizontal, 14)
                            .padding(.vertical, 8)
                            .background(
                                RoundedRectangle(cornerRadius: 18, style: .continuous)
                                    .fill(RosettaColors.primaryBlue)
                            )
                    }

                    Spacer()
                        .frame(height: 12)
                }
                .padding(.horizontal, 12)
            }
        }
    }

    // MARK: - Theme Section

    private var themeSection: some View {
        VStack(alignment: .leading, spacing: 10) {
            Text("COLOR THEME")
                .font(.system(size: 13, weight: .medium))
                .foregroundStyle(RosettaColors.Adaptive.textSecondary)
                .padding(.horizontal, 4)

            SettingsCard {
                HStack(spacing: 0) {
                    ForEach(ThemeMode.allCases, id: \.self) { mode in
                        themeButton(mode)
                        if mode != ThemeMode.allCases.last {
                            Divider()
                                .frame(height: 24)
                                .foregroundStyle(RosettaColors.Adaptive.divider)
                        }
                    }
                }
                .frame(height: 52)
            }
        }
    }

    private func themeButton(_ mode: ThemeMode) -> some View {
        Button {
            withAnimation(.easeInOut(duration: 0.2)) {
                themeModeRaw = mode.rawValue
            }
            applyThemeMode(mode)
        } label: {
            HStack(spacing: 8) {
                Image(systemName: mode.iconName)
                    .font(.system(size: 14))
                    .foregroundStyle(themeMode == mode ? RosettaColors.primaryBlue : RosettaColors.Adaptive.textSecondary)

                Text(mode.label)
                    .font(.system(size: 15, weight: themeMode == mode ? .semibold : .regular))
                    .foregroundStyle(themeMode == mode ? RosettaColors.primaryBlue : RosettaColors.Adaptive.text)
            }
            .frame(maxWidth: .infinity)
            .contentShape(Rectangle())
        }
        .buttonStyle(.plain)
    }

    private func applyThemeMode(_ mode: ThemeMode) {
        guard let windowScene = UIApplication.shared.connectedScenes
            .compactMap({ $0 as? UIWindowScene })
            .first(where: { $0.activationState == .foregroundActive })
                ?? UIApplication.shared.connectedScenes
            .compactMap({ $0 as? UIWindowScene }).first
        else { return }

        let style: UIUserInterfaceStyle
        switch mode {
        case .dark: style = .dark
        case .light: style = .light
        case .system: style = .unspecified
        }

        for window in windowScene.windows {
            window.overrideUserInterfaceStyle = style
        }
    }

    // MARK: - Wallpaper Section

    private var wallpaperSection: some View {
        VStack(alignment: .leading, spacing: 10) {
            Text("CHAT BACKGROUND")
                .font(.system(size: 13, weight: .medium))
                .foregroundStyle(RosettaColors.Adaptive.textSecondary)
                .padding(.horizontal, 4)

            LazyVGrid(columns: columns, spacing: 10) {
                ForEach(WallpaperOption.allOptions) { option in
                    wallpaperCell(option)
                }
            }
        }
    }

    private func wallpaperCell(_ option: WallpaperOption) -> some View {
        let isSelected = selectedWallpaperId == option.id

        return Button {
            withAnimation(.easeInOut(duration: 0.2)) {
                selectedWallpaperId = option.id
            }
        } label: {
            ZStack {
                wallpaperPreview(for: option.id)

                // "None" label
                if case .none = option.style {
                    Text("None")
                        .font(.system(size: 13, weight: .medium))
                        .foregroundStyle(RosettaColors.Adaptive.textSecondary)
                }

                // Selection checkmark
                if isSelected {
                    VStack {
                        Spacer()
                        HStack {
                            Spacer()
                            Image(systemName: "checkmark.circle.fill")
                                .font(.system(size: 22))
                                .foregroundStyle(RosettaColors.primaryBlue)
                                .background(Circle().fill(.white).frame(width: 18, height: 18))
                                .padding(8)
                        }
                    }
                }
            }
            .frame(height: 140)
            .clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous))
            .overlay(
                RoundedRectangle(cornerRadius: 14, style: .continuous)
                    .stroke(isSelected ? RosettaColors.primaryBlue : Color.white.opacity(0.1), lineWidth: isSelected ? 2 : 0.5)
            )
        }
        .buttonStyle(.plain)
    }

    // MARK: - Wallpaper Preview Renderer

    @ViewBuilder
    private func wallpaperPreview(for wallpaperId: String) -> some View {
        let option = WallpaperOption.allOptions.first(where: { $0.id == wallpaperId })
            ?? WallpaperOption.allOptions[0]

        switch option.style {
        case .none:
            RosettaColors.Adaptive.background

        case .image(let assetName):
            Image(assetName)
                .resizable()
                .aspectRatio(contentMode: .fill)
        }
    }
}
