<?php

namespace App\Filament\Widgets;

use App\Models\Bet;
use Filament\Widgets\ChartWidget;
use Illuminate\Support\Carbon;

class BetsChartWidget extends ChartWidget
{
    protected static ?int $sort = 4;
    protected ?string $heading = 'Bets Won vs Lost — Daily';
    protected int | string | array $columnSpan = 'full';

    public ?string $filter = '14';

    protected function getFilters(): ?array
    {
        return [
            '7'  => 'Last 7 days',
            '14' => 'Last 14 days',
            '30' => 'Last 30 days',
        ];
    }

    protected function getData(): array
    {
        $days  = (int) ($this->filter ?? 14);
        $start = Carbon::now()->subDays($days - 1)->startOfDay();

        $won  = Bet::where('status', 'won')->where('created_at', '>=', $start)
            ->get()->groupBy(fn($b) => $b->created_at->format('M d'));

        $lost = Bet::where('status', 'lost')->where('created_at', '>=', $start)
            ->get()->groupBy(fn($b) => $b->created_at->format('M d'));

        $labels   = [];
        $wonData  = [];
        $lostData = [];

        for ($i = $days - 1; $i >= 0; $i--) {
            $label      = Carbon::now()->subDays($i)->format('M d');
            $labels[]   = $label;
            $wonData[]  = $won->get($label, collect())->count();
            $lostData[] = $lost->get($label, collect())->count();
        }

        return [
            'datasets' => [
                [
                    'label'           => 'Won',
                    'data'            => $wonData,
                    'backgroundColor' => '#10b981',
                ],
                [
                    'label'           => 'Lost',
                    'data'            => $lostData,
                    'backgroundColor' => '#ef4444',
                ],
            ],
            'labels' => $labels,
        ];
    }

    protected function getType(): string
    {
        return 'bar';
    }
}
