<?php

namespace App\Filament\AssociationAdmin\Widgets;

use App\Models\ProjectCharter;
use BezhanSalleh\FilamentShield\Traits\HasWidgetShield;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget as BaseWidget;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\HtmlString;

class AssociationProjectCharterTable extends BaseWidget
{
    use HasWidgetShield;

    protected static ?int $sort = 3;

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

    public function getHeading(): string
    {
        return __('association-admin-dashboard.dashboard').' - '.'مشاريع الجهة';
    }

    protected function getTableHeading(): ?string
    {
        return __('association-admin-dashboard.dashboard').' - '.'مشاريع الجهة';
    }

    public function table(Table $table): Table
    {
        return $table
            ->query(
                ProjectCharter::query()->withoutGlobalScope(\App\Scopes\ViewPermissionScope::class)
                    ->when(Auth::user()?->association_id, function (Builder $query, $associationId) {
                        $query->where('status', ProjectCharter::STATUS_APPROVED)
                            ->whereHas('order', function ($orderQuery) use ($associationId) {
                                $orderQuery->where('association_id', $associationId);
                            });
                    }, function (Builder $query) {
                        // If user has no association, show no charters for security
                        $query->whereRaw('1 = 0');
                    })
            )
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->label('اسم المشروع')
                    ->sortable()
                    ->searchable()
                    ->weight('medium')
                    ->wrap(),

                Tables\Columns\BadgeColumn::make('project_status')
                    ->label('حالة المشروع')
                    ->colors([
                        'gray' => 'not_started',
                        'info' => 'in_progress',
                        'danger' => 'late',
                        'success' => 'done',
                    ])
                    ->formatStateUsing(function (string $state): string {
                        return match ($state) {
                            'not_started' => 'جديد',
                            'in_progress' => 'قيد التنفيذ',
                            'late' => 'متأخر',
                            'done' => 'مكتمل',
                            default => $state,
                        };
                    }),

                Tables\Columns\TextColumn::make('estimated_cost')
                    ->label('قيمة المشروع')
                    ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                    ->numeric(2)
                    ->sortable()
                    ->alignEnd(),

                Tables\Columns\TextColumn::make('project_progress')
                    ->label('نسبة الإنجاز')
                    ->formatStateUsing(fn ($state) => number_format($state, 1).'%')
                    ->badge()
                    ->color(function ($state) {
                        if ($state >= 80) {
                            return 'success';
                        }
                        if ($state >= 50) {
                            return 'warning';
                        }
                        if ($state >= 25) {
                            return 'info';
                        }

                        return 'gray';
                    })
                    ->sortable()
                    ->alignCenter(),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('project_status')
                    ->label('حالة المشروع')
                    ->options([
                        'not_started' => 'جديد',
                        'in_progress' => 'قيد التنفيذ',
                        'late' => 'متأخر',
                        'done' => 'مكتمل',
                    ])
                    ->placeholder('جميع الحالات'),
            ])
            ->actions([
                Tables\Actions\Action::make('view_progress')
                    ->label('عرض التفاصيل')
                    ->icon('heroicon-o-eye')
                    ->color('info')
                    ->url(
                        fn (ProjectCharter $record): string => route('filament.association-admin.resources.association-project-charters.view', ['record' => $record])
                    ),
            ])
            ->emptyStateHeading('لا توجد مشاريع')
            ->emptyStateDescription('لم يتم العثور على أي مشاريع معتمدة للجمعية.')
            ->emptyStateIcon('heroicon-o-document-text')
            ->defaultSort('created_at', 'desc')
            ->paginated([5, 10, 25])
            ->defaultPaginationPageOption(5);
    }
}
