import SwiftUI
import AppKit

// MARK: - Chess Position View Components

struct ChessPieceView: View {
    let piece: ChessPiece
    
    var body: some View {
        Text(pieceSymbol)
            .font(.system(size: 24, weight: .bold))
            .foregroundColor(piece.color == .white ? .white : .black)
    }
    
    private var pieceSymbol: String {
        switch piece.type {
        case .pawn: return "♟"
        case .knight: return "♞"
        case .bishop: return "♝"
        case .rook: return "♜"
        case .queen: return "♛"
        case .king: return "♚"
        }
    }
}

struct ChessboardSquareView: View {
    let isLightSquare: Bool
    let piece: ChessPiece?
    
    var body: some View {
        ZStack {
            Rectangle()
                .fill(isLightSquare ? Color.white : Color.gray)
                .frame(width: 40, height: 40)
            
            if let piece = piece {
                ChessPieceView(piece: piece)
            }
        }
    }
}

struct ChessboardView: View {
    let position: ChessPosition?
    
    var body: some View {
        VStack(spacing: 0) {
            ForEach((0..<8).reversed(), id: \.self) { rank in
                HStack(spacing: 0) {
                    ForEach(0..<8, id: \.self) { file in
                        let boardPosition = BoardPosition(file: file, rank: rank)
                        ChessboardSquareView(
                            isLightSquare: (rank + file) % 2 == 0,
                            piece: position?[boardPosition]
                        )
                    }
                }
            }
        }
        .border(Color.black, width: 1)
    }
}

struct AnalysisStatusView: View {
    let isAnalyzing: Bool
    let confidence: Double
    
    var body: some View {
        VStack(spacing: 8) {
            if isAnalyzing {
                ProgressView("Analyzing position...")
            } else {
                Text("Recognition Confidence: \(Int(confidence * 100))%")
                    .foregroundColor(confidence > 0.7 ? .green : .orange)
            }
        }
        .padding()
    }
}

class CustomNSView: NSView {
    private static let invisibleCursor: NSCursor = {
        let image = NSImage(size: NSSize(width: 1, height: 1))
        image.lockFocus()
        NSColor.clear.set()
        NSRect(x: 0, y: 0, width: 1, height: 1).fill()
        image.unlockFocus()
        return NSCursor(image: image, hotSpot: .zero)
    }()
    
    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        setupView()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupView()
    }
    
    private func setupView() {
        wantsLayer = true
        layer?.backgroundColor = NSColor.clear.cgColor
    }
    
    override func resetCursorRects() {
        super.resetCursorRects()
        addCursorRect(bounds, cursor: Self.invisibleCursor)
    }
}

struct HiddenCursorView: NSViewRepresentable {
    func makeNSView(context: Context) -> CustomNSView {
        let view = CustomNSView()
        view.wantsLayer = true
        return view
    }
    
    func updateNSView(_ nsView: CustomNSView, context: Context) {
        nsView.setFrameSize(nsView.frame.size)
    }
}

struct CaptureStatusButton: View {
    let isCapturing: Bool
    let isBoardDetected: Bool
    
    var body: some View {
        HStack {
            Circle()
                .fill(statusColor)
                .frame(width: 12, height: 12)
            Text(statusText)
                .foregroundColor(statusColor)
        }
        .padding()
        .background(
            RoundedRectangle(cornerRadius: 8)
                .stroke(statusColor, lineWidth: 2)
        )
    }
    
    private var statusColor: Color {
        if isCapturing && isBoardDetected {
            return .green
        } else if isCapturing {
            return .yellow
        } else {
            return .gray
        }
    }
    
    private var statusText: String {
        if isCapturing && isBoardDetected {
            return "Capturing"
        } else if isCapturing {
            return "Waiting for board"
        } else {
            return "Not capturing"
        }
    }
}

struct CaptureView: View {
    @ObservedObject var viewModel: ScreenCaptureViewModel
    
    var body: some View {
        HStack {
            VStack {
                Text("Full Capture")
                if let image = viewModel.capturedImage {
                    Image(nsImage: image)
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(maxWidth: 400)
                } else {
                    Text("No capture available")
                        .foregroundColor(.gray)
                }
            }
            
            Divider()
            
            VStack {
                Text("Chessboard Preview")
                if let image = viewModel.croppedBoardImage {
                    Image(nsImage: image)
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(maxWidth: 400)
                        .overlay(
                            HiddenCursorView()
                                .allowsHitTesting(true)
                        )
                } else {
                    Text("No board detected")
                        .foregroundColor(.gray)
                }
                
                if viewModel.snapshotTaken {
                    Divider()
                        .padding(.vertical)
                    
                    Text("Latest Snapshot")
                    if let snapshot = viewModel.latestSnapshot {
                        Image(nsImage: snapshot)
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .frame(maxWidth: 400)
                            .padding()
                            .background(Color.black.opacity(0.1))
                            .cornerRadius(8)
                    }
                }
            }
        }
        .padding()
    }
}

struct AnalysisView: View {
    @ObservedObject var viewModel: ScreenCaptureViewModel
    
    var body: some View {
        VStack {
            if let position = viewModel.currentPosition {
                HStack(alignment: .top, spacing: 20) {
                    VStack(alignment: .leading) {
                        Text("Current Position")
                            .font(.headline)
                        ChessboardView(position: position)
                            .padding()
                            .background(Color.white)
                            .cornerRadius(8)
                            .shadow(radius: 2)
                        
                        AnalysisStatusView(
                            isAnalyzing: viewModel.isAnalyzing,
                            confidence: viewModel.recognitionConfidence
                        )
                    }
                    
                    VStack(alignment: .leading) {
                        Text("Position Details")
                            .font(.headline)
                        Text("FEN: \(position.fen)")
                            .font(.system(.body, design: .monospaced))
                            .padding(.vertical)
                        
                        if viewModel.captureError == .recognitionFailed {
                            Text("Recognition Error")
                                .foregroundColor(.red)
                                .padding()
                        }
                    }
                    .padding()
                    .background(Color.gray.opacity(0.1))
                    .cornerRadius(8)
                }
            } else {
                Text("No position detected")
                    .foregroundColor(.gray)
            }
            
            Spacer()
        }
        .padding()
    }
}

struct ContentView: View {
    @StateObject private var viewModel = ScreenCaptureViewModel()
    @State private var selectedTab = 0
    
    var body: some View {
        VStack {
            // Status and Scan controls
            HStack {
                CaptureStatusButton(
                    isCapturing: viewModel.isCapturing,
                    isBoardDetected: viewModel.isBoardDetected
                )
                
                Button(action: {
                    Task {
                        await viewModel.takeSnapshot()
                    }
                }) {
                    Text("Scan")
                        .foregroundColor(.white)
                        .padding(.horizontal, 20)
                        .padding(.vertical, 10)
                }
                .buttonStyle(.borderedProminent)
                .disabled(!viewModel.isCapturing || !viewModel.isBoardDetected)
            }
            .onAppear {
                viewModel.startMonitoring()
            }
            .onDisappear {
                viewModel.stopMonitoring()
            }
            
            // Error display
            if let error = viewModel.captureError {
                Text(error.localizedDescription)
                    .foregroundColor(.red)
                    .padding()
            }
            
            // Main content area with tabs
            TabView(selection: $selectedTab) {
                CaptureView(viewModel: viewModel)
                    .tabItem {
                        Label("Capture", systemImage: "camera")
                    }
                    .tag(0)
                
                AnalysisView(viewModel: viewModel)
                    .tabItem {
                        Label("Analysis", systemImage: "magnifyingglass")
                    }
                    .tag(1)
            }
        }
        .frame(minWidth: 1000, minHeight: 700)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
