//
//  StatisticsSheetView.swift
//  Blackjack
//
//  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: BlackjackSession?
    
    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) {
                state.endSessionAndStartNew()
                dismiss()
            }
            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),
                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)
        } else {
            NoActiveSessionView()
        }
    }
    
    // MARK: - Global Stats Content
    
    private var globalStatsContent: some View {
        let stats = state.aggregatedStats
        let gameStats = state.aggregatedBlackjackStats
        
        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")
                        )
                    }
                }
            }
            
            // Blackjack-specific stats
            SheetSection(title: String(localized: "GAME STATS"), icon: "suit.spade.fill") {
                VStack(spacing: Design.Spacing.medium) {
                    ForEach(gameStats.displayItems) { item in
                        GameStatRow(item: item)
                    }
                }
            }
            
            // 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: BlackjackSession) -> some View {
        // Game stats section
        SheetSection(title: String(localized: "IN GAME STATS"), icon: "gamecontroller.fill") {
            VStack(spacing: Design.Spacing.large) {
                // Hands played
                VStack(spacing: Design.Spacing.xSmall) {
                    Text(String(localized: "Hands 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 Blackjack-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)
                }
            }
        }
        
        // 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: - Helpers
    
    private func styleDisplayName(for rawValue: String) -> String {
        BlackjackStyle(rawValue: rawValue)?.displayName ?? rawValue.capitalized
    }
}

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

// MARK: - Session Detail View

private struct SessionDetailView: View {
    let session: BlackjackSession
    let styleDisplayName: String
    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) {
                        // Hands played
                        VStack(spacing: Design.Spacing.xSmall) {
                            Text(String(localized: "Hands 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))
                        
                        // Blackjack-specific stats
                        ForEach(session.gameStats.displayItems) { item in
                            GameStatRow(item: item)
                        }
                    }
                }
                
                // 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
                    )
                }
                
                // 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: - Preview

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