<?php

namespace App\Filament\Widgets;

use App\Models\Bet;
use App\Models\Transaction;
use App\Models\User;
use Filament\Widgets\StatsOverviewWidget as BaseWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
use Illuminate\Support\Carbon;

class CasinoStatsOverview extends BaseWidget
{
    protected static ?int $sort = 1;
    protected ?string $pollingInterval = '30s';

    protected function getStats(): array
    {
        $today     = today();
        $yesterday = Carbon::yesterday();
        $thisMonth = Carbon::now()->startOfMonth();

        // Players
        $totalUsers    = User::count();
        $newToday      = User::whereDate('created_at', $today)->count();
        $newYesterday  = User::whereDate('created_at', $yesterday)->count();
        $activePlayers = User::where('is_active', true)->whereHas('bets')->count();

        // Bets
        $totalBets    = Bet::count();
        $todayBets    = Bet::whereDate('created_at', $today)->count();
        $yesterdayBets = Bet::whereDate('created_at', $yesterday)->count();
        $pendingBets  = Bet::where('status', 'pending')->count();
        $wonBets      = Bet::where('status', 'won')->count();
        $lostBets     = Bet::where('status', 'lost')->count();
        $winRate      = $totalBets > 0 ? round(($wonBets / $totalBets) * 100, 1) : 0;

        // Finance
        $totalDeposits   = Transaction::where('type', 'deposit')->where('status', 'completed')->sum('amount');
        $monthDeposits   = Transaction::where('type', 'deposit')->where('status', 'completed')->where('created_at', '>=', $thisMonth)->sum('amount');
        $todayDeposits   = Transaction::where('type', 'deposit')->where('status', 'completed')->whereDate('created_at', $today)->sum('amount');
        $totalWithdrawals = Transaction::where('type', 'withdrawal')->where('status', 'completed')->sum('amount');
        $pendingWithdrawals = Transaction::where('type', 'withdrawal')->where('status', 'pending')->count();
        $totalPayouts    = Bet::where('status', 'won')->sum('actual_payout');
        $totalStaked     = Bet::whereIn('status', ['won', 'lost'])->sum('stake');
        $netRevenue      = $totalStaked - $totalPayouts;
        $todayRevenue    = Bet::whereDate('created_at', $today)->whereIn('status', ['won','lost'])->sum('stake')
                         - Bet::whereDate('created_at', $today)->where('status', 'won')->sum('actual_payout');

        // Trend helpers
        $regTrend   = $newYesterday > 0 ? round((($newToday - $newYesterday) / $newYesterday) * 100, 1) : 0;
        $betTrend   = $yesterdayBets > 0 ? round((($todayBets - $yesterdayBets) / $yesterdayBets) * 100, 1) : 0;

        return [
            Stat::make('Total Players', number_format($totalUsers))
                ->description($newToday . ' new today' . ($regTrend >= 0 ? ' ▲' : ' ▼') . abs($regTrend) . '%')
                ->descriptionIcon('heroicon-m-user-plus')
                ->chart(User::selectRaw('DATE(created_at) as day, COUNT(*) as count')
                    ->where('created_at', '>=', Carbon::now()->subDays(7))
                    ->groupBy('day')->pluck('count')->toArray())
                ->color('success'),

            Stat::make('Active Players', number_format($activePlayers))
                ->description('With at least 1 bet')
                ->descriptionIcon('heroicon-m-users')
                ->color('info'),

            Stat::make('Total Bets', number_format($totalBets))
                ->description($todayBets . ' today' . ($betTrend >= 0 ? ' ▲' : ' ▼') . abs($betTrend) . '%')
                ->descriptionIcon('heroicon-m-ticket')
                ->chart(Bet::selectRaw('DATE(created_at) as day, COUNT(*) as count')
                    ->where('created_at', '>=', Carbon::now()->subDays(7))
                    ->groupBy('day')->pluck('count')->toArray())
                ->color('primary'),

            Stat::make('Pending Bets', number_format($pendingBets))
                ->description($winRate . '% overall win rate')
                ->descriptionIcon('heroicon-m-clock')
                ->color($pendingBets > 0 ? 'warning' : 'success'),

            Stat::make('Total Deposits', '$' . number_format($totalDeposits, 2))
                ->description('$' . number_format($todayDeposits, 2) . ' today · $' . number_format($monthDeposits, 2) . ' this month')
                ->descriptionIcon('heroicon-m-arrow-trending-up')
                ->color('success'),

            Stat::make('Pending Withdrawals', number_format($pendingWithdrawals))
                ->description('$' . number_format($totalWithdrawals, 2) . ' paid out total')
                ->descriptionIcon('heroicon-m-arrow-trending-down')
                ->color($pendingWithdrawals > 0 ? 'warning' : 'gray'),

            Stat::make('Total Staked', '$' . number_format($totalStaked, 2))
                ->description('By all players across all bets')
                ->descriptionIcon('heroicon-m-currency-dollar')
                ->color('primary'),

            Stat::make('House Revenue', '$' . number_format($netRevenue, 2))
                ->description('Staked minus payouts · $' . number_format($todayRevenue, 2) . ' today')
                ->descriptionIcon('heroicon-m-building-library')
                ->color($netRevenue >= 0 ? 'success' : 'danger'),
        ];
    }
}
