<?php

namespace App\Filament\Widgets;

use App\Filament\Resources\ProjectCharterResource;
use App\Models\ProjectCharter;
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 ProjectDetailsTable extends BaseWidget
{
    use HasWidgetShield;
    use InteractsWithPageFilters;

    protected static ?string $heading = null;

    protected static ?int $sort = 6;

    protected static bool $isLazy = false;

    protected static ?string $pollingInterval = null;

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

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

    public function table(Table $table): Table
    {
        return $table
            ->query($this->getQuery())
            ->columns([
                TextColumn::make('name')
                    ->label(__('project_charter.name'))
                    ->searchable()
                    ->sortable()
                    ->url(fn (ProjectCharter $record): string => ProjectCharterResource::getUrl('view', ['record' => $record]))
                    ->color('primary')
                    ->weight('medium'),
                TextColumn::make('project_progress')
                    ->label(__('project_charter.project_completion_percentage'))
                    ->formatStateUsing(fn ($state) => number_format($state, 1).'%')
                    ->sortable(),
                TextColumn::make('project_status')
                    ->label(__('project_charter.progress_status'))
                    ->getStateUsing(fn ($record) => $record->project_status)
                    ->formatStateUsing(function ($state) {
                        return match ($state) {
                            'not_started' => __('project_charter.project_status_not_started'),
                            'in_progress' => __('project_charter.project_status_in_progress'),
                            'late' => __('project_charter.project_status_late'),
                            'done' => __('project_charter.project_status_done'),
                            default => $state,
                        };
                    })
                    ->badge()
                    ->color(fn ($record) => $record->project_status_color ?? 'gray')
                    ->sortable(),
                TextColumn::make('donors')
                    ->label(__('widgets.donor_name'))
                    ->getStateUsing(function ($record) {
                        $portfolios = $record->order?->donorFinancialPortfolios;
                        if (! $portfolios || $portfolios->isEmpty()) {
                            return '-';
                        }
                        $names = $portfolios->pluck('name')->unique()->toArray();
                        $separator = app()->getLocale() === 'ar' ? '، ' : ', ';

                        return implode($separator, $names);
                    })
                    ->wrap()
                    ->toggleable(isToggledHiddenByDefault: false),
            ])
            ->defaultSort('start_date', 'desc')
            ->paginated([10, 25, 50])
            ->defaultPaginationPageOption(10)
            ->striped();
    }

    protected function getQuery()
    {
        $query = ProjectCharter::query()
            ->with([
                'order.donorFinancialPortfolios',
                'initiativeProject.initiative.performanceWallet.performanceCard.department',
                'deliverables',
            ]);

        // Apply year filter
        if ($selectedYear = $this->filters['year'] ?? null) {
            $query->where(function ($subQuery) use ($selectedYear) {
                $subQuery->whereYear('start_date', $selectedYear)
                    ->orWhereYear('expected_end_date', $selectedYear);
            });
        }

        if ($departmentId = $this->filters['department_id'] ?? null) {
            $query->whereHas('initiativeProject.initiative.performanceWallet.performanceCard', function ($q) use ($departmentId) {
                $q->where('department_id', $departmentId);
            });
        }
        if ($walletId = $this->filters['performance_wallet_id'] ?? null) {
            $query->whereHas('initiativeProject.initiative', function ($q) use ($walletId) {
                $q->where('performance_wallet_id', $walletId);
            });
        }
        if ($initiativeId = $this->filters['initiative_id'] ?? null) {
            $query->whereHas('initiativeProject', function ($q) use ($initiativeId) {
                $q->where('initiative_id', $initiativeId);
            });
        }

        return $query;
    }
}
