//
//  StatisticsSheetView.swift
//  Baccarat
//
//  Game statistics with session history and per-style stats.
//

import SwiftUI
import CasinoKit

struct StatisticsSheetView: View {
    @Bindable var state: GameState
    
    @Environment(\.dismiss) private var dismiss
    @State private var selectedTab: StatisticsTab = .current
    @State private var selectedSession: BaccaratSession?
    
    var body: some View {
        SheetContainerView(
            title: String(localized: "Statistics"),
            content: {
                // Tab selector (from CasinoKit)
                StatisticsTabSelector(selectedTab: $selectedTab)
                
                // Content based on selected tab
                switch selectedTab {
                case .current:
                    currentSessionContent
                case .global:
                    globalStatsContent
                case .history:
                    sessionHistoryContent
                }
            },
            onCancel: nil,
            onDone: { dismiss() },
            doneButtonText: String(localized: "Done")
        )
        .confirmationDialog(
            String(localized: "End Session?"),
            isPresented: $state.showEndSessionConfirmation,
            titleVisibility: .visible
        ) {
            Button(String(localized: "End Session"), role: .destructive) {
                // Dismiss first for responsive UI, then end session
                dismiss()
                Task { @MainActor in
                    state.endSessionAndStartNew()
                }
            }
            Button(String(localized: "Cancel"), role: .cancel) {}
        } message: {
            if let session = state.currentSession {
                Text(String(localized: "You played \(session.roundsPlayed) hands with a net result of \(SessionFormatter.formatMoney(session.netResult)). This session will be saved to your history."))
            }
        }
        .sheet(item: $selectedSession) { session in
            SessionDetailView(
                session: session,
                styleDisplayName: styleDisplayName(for: session.gameStyle),
                roundHistory: state.roundHistory(for: session),
                onDelete: {
                    state.deleteSession(id: session.id)
                    selectedSession = nil
                }
            )
        }
    }
    
    // MARK: - Tab Selector (uses CasinoKit.StatisticsTabSelector)
    
    // MARK: - Current Session Content
    
    @ViewBuilder
    private var currentSessionContent: some View {
        if let session = state.currentSession {
            // Current session header
            CurrentSessionHeader(
                duration: session.duration,
                roundsPlayed: session.roundsPlayed,
                netResult: session.netResult,
                onEndSession: {
                    state.showEndSessionConfirmation = true
                }
            )
            .padding(.horizontal)
            
            // Session stats
            sessionStatsSection(session: session)
            
            // Road displays for current session
            bigRoadSection
            roadMapSection
        } else {
            NoActiveSessionView()
        }
    }
    
    // MARK: - Global Stats Content
    
    private var globalStatsContent: some View {
        let stats = state.aggregatedStats
        let gameStats = state.aggregatedBaccaratStats
        
        return Group {
            // Summary section
            SheetSection(title: String(localized: "ALL TIME SUMMARY"), icon: "globe") {
                VStack(spacing: Design.Spacing.large) {
                    // Sessions overview
                    HStack(spacing: Design.Spacing.large) {
                        StatColumn(
                            value: "\(stats.totalSessions)",
                            label: String(localized: "Sessions")
                        )
                        StatColumn(
                            value: "\(stats.totalRoundsPlayed)",
                            label: String(localized: "Hands")
                        )
                        StatColumn(
                            value: SessionFormatter.formatPercent(stats.winRate),
                            label: String(localized: "Win Rate"),
                            valueColor: stats.winRate >= 50 ? .green : .orange
                        )
                    }
                    
                    Divider().background(Color.white.opacity(Design.Opacity.hint))
                    
                    // Financial summary
                    HStack(spacing: Design.Spacing.large) {
                        StatColumn(
                            value: SessionFormatter.formatMoney(stats.totalWinnings),
                            label: String(localized: "Net"),
                            valueColor: stats.totalWinnings >= 0 ? .green : .red
                        )
                        StatColumn(
                            value: SessionFormatter.formatDuration(stats.totalPlayTime),
                            label: String(localized: "Time")
                        )
                    }
                }
            }
            
            // Baccarat-specific stats
            SheetSection(title: String(localized: "GAME STATS"), icon: "suit.diamond.fill") {
                VStack(spacing: Design.Spacing.medium) {
                    ForEach(gameStats.displayItems) { item in
                        GameStatRow(item: item)
                    }
                    
                    Divider().background(Color.white.opacity(Design.Opacity.hint))
                    
                    // Win distribution
                    HStack(spacing: Design.Spacing.large) {
                        WinStatCompact(
                            label: String(localized: "Player"),
                            count: gameStats.playerWins,
                            color: .blue
                        )
                        WinStatCompact(
                            label: String(localized: "Banker"),
                            count: gameStats.bankerWins,
                            color: .red
                        )
                        WinStatCompact(
                            label: String(localized: "Tie"),
                            count: gameStats.ties,
                            color: .green
                        )
                    }
                }
            }
            
            // Session performance (from CasinoKit)
            SheetSection(title: String(localized: "SESSION PERFORMANCE"), icon: "chart.bar.fill") {
                SessionPerformanceSection(
                    winningSessions: stats.winningSessions,
                    losingSessions: stats.losingSessions,
                    bestSession: stats.bestSession,
                    worstSession: stats.worstSession
                )
            }
        }
    }
    
    // MARK: - Session History Content
    
    private var sessionHistoryContent: some View {
        Group {
            if state.sessionHistory.isEmpty && state.currentSession == nil {
                EmptyHistoryView()
            } else {
                LazyVStack(spacing: Design.Spacing.medium) {
                    // Current session at top if exists (taps go to Current tab)
                    if let current = state.currentSession {
                        Button {
                            withAnimation {
                                selectedTab = .current
                            }
                        } label: {
                            SessionSummaryRow(
                                styleDisplayName: styleDisplayName(for: current.gameStyle),
                                duration: current.duration,
                                roundsPlayed: current.roundsPlayed,
                                netResult: current.netResult,
                                startTime: current.startTime,
                                isActive: true,
                                endReason: nil
                            )
                        }
                        .buttonStyle(.plain)
                    }
                    
                    // Historical sessions - tap to view details, swipe to delete
                    ForEach(state.sessionHistory) { session in
                        Button {
                            selectedSession = session
                        } label: {
                            HStack {
                                SessionSummaryRow(
                                    styleDisplayName: styleDisplayName(for: session.gameStyle),
                                    duration: session.duration,
                                    roundsPlayed: session.roundsPlayed,
                                    netResult: session.netResult,
                                    startTime: session.startTime,
                                    isActive: false,
                                    endReason: session.endReason
                                )
                                
                                Image(systemName: "chevron.right")
                                    .font(.system(size: Design.BaseFontSize.small, weight: .semibold))
                                    .foregroundStyle(.white.opacity(Design.Opacity.light))
                            }
                        }
                        .buttonStyle(.plain)
                        .swipeActions(edge: .trailing, allowsFullSwipe: true) {
                            Button(role: .destructive) {
                                withAnimation {
                                    state.deleteSession(id: session.id)
                                }
                            } label: {
                                Label(String(localized: "Delete"), systemImage: "trash")
                            }
                        }
                    }
                }
                .padding(.horizontal)
            }
        }
    }
    
    
    // MARK: - Session Stats Section
    
    @ViewBuilder
    private func sessionStatsSection(session: BaccaratSession) -> some View {
        // Game stats section
        SheetSection(title: String(localized: "GAME STATS"), icon: "gamecontroller.fill") {
            VStack(spacing: Design.Spacing.large) {
                // Rounds played
                VStack(spacing: Design.Spacing.xSmall) {
                    Text(String(localized: "Rounds played"))
                        .font(.system(size: Design.BaseFontSize.body))
                        .foregroundStyle(.white.opacity(Design.Opacity.strong))
                    Text("\(session.roundsPlayed)")
                        .font(.system(size: Design.BaseFontSize.xxLarge, weight: .bold, design: .rounded))
                        .foregroundStyle(.white)
                }
                
                // Win/Loss/Push
                HStack(spacing: Design.Spacing.medium) {
                    OutcomeCircle(label: String(localized: "Won"), count: session.wins, color: .white)
                    OutcomeCircle(label: String(localized: "Lost"), count: session.losses, color: .red)
                    OutcomeCircle(label: String(localized: "Push"), count: session.pushes, color: .gray)
                }
                
                Divider().background(Color.white.opacity(Design.Opacity.hint))
                
                // Game time and Baccarat-specific stats
                StatRow(icon: "clock", label: String(localized: "Total game time"), value: SessionFormatter.formatDuration(session.duration))
                
                ForEach(session.gameStats.displayItems) { item in
                    GameStatRow(item: item)
                }
                
                Divider().background(Color.white.opacity(Design.Opacity.hint))
                
                // Win distribution
                HStack(spacing: Design.Spacing.large) {
                    WinStatCompact(
                        label: String(localized: "Player"),
                        count: session.gameStats.playerWins,
                        color: .blue
                    )
                    WinStatCompact(
                        label: String(localized: "Banker"),
                        count: session.gameStats.bankerWins,
                        color: .red
                    )
                    WinStatCompact(
                        label: String(localized: "Tie"),
                        count: session.gameStats.ties,
                        color: .green
                    )
                }
            }
        }
        
        // Chips stats section (from CasinoKit)
        SheetSection(title: String(localized: "CHIPS STATS"), icon: "dollarsign.circle.fill") {
            ChipsStatsSection(
                totalWinnings: session.totalWinnings,
                biggestWin: session.biggestWin,
                biggestLoss: session.biggestLoss,
                totalBetAmount: session.totalBetAmount,
                averageBet: session.roundsPlayed > 0 ? session.averageBet : nil,
                biggestBet: session.biggestBet
            )
        }
    }
    
    // MARK: - Road Sections
    
    private var bigRoadSection: some View {
        SheetSection(title: String(localized: "BIG ROAD"), icon: "chart.bar.xaxis") {
            if state.roundHistory.isEmpty {
                emptyRoadPlaceholder
            } else {
                BigRoadView(results: state.roundHistory)
                    .frame(height: Size.bigRoadHeight)
            }
        }
    }
    
    private var roadMapSection: some View {
        SheetSection(title: String(localized: "HISTORY"), icon: "clock.arrow.circlepath") {
            if state.roundHistory.isEmpty {
                emptyRoadPlaceholder
            } else {
                // Horizontal display matching what's shown during gameplay
                ScrollView(.horizontal) {
                    HStack(spacing: Design.Spacing.xSmall) {
                        ForEach(state.roundHistory) { result in
                            RoadDot(
                                result: result.result,
                                dotSize: Size.roadDotSize,
                                hasPair: result.hasPair,
                                isNatural: result.isNatural
                            )
                        }
                    }
                    .padding(.vertical, Design.Spacing.xSmall)
                }
                .scrollIndicators(.hidden)
            }
        }
    }
    
    private var emptyRoadPlaceholder: some View {
        Text(String(localized: "No rounds played yet"))
            .font(.system(size: Design.BaseFontSize.body))
            .foregroundStyle(.white.opacity(Design.Opacity.medium))
            .frame(maxWidth: .infinity)
            .padding(.vertical, Design.Spacing.xLarge)
    }
    
    // MARK: - Helpers
    
    private func styleDisplayName(for rawValue: String) -> String {
        // Return the deck count display name
        DeckCount(rawValue: Int(rawValue) ?? 8)?.displayName ?? rawValue
    }
}

// MARK: - Statistics Tab & Supporting Views
// StatisticsTab, StatColumn, OutcomeCircle, StatRow, ChipStatRow are now provided by CasinoKit

// MARK: - Baccarat-Specific Views

/// Compact win distribution indicator for Player/Banker/Tie.
private struct WinStatCompact: View {
    let label: String
    let count: Int
    let color: Color
    
    private let indicatorSize: CGFloat = 24
    
    var body: some View {
        VStack(spacing: CasinoDesign.Spacing.xSmall) {
            Circle()
                .fill(color)
                .frame(width: indicatorSize, height: indicatorSize)
            
            Text("\(count)")
                .font(.system(size: CasinoDesign.BaseFontSize.large, weight: .bold))
                .foregroundStyle(.white)
            
            Text(label)
                .font(.system(size: CasinoDesign.BaseFontSize.small))
                .foregroundStyle(color)
        }
        .frame(maxWidth: .infinity)
    }
}

// MARK: - Session Detail View

private struct SessionDetailView: View {
    let session: BaccaratSession
    let styleDisplayName: String
    let roundHistory: [RoundResult]
    let onDelete: () -> Void
    
    @Environment(\.dismiss) private var dismiss
    @State private var showDeleteConfirmation = false
    
    var body: some View {
        SheetContainerView(
            title: styleDisplayName,
            content: {
                // Session header info (from CasinoKit)
                SessionDetailHeader(
                    startTime: session.startTime,
                    endReason: session.endReason,
                    netResult: session.netResult,
                    winRate: session.winRate
                )
                
                // Game stats section
                SheetSection(title: String(localized: "GAME STATS"), icon: "gamecontroller.fill") {
                    VStack(spacing: Design.Spacing.large) {
                        // Rounds played
                        VStack(spacing: Design.Spacing.xSmall) {
                            Text(String(localized: "Rounds played"))
                                .font(.system(size: Design.BaseFontSize.body))
                                .foregroundStyle(.white.opacity(Design.Opacity.strong))
                            Text("\(session.roundsPlayed)")
                                .font(.system(size: Design.BaseFontSize.xxLarge, weight: .bold, design: .rounded))
                                .foregroundStyle(.white)
                        }
                        
                        // Win/Loss/Push (from CasinoKit)
                        HStack(spacing: Design.Spacing.medium) {
                            OutcomeCircle(label: String(localized: "Won"), count: session.wins, color: .white)
                            OutcomeCircle(label: String(localized: "Lost"), count: session.losses, color: .red)
                            OutcomeCircle(label: String(localized: "Push"), count: session.pushes, color: .gray)
                        }
                        
                        Divider().background(Color.white.opacity(Design.Opacity.hint))
                        
                        // Game time (from CasinoKit)
                        StatRow(icon: "clock", label: String(localized: "Total game time"), value: SessionFormatter.formatDuration(session.duration))
                        
                        // Baccarat-specific stats
                        ForEach(session.gameStats.displayItems) { item in
                            GameStatRow(item: item)
                        }
                        
                        Divider().background(Color.white.opacity(Design.Opacity.hint))
                        
                        // Win distribution (Baccarat-specific)
                        HStack(spacing: Design.Spacing.large) {
                            WinStatCompact(
                                label: String(localized: "Player"),
                                count: session.gameStats.playerWins,
                                color: .blue
                            )
                            WinStatCompact(
                                label: String(localized: "Banker"),
                                count: session.gameStats.bankerWins,
                                color: .red
                            )
                            WinStatCompact(
                                label: String(localized: "Tie"),
                                count: session.gameStats.ties,
                                color: .green
                            )
                        }
                    }
                }
                
                // Chips stats section (from CasinoKit)
                SheetSection(title: String(localized: "CHIPS STATS"), icon: "dollarsign.circle.fill") {
                    ChipsStatsSection(
                        totalWinnings: session.totalWinnings,
                        biggestWin: session.biggestWin,
                        biggestLoss: session.biggestLoss,
                        totalBetAmount: session.totalBetAmount,
                        averageBet: session.roundsPlayed > 0 ? session.averageBet : nil,
                        biggestBet: session.biggestBet
                    )
                }
                
                // Balance section (from CasinoKit)
                SheetSection(title: String(localized: "BALANCE"), icon: "banknote.fill") {
                    BalanceSection(
                        startingBalance: session.startingBalance,
                        endingBalance: session.endingBalance,
                        netResult: session.netResult
                    )
                }
                
                // Big Road section (Baccarat-specific)
                if !roundHistory.isEmpty {
                    SheetSection(title: String(localized: "BIG ROAD"), icon: "chart.bar.xaxis") {
                        BigRoadView(results: roundHistory)
                            .frame(height: Size.bigRoadHeight)
                    }
                    
                    // History road section
                    SheetSection(title: String(localized: "HISTORY"), icon: "clock.arrow.circlepath") {
                        ScrollView(.horizontal) {
                            HStack(spacing: Design.Spacing.xSmall) {
                                ForEach(roundHistory) { result in
                                    RoadDot(
                                        result: result.result,
                                        dotSize: Size.roadDotSize,
                                        hasPair: result.hasPair,
                                        isNatural: result.isNatural
                                    )
                                }
                            }
                            .padding(.vertical, Design.Spacing.xSmall)
                        }
                        .scrollIndicators(.hidden)
                    }
                }
                
                // Delete button (from CasinoKit)
                DeleteSessionButton {
                    showDeleteConfirmation = true
                }
            },
            onCancel: nil,
            onDone: { dismiss() },
            doneButtonText: String(localized: "Done")
        )
        .confirmationDialog(
            String(localized: "Delete Session?"),
            isPresented: $showDeleteConfirmation,
            titleVisibility: .visible
        ) {
            Button(String(localized: "Delete"), role: .destructive) {
                onDelete()
                dismiss()
            }
            Button(String(localized: "Cancel"), role: .cancel) {}
        } message: {
            Text(String(localized: "This will permanently remove this session from your history."))
        }
    }
}

// MARK: - Big Road View

private struct BigRoadView: View {
    let results: [RoundResult]
    
    private let maxRows = 6
    private let cellSize: CGFloat = Size.bigRoadCellSize
    
    /// Convert results into columns for Big Road display.
    private var columns: [[RoundResult]] {
        var cols: [[RoundResult]] = []
        var currentCol: [RoundResult] = []
        var lastResult: GameResult?
        
        for result in results {
            let currentResult = result.result
            
            if currentResult == .tie {
                // Ties don't start new columns
                if !currentCol.isEmpty {
                    currentCol.append(result)
                } else if !cols.isEmpty {
                    cols[cols.count - 1].append(result)
                } else {
                    currentCol.append(result)
                }
            } else if lastResult == nil || currentResult == lastResult {
                currentCol.append(result)
                lastResult = currentResult
            } else {
                if !currentCol.isEmpty {
                    cols.append(currentCol)
                }
                currentCol = [result]
                lastResult = currentResult
            }
        }
        
        if !currentCol.isEmpty {
            cols.append(currentCol)
        }
        
        return cols
    }
    
    var body: some View {
        ScrollView(.horizontal) {
            HStack(spacing: Design.Spacing.xxSmall) {
                ForEach(Array(columns.enumerated()), id: \.offset) { _, column in
                    VStack(spacing: Design.Spacing.xxSmall) {
                        ForEach(Array(column.prefix(maxRows).enumerated()), id: \.offset) { _, result in
                            BigRoadCell(result: result)
                        }
                        
                        if column.count > maxRows {
                            Text("+\(column.count - maxRows)")
                                .font(.system(size: Design.BaseFontSize.xxSmall))
                                .foregroundStyle(.white.opacity(Design.Opacity.medium))
                        }
                        
                        Spacer(minLength: 0)
                    }
                }
            }
            .padding(Design.Spacing.small)
        }
        .background(
            RoundedRectangle(cornerRadius: Design.CornerRadius.medium)
                .fill(Color.black.opacity(Design.Opacity.light))
        )
        .scrollIndicators(.hidden)
    }
}

private struct BigRoadCell: View {
    let result: RoundResult
    
    private let cellSize: CGFloat = Size.bigRoadCellSize
    
    private var color: Color {
        switch result.result {
        case .playerWins: return .blue
        case .bankerWins: return .red
        case .tie: return .green
        }
    }
    
    var body: some View {
        ZStack {
            Circle()
                .stroke(color, lineWidth: Design.LineWidth.medium)
                .frame(width: cellSize, height: cellSize)
            
            if result.hasPair {
                Circle()
                    .fill(Color.yellow)
                    .frame(width: cellSize * 0.25, height: cellSize * 0.25)
                    .offset(y: cellSize * 0.3)
            }
            
            if result.isNatural {
                Circle()
                    .fill(Color.white)
                    .frame(width: cellSize * 0.25, height: cellSize * 0.25)
                    .offset(y: -cellSize * 0.3)
            }
            
            if result.result == .tie {
                Rectangle()
                    .fill(color)
                    .frame(width: cellSize * 0.8, height: Design.LineWidth.medium)
                    .rotationEffect(.degrees(-45))
            }
        }
    }
}

// MARK: - Local Size Constants

private enum Size {
    static let outcomeCircleSize: CGFloat = 48
    static let outcomeCircleInner: CGFloat = 24
    static let statIconWidth: CGFloat = 32
    static let chipIconSize: CGFloat = 28
    static let bigRoadHeight: CGFloat = 180
    static let bigRoadCellSize: CGFloat = 24
    static let winIndicatorSize: CGFloat = 24
    static let roadDotSize: CGFloat = 28
}

// MARK: - Preview

#Preview {
    StatisticsSheetView(state: GameState(settings: GameSettings()))
}
