//
//  IconGeneratorView.swift
//  CasinoKit
//
//  Development tool to generate and export app icon images.
//  Run this view, tap the button, then find the icons in the Files app.
//

import SwiftUI

/// A development view that generates and saves app icon images.
/// After running, find the icons in Files app → On My iPhone → [App Name]
public struct IconGeneratorView: View {
    let config: AppIconConfig
    let appName: String
    
    @State private var status: String = "Tap the button to generate the icon"
    @State private var isGenerating = false
    @State private var generatedIcon: GeneratedIconInfo?
    
    // Development view: fixed sizes acceptable
    private let previewSize: CGFloat = 200
    private let iconCornerRadiusRatio: CGFloat = 0.22
    
    /// Creates a new icon generator view.
    /// - Parameters:
    ///   - config: The app icon configuration to use for rendering.
    ///   - appName: The app name for display in instructions (e.g., "Blackjack", "Baccarat").
    public init(config: AppIconConfig, appName: String) {
        self.config = config
        self.appName = appName
    }
    
    public var body: some View {
        NavigationStack {
            ScrollView {
                VStack(spacing: 24) {
                    // Preview
                    AppIconView(config: config, size: previewSize)
                        .clipShape(.rect(cornerRadius: previewSize * iconCornerRadiusRatio))
                        .shadow(radius: 10)
                    
                    Text("App Icon Preview")
                        .font(.headline)
                    
                    // Generate button
                    Button {
                        Task {
                            await generateIcon()
                        }
                    } label: {
                        HStack {
                            if isGenerating {
                                ProgressView()
                                    .tint(.white)
                            }
                            Text(isGenerating ? "Generating..." : "Generate & Save Icon")
                        }
                        .font(.headline)
                        .foregroundStyle(.white)
                        .frame(maxWidth: .infinity)
                        .padding()
                        .background(isGenerating ? Color.gray : Color.blue)
                        .clipShape(.rect(cornerRadius: 12))
                    }
                    .disabled(isGenerating)
                    .padding(.horizontal)
                    
                    // Status
                    Text(status)
                        .font(.callout)
                        .foregroundStyle(.secondary)
                        .multilineTextAlignment(.center)
                        .padding(.horizontal)
                    
                    // Generated icon confirmation
                    if let icon = generatedIcon {
                        HStack {
                            Image(systemName: "checkmark.circle.fill")
                                .foregroundStyle(.green)
                            Text(icon.filename)
                                .font(.callout.monospaced())
                            Spacer()
                            Text("\(Int(icon.size))px")
                                .font(.callout)
                                .foregroundStyle(.secondary)
                        }
                        .padding()
                        .background(Color.green.opacity(0.1))
                        .clipShape(.rect(cornerRadius: 12))
                        .padding(.horizontal)
                    }
                    
                    // Instructions
                    instructionsSection
                }
                .padding(.vertical)
            }
            .navigationTitle("Icon Generator")
        }
    }
    
    private var instructionsSection: some View {
        VStack(alignment: .leading, spacing: 12) {
            Text("After generating:")
                .font(.headline)
            
            VStack(alignment: .leading, spacing: 8) {
                instructionRow(number: 1, text: "Open Files app on your device/simulator")
                instructionRow(number: 2, text: "Navigate to: On My iPhone → \(appName)")
                instructionRow(number: 3, text: "Find AppIcon.png (1024×1024)")
                instructionRow(number: 4, text: "AirDrop or share to your Mac")
                instructionRow(number: 5, text: "Drag into Xcode's Assets.xcassets/AppIcon")
            }
            
            Divider()
            
            Text("Note: iOS uses a single 1024px icon")
                .font(.subheadline.bold())
            Text("Xcode automatically generates all required sizes from the 1024px source.")
                .font(.caption)
                .foregroundStyle(.secondary)
        }
        .padding()
        .background(Color.gray.opacity(0.1))
        .clipShape(.rect(cornerRadius: 12))
        .padding(.horizontal)
    }
    
    private func instructionRow(number: Int, text: String) -> some View {
        HStack(alignment: .top, spacing: 8) {
            Text("\(number).")
                .font(.callout.bold())
                .foregroundStyle(.blue)
            Text(text)
                .font(.callout)
        }
    }
    
    @MainActor
    private func generateIcon() async {
        isGenerating = true
        generatedIcon = nil
        status = "Generating icon..."
        
        let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        
        // Render the 1024px icon (the only size needed for modern iOS)
        let view = AppIconView(config: config, size: 1024)
        let renderer = ImageRenderer(content: view)
        renderer.scale = 1.0
        
        if let uiImage = renderer.uiImage,
           let data = uiImage.pngData() {
            let filename = "AppIcon.png"
            let fileURL = documentsPath.appending(path: filename)
            
            do {
                try data.write(to: fileURL)
                generatedIcon = GeneratedIconInfo(filename: filename, size: 1024)
                status = "✅ Icon saved to Documents folder!\nOpen Files app to find it."
            } catch {
                status = "Error saving icon: \(error.localizedDescription)"
            }
        } else {
            status = "⚠️ Failed to render icon"
        }
        
        isGenerating = false
    }
}

/// Information about a generated icon file.
public struct GeneratedIconInfo: Identifiable, Sendable {
    public let id = UUID()
    public let filename: String
    public let size: CGFloat
    
    public init(filename: String, size: CGFloat) {
        self.filename = filename
        self.size = size
    }
}

#Preview {
    IconGeneratorView(config: .example, appName: "Casino")
}
