<?php

declare(strict_types=1);

namespace App\Filament\Widgets;

use App\Business\Workbench\BusinessOverviewMetricService;
use App\Services\DberpPermissionService;
use Filament\Widgets\ChartWidget;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Facades\Auth;

class InventoryWarningDistributionChartWidget extends ChartWidget
{
    protected static bool $isLazy = true;

    protected string $view = 'filament.widgets.inventory-warning-distribution-chart-widget';

    protected ?string $pollingInterval = null;

    protected ?string $maxHeight = '280px';

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

    protected string $color = 'danger';

    public static function canView(): bool
    {
        return app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::VIEW_WORKBENCH_OVERVIEW);
    }

    public function getHeading(): string|Htmlable|null
    {
        return __('dberp.widgets.business_overview_workbench.chart_inventory_distribution_heading');
    }

    public function getDescription(): string|Htmlable|null
    {
        return __('dberp.widgets.business_overview_workbench.chart_inventory_distribution_description');
    }

    public function hasChartData(): bool
    {
        $values = $this->distributionData()['datasets'][0]['data'] ?? [];

        return array_sum(array_map(intval(...), $values)) > 0;
    }

    /**
     * @return array<string, mixed>
     */
    private function distributionData(): array
    {
        return $this->cachedDistribution ??= app(BusinessOverviewMetricService::class)->inventoryWarningDistribution();
    }

    /**
     * @var array<string, mixed>|null
     */
    private ?array $cachedDistribution = null;

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

    /**
     * @return array<string, mixed>
     */
    protected function getData(): array
    {
        return $this->distributionData();
    }

    /**
     * @return array<string, mixed>|null
     */
    protected function getOptions(): ?array
    {
        return [
            'maintainAspectRatio' => false,
            'plugins' => [
                'legend' => [
                    'display' => true,
                    'position' => 'bottom',
                ],
            ],
        ];
    }
}
