<?php

namespace App\Filament\Resources\OrderResource\Widgets;

use App\Enums\OrderStatus;
use App\Filament\Resources\OrderResource\Widgets\Concerns\AppliesOrdersListDateFilter;
use App\Models\Order;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget;

class OrdersByStatusWidget extends TableWidget
{
    use AppliesOrdersListDateFilter;

    protected int | string | array $columnSpan = 1;

    protected static ?int $sort = 1;

    public static function canView(): bool
    {
        return auth()->user()?->can('orders.view') ?? false;
    }

    public static function getCountsHeading(): string
    {
        return 'Reporte: Órdenes por estado';
    }

    public function table(Table $table): Table
    {
        return $table
            ->heading(static::getCountsHeading())
            ->queryStringIdentifier('orders_by_status')
            ->query(
                $this->applyOrdersListDateFilter(
                    Order::query()
                    ->leftJoin('tbl_order_statuses as s', 's.id_order_status', '=', 'tbl_orders.status_id')
                    ->selectRaw('MIN(tbl_orders.id_order) as id_order, tbl_orders.status_id, s.code as status_code, s.name as status_name, COUNT(*) as total')
                    ->groupBy('tbl_orders.status_id', 's.code', 's.name')
                    ->orderByDesc('total')
                )
            )
            ->columns([
                Tables\Columns\TextColumn::make('status_name')
                    ->label('Estado')
                    ->formatStateUsing(fn (?string $state) => filled($state) ? $state : '-')
                    ->badge()
                    ->color(function ($record): string {
                        $code = (string) ($record->status_code ?? '');
                        return OrderStatus::tryFrom($code)?->filamentColor() ?? 'gray';
                    })
                    ->tooltip(function ($record): ?string {
                        $code = (string) ($record->status_code ?? '');
                        return OrderStatus::tryFrom($code)?->definition();
                    })
                    ->wrap(),
                Tables\Columns\TextColumn::make('total')
                    ->label('Cantidad')
                    ->numeric()
                    ->sortable(),
            ])
            ->paginated(false);
    }
}
