<?php

declare(strict_types=1);

namespace App\Filament\Resources\FindingExceptionResource\Pages;

use App\Filament\Resources\FindingExceptionResource;
use App\Filament\Resources\FindingResource;
use App\Filament\Widgets\ManagedEnvironment\FindingExceptionStatsOverview;
use App\Models\FindingException;
use Filament\Actions\Action;
use Filament\Resources\Pages\ListRecords;
use Filament\Schemas\Components\Tabs\Tab;
use Illuminate\Database\Eloquent\Builder;

class ListFindingExceptions extends ListRecords
{
    protected static string $resource = FindingExceptionResource::class;

    protected function getHeaderWidgets(): array
    {
        return [
            FindingExceptionStatsOverview::class,
        ];
    }

    /**
     * @return array<string, Tab>
     */
    public function getTabs(): array
    {
        $stats = FindingExceptionResource::exceptionStatsForCurrentTenant();
        $needsAction = $stats['pending'] + $stats['expiring'] + $stats['expired'];

        return [
            'all' => Tab::make('All')
                ->icon('heroicon-m-list-bullet'),
            'needs_action' => Tab::make('Needs action')
                ->icon('heroicon-m-exclamation-triangle')
                ->modifyQueryUsing(fn (Builder $query) => $query->whereIn('status', [
                    FindingException::STATUS_PENDING,
                    FindingException::STATUS_EXPIRING,
                    FindingException::STATUS_EXPIRED,
                ]))
                ->badge($needsAction > 0 ? $needsAction : null)
                ->badgeColor('warning'),
            'active' => Tab::make('Active')
                ->icon('heroicon-m-check-badge')
                ->modifyQueryUsing(fn (Builder $query) => $query->where('status', FindingException::STATUS_ACTIVE)),
            'historical' => Tab::make('Historical')
                ->icon('heroicon-m-archive-box')
                ->modifyQueryUsing(fn (Builder $query) => $query->whereIn('status', [
                    FindingException::STATUS_REJECTED,
                    FindingException::STATUS_REVOKED,
                    FindingException::STATUS_SUPERSEDED,
                ])),
        ];
    }

    protected function getHeaderActions(): array
    {
        return [
            Action::make('open_findings')
                ->label('Open findings')
                ->icon('heroicon-o-arrow-top-right-on-square')
                ->color('gray')
                ->url(FindingResource::getUrl('index')),
            Action::make('open_approval_queue')
                ->label('Open approval queue')
                ->icon('heroicon-o-arrow-top-right-on-square')
                ->color('gray')
                ->visible(fn (): bool => FindingExceptionResource::canAccessApprovalQueueForTenant())
                ->url(fn (): ?string => FindingExceptionResource::approvalQueueUrl()),
        ];
    }
}
