<?php

namespace App\Filament\Widgets;

use Filament\Widgets\ChartWidget;
use App\Models\Transaction;
use Illuminate\Support\Facades\DB;

class GatewayStatistics extends ChartWidget
{
    protected static ?int $sort = 3;
    protected ?string $heading = 'Gateway Volume Share';
    protected ?string $maxHeight = '220px';
    protected int | string | array $columnSpan = [
        'default' => 'full',
        'md' => 1,
        'xl' => 1,
    ];

    protected function getData(): array
    {
        $gatewayCounts = Transaction::select('gateway', DB::raw('SUM(amount) as total_volume'))
            ->whereNotNull('gateway')
            ->whereIn('status', ['SUCCESS', 'Complete', 'COMPLETED'])
            ->groupBy('gateway')
            ->orderByDesc('total_volume')
            ->limit(5)
            ->get();

        $labels = [];
        $data = [];
        $colors = [];

        $colorMap = [
            'bkash' => '#E11471',
            'bkash personal' => '#E11471',
            'nagad' => '#F37021',
            'nagad personal' => '#F37021',
            'rocket' => '#8C1561',
            'rocket personal' => '#8C1561',
            'upay' => '#0055A5',
            'binance' => '#F0B90B',
            'stripe' => '#6366F1',
            'paypal' => '#0079C1',
        ];

        foreach ($gatewayCounts as $gw) {
            $name = $gw->gateway ?: 'Other';
            $labels[] = strtoupper($name);
            $data[] = (float) $gw->total_volume;

            $lower = strtolower($name);
            $colors[] = $colorMap[$lower] ?? '#10B981';
        }

        if (empty($data)) {
            $labels = ['No Data Yet'];
            $data = [1];
            $colors = ['#374151'];
        }

        return [
            'datasets' => [
                [
                    'label' => 'Volume (' . setting('currency_symbol', '৳') . ')',
                    'data' => $data,
                    'backgroundColor' => $colors,
                    'borderWidth' => 0,
                    'hoverOffset' => 4,
                ],
            ],
            'labels' => $labels,
        ];
    }

    protected function getOptions(): array
    {
        return [
            'cutout' => '72%',
            'maintainAspectRatio' => false,
            'plugins' => [
                'legend' => [
                    'display' => true,
                    'position' => 'bottom',
                    'labels' => [
                        'boxWidth' => 8,
                        'boxHeight' => 8,
                        'usePointStyle' => true,
                        'pointStyle' => 'circle',
                        'padding' => 8,
                        'font' => [
                            'size' => 10,
                            'weight' => '600',
                        ],
                    ],
                ],
            ],
        ];
    }

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