<?php

namespace App\Filament\Widgets;

use App\Filament\Resources\PerformanceCardResource;
use App\Models\PerformanceWallet;
use BezhanSalleh\FilamentShield\Traits\HasWidgetShield;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Filament\Widgets\Concerns\InteractsWithPageFilters;
use Filament\Widgets\TableWidget as BaseWidget;

class PerformanceWalletStatusTable extends BaseWidget
{
    use HasWidgetShield;
    use InteractsWithPageFilters;

    protected static ?string $heading = null;

    protected static bool $isLazy = false;

    protected static ?string $pollingInterval = null;

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

    protected static ?int $sort = 4; // position after gauge

    public function getHeading(): string
    {
        return __('pages.projects_dashboard').' - '.__('widgets.performance_wallets_status');
    }

    protected function getTableHeading(): string
    {
        return __('pages.projects_dashboard').' - '.__('widgets.performance_wallets_status');
    }

    public function table(Table $table): Table
    {
        return $table
            ->query($this->getQuery())
            ->columns([
                TextColumn::make('name')
                    ->label(__('performance_wallet.name'))
                    ->searchable()
                    ->sortable()
                    ->url(
                        fn (PerformanceWallet $record): ?string => $record->performanceCard
                            ? PerformanceCardResource::getUrl('view', ['record' => $record->performanceCard])
                            : null
                    )
                    ->color('primary')
                    ->weight('medium'),
                TextColumn::make('performanceCard.department.name')
                    ->label(__('department.department'))
                    ->toggleable(isToggledHiddenByDefault: true)
                    ->sortable(),
                TextColumn::make('performanceCard.name')
                    ->label(__('performance_card.performance_card'))
                    ->toggleable(isToggledHiddenByDefault: true)
                    ->sortable(),
                TextColumn::make('start_date')
                    ->label(__('performance_wallet.start_date'))
                    ->date()
                    ->sortable(),
                TextColumn::make('expected_end_date')
                    ->label(__('performance_wallet.expected_end_date'))
                    ->date()
                    ->sortable(),
                TextColumn::make('initiatives_count')
                    ->label(__('performance_wallet.initiatives_count'))
                    ->counts('initiatives')
                    ->sortable(),
                TextColumn::make('createdBy.name')
                    ->label(__('performance_wallet.created_by'))
                    ->toggleable(isToggledHiddenByDefault: true)
                    ->sortable(),
            ])
            ->paginated([10, 25, 50])
            ->defaultPaginationPageOption(10)
            ->striped();
    }

    protected function getQuery()
    {
        $query = PerformanceWallet::query()->with(['performanceCard.department', 'createdBy'])
            ->withCount('initiatives');

        if ($departmentId = $this->filters['department_id'] ?? null) {
            $query->whereHas('performanceCard', function ($q) use ($departmentId) {
                $q->where('department_id', $departmentId);
            });
        }

        if ($walletId = $this->filters['performance_wallet_id'] ?? null) {
            $query->where('id', $walletId);
        }

        if ($initiativeId = $this->filters['initiative_id'] ?? null) {
            // Narrow to wallets that have the selected initiative
            $query->whereHas('initiatives', function ($q) use ($initiativeId) {
                $q->where('id', $initiativeId);
            });
        }

        return $query;
    }
}
