<?php

namespace App\Filament\Widgets;

use App\Models\Payment;
use Carbon\CarbonImmutable;
use Filament\Support\RawJs;
use Filament\Widgets\ChartWidget;

class RevenueTrendChart extends ChartWidget
{
    protected static bool $isLazy = false;

    protected static ?int $sort = 3;

    protected ?string $heading = 'Payment revenue';

    protected ?string $description = 'Verified payment amount by day.';

    protected string $color = 'success';

    protected int|string|array $columnSpan = 1;

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

    /**
     * @return array<string, mixed>
     */
    protected function getData(): array
    {
        $start = CarbonImmutable::now()->subDays(13)->startOfDay();
        $dates = collect(range(0, 13))->map(fn (int $offset): CarbonImmutable => $start->addDays($offset));

        return [
            'datasets' => [
                [
                    'label' => (string) setting('payment.default_currency', 'INR'),
                    'data' => $dates
                        ->map(fn (CarbonImmutable $date): float => Payment::query()
                            ->whereDate('verified_at', $date)
                            ->sum('amount_paise') / 100)
                        ->all(),
                    'backgroundColor' => 'rgba(16, 185, 129, 0.72)',
                    'borderColor' => '#059669',
                    'borderRadius' => 8,
                    'borderSkipped' => false,
                ],
            ],
            'labels' => $dates->map(fn (CarbonImmutable $date): string => $date->format('j M'))->all(),
        ];
    }

    /**
     * @return array<string, mixed>|RawJs|null
     */
    protected function getOptions(): array|RawJs|null
    {
        return [
            'plugins' => [
                'legend' => [
                    'display' => false,
                ],
            ],
            'scales' => [
                'x' => [
                    'grid' => [
                        'display' => false,
                    ],
                ],
                'y' => [
                    'beginAtZero' => true,
                ],
            ],
        ];
    }
}
