<?php

namespace App\Filament\Widgets;

use App\Models\MediaStorageTarget;
use App\Services\Storage\StorageHealthService;
use Filament\Widgets\StatsOverviewWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;

class StorageCapacityWidget extends StatsOverviewWidget
{
    protected static ?int $sort = 1;

    protected function getStats(): array
    {
        $health = app(StorageHealthService::class);

        return MediaStorageTarget::all()
            ->map(function (MediaStorageTarget $target) use ($health) {
                $stats = $health->getCapacity($target);

                if ($stats['status'] !== 'ok') {
                    return Stat::make($target->name, 'Kapazität unbekannt')
                        ->description(match ($stats['status']) {
                            'unavailable' => 'Monitoring nicht verfügbar',
                            'unknown' => 'Monitor-Pfad nicht gesetzt',
                            'error' => $stats['message'] ?? 'Fehler beim Auslesen',
                            default => 'Status unbekannt',
                        })
                        ->descriptionIcon('heroicon-m-question-mark-circle')
                        ->color('warning');
                }

                $used = $this->formatBytes($stats['used']);
                $total = $this->formatBytes($stats['total']);
                $free = $this->formatBytes($stats['free']);
                $percentageValue = $stats['percentage'];
                $percent = $percentageValue !== null ? $percentageValue.' %' : '–';

                $color = 'success';
                if ($percentageValue === null) {
                    $color = 'warning';
                } elseif ($percentageValue >= 80) {
                    $color = 'danger';
                } elseif ($percentageValue >= 60) {
                    $color = 'warning';
                }

                return Stat::make($target->name, "$used / $total")
                    ->description("Frei: $free · Auslastung: $percent")
                    ->color($color)
                    ->extraAttributes([
                        'data-storage-disk' => $target->key,
                    ]);
            })
            ->toArray();
    }

    private function formatBytes(?int $bytes): string
    {
        if ($bytes === null) {
            return '–';
        }

        $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
        $index = 0;
        $value = (float) $bytes;

        while ($value >= 1024 && $index < count($units) - 1) {
            $value /= 1024;
            $index++;
        }

        return round($value, 1).' '.$units[$index];
    }
}
