<?php

namespace App\Filament\Widgets;

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

class RevenueChartWidget extends ChartWidget
{
    protected static ?int $sort = 3;
    protected ?string $heading = 'Revenue vs Withdrawals — Last 30 Days';
    protected int | string | array $columnSpan = 'full';

    public ?string $filter = '30';

    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 ?? 30);
        $start = Carbon::now()->subDays($days - 1)->startOfDay();

        $deposits = Transaction::where('type', 'deposit')
            ->where('status', 'completed')
            ->where('created_at', '>=', $start)
            ->get()
            ->groupBy(fn($t) => $t->created_at->format('M d'));

        $withdrawals = Transaction::where('type', 'withdrawal')
            ->where('status', 'completed')
            ->where('created_at', '>=', $start)
            ->get()
            ->groupBy(fn($t) => $t->created_at->format('M d'));

        $labels   = [];
        $depData  = [];
        $withData = [];

        for ($i = $days - 1; $i >= 0; $i--) {
            $label      = Carbon::now()->subDays($i)->format('M d');
            $labels[]   = $label;
            $depData[]  = round($deposits->get($label, collect())->sum('amount'), 2);
            $withData[] = round($withdrawals->get($label, collect())->sum('amount'), 2);
        }

        return [
            'datasets' => [
                [
                    'label'           => 'Deposits ($)',
                    'data'            => $depData,
                    'borderColor'     => '#10b981',
                    'backgroundColor' => 'rgba(16,185,129,0.1)',
                    'fill'            => true,
                    'tension'         => 0.4,
                ],
                [
                    'label'           => 'Withdrawals ($)',
                    'data'            => $withData,
                    'borderColor'     => '#f59e0b',
                    'backgroundColor' => 'rgba(245,158,11,0.1)',
                    'fill'            => true,
                    'tension'         => 0.4,
                ],
            ],
            'labels' => $labels,
        ];
    }

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