<?php

declare(strict_types=1);

namespace App\Filament\Widgets\Supervisor;

use App\Services\CollectorVisibilityResolver;
use App\Services\Metrics\CollectionMetricsService;
use Carbon\Carbon;
use Filament\Widgets\ChartWidget;
use Illuminate\Support\Facades\Auth;

/**
 * Gráfico de tendencia de cobros del equipo.
 *
 * Muestra los cobros diarios de la última semana.
 */
class TeamCollectionTrendChart extends ChartWidget
{
    protected ?string $heading = 'Cobros del Equipo (Última Semana)';

    protected ?string $pollingInterval = '300s';

    protected static ?int $sort = 3;

    protected int|string|array $columnSpan = 'half';

    /**
     * Solo visible para Supervisores.
     */
    public static function canView(): bool
    {
        $user = Auth::user();

        return $user && $user->hasRole('supervisor') && ! $user->isSuperAdmin();
    }

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

    protected function getData(): array
    {
        $user = Auth::user();
        $companyId = $user->company_id;

        $service = app(CollectionMetricsService::class);

        // Visibilidad supervisor→cobrador (#71): scope de la tendencia al equipo visible.
        $collectorIds = app(CollectorVisibilityResolver::class)->visibleCollectorIds($user);
        $trend = $service->getTeamCollectionTrend($companyId, 7, $collectorIds);

        $labels = $trend->map(function ($item) {
            return Carbon::parse($item['date'])->translatedFormat('D d');
        })->toArray();

        $amounts = $trend->pluck('amount')->toArray();
        $counts = $trend->pluck('count')->toArray();

        return [
            'datasets' => [
                [
                    'label' => 'Monto Cobrado',
                    'data' => $amounts,
                    'backgroundColor' => '#10b981',
                    'borderRadius' => 4,
                    'yAxisID' => 'y',
                ],
                [
                    'label' => '# Pagos',
                    'data' => $counts,
                    'type' => 'line',
                    'borderColor' => '#3b82f6',
                    'backgroundColor' => 'transparent',
                    'tension' => 0.3,
                    'pointRadius' => 4,
                    'yAxisID' => 'y1',
                ],
            ],
            'labels' => $labels,
        ];
    }

    protected function getOptions(): array
    {
        return [
            'plugins' => [
                'legend' => [
                    'display' => true,
                    'position' => 'top',
                ],
                'tooltip' => [
                    'callbacks' => [
                        'label' => "function(context) {
                            if (context.dataset.label === 'Monto Cobrado') {
                                const value = context.raw;
                                return 'Cobrado: $' + value.toLocaleString('es-CO');
                            }
                            return '# Pagos: ' + context.raw;
                        }",
                    ],
                ],
            ],
            'scales' => [
                'y' => [
                    'type' => 'linear',
                    'position' => 'left',
                    'beginAtZero' => true,
                    'ticks' => [
                        'callback' => "function(value) {
                            return '$' + value.toLocaleString('es-CO');
                        }",
                    ],
                ],
                'y1' => [
                    'type' => 'linear',
                    'position' => 'right',
                    'beginAtZero' => true,
                    'grid' => [
                        'drawOnChartArea' => false,
                    ],
                    'ticks' => [
                        'stepSize' => 1,
                    ],
                ],
            ],
        ];
    }
}
