<?php

namespace App\Filament\Widgets;

use App\Filament\Resources\ProjectCharterResource;
use App\Models\DonorFinancialPortfolio;
use App\Models\ProjectCharter;
use BezhanSalleh\FilamentShield\Traits\HasWidgetShield;
use Filament\Tables;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget as BaseWidget;
use Illuminate\Support\HtmlString;

class DonorProjectStatusTable extends BaseWidget
{
    use HasWidgetShield;

    protected static ?int $sort = 2;

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

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

    public function getTableHeading(): string
    {
        return __('pages.financial_portfolios_dashboard').' - '.__('widgets.donor_project_status_table');
    }

    public function table(Table $table): Table
    {
        return $table
            ->query(
                ProjectCharter::query()
                    ->whereHas('order.donorFinancialPortfolios', function ($query) {
                        // Only show projects with orders linked to portfolios accessible to current user
                        $query->whereIn('donor_financial_portfolio_id', DonorFinancialPortfolio::pluck('id'));
                    })
                    ->with(['order.donorFinancialPortfolios', 'order.association'])
            )
            ->defaultSort('created_at', 'desc')
            ->columns([
                // اسم المشروع - Project Name (from ProjectCharter)
                TextColumn::make('name')
                    ->label(__('widgets.project_name'))
                    ->searchable()
                    ->sortable()
                    ->wrap()
                    ->url(fn (ProjectCharter $record): string => ProjectCharterResource::getUrl('view', ['record' => $record]))
                    ->color('primary')
                    ->weight('medium'),

                // قيمة المشاريع - Project Value (Total allocated amount from order)
                TextColumn::make('project_value')
                    ->label(__('widgets.project_value'))
                    ->getStateUsing(function (ProjectCharter $record) {
                        return $record->order?->getTotalAllocatedFunding() ?? 0;
                    })
                    ->numeric(2)
                    ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                    ->sortable()
                    ->color('primary'),

                // حالة المشروع - Project Status (from ProjectCharter)
                TextColumn::make('project_status')
                    ->label(__('widgets.project_status'))
                    ->badge()
                    ->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,
                        };
                    })
                    ->color(fn (ProjectCharter $record) => $record->project_status_color ?? 'gray')
                    ->sortable(),

                // اسم المانح - Donors (from order's donor portfolios)
                TextColumn::make('donors')
                    ->label(__('widgets.donor_name'))
                    ->getStateUsing(function (ProjectCharter $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(),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('project_status')
                    ->label(__('widgets.filter_by_status'))
                    ->options([
                        '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'),
                    ])
                    ->multiple(),
            ])
            ->actions([])
            ->emptyStateHeading(__('widgets.no_projects_found'))
            ->emptyStateDescription(__('widgets.no_projects_description'))
            ->emptyStateIcon('heroicon-o-document-text')
            ->paginated([10, 25, 50])
            ->defaultPaginationPageOption(25);
    }
}
