<?php

namespace App\Filament\Widgets;

use App\Filament\Resources\InitiativeResource;
use App\Models\InitiativeOperationGoal;
use BezhanSalleh\FilamentShield\Traits\HasWidgetShield;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Widgets\Concerns\InteractsWithPageFilters;
use Filament\Widgets\TableWidget as BaseWidget;

class InitiativeOperationGoalsStatusTable extends BaseWidget
{
    use HasWidgetShield, InteractsWithPageFilters;

    protected static ?string $heading = null;

    protected static bool $isLazy = false;

    protected static ?string $pollingInterval = null;

    protected static ?int $sort = 6;

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

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

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

    public function table(Table $table): Table
    {
        return $table
            ->query($this->getBaseQuery())
            ->columns([
                Tables\Columns\TextColumn::make('initiative.name')
                    ->label(__('widgets.initiative'))
                    ->sortable()
                    ->searchable()
                    ->wrap()
                    ->url(fn (InitiativeOperationGoal $record): string => InitiativeResource::getUrl('view', ['record' => $record->initiative]))
                    ->color('primary')
                    ->weight('medium'),

                Tables\Columns\TextColumn::make('name')
                    ->label(__('widgets.goal'))
                    ->sortable()
                    ->searchable()
                    ->wrap(),

                Tables\Columns\TextColumn::make('target')
                    ->label(__('widgets.target_single'))
                    ->getStateUsing(fn (InitiativeOperationGoal $record) => $record->target)
                    ->alignEnd()
                    ->wrap(),

                Tables\Columns\TextColumn::make('actual')
                    ->label(__('widgets.actual_single'))
                    ->getStateUsing(fn (InitiativeOperationGoal $record) => $record->actual ?? '-')
                    ->alignEnd()
                    ->wrap(),

                Tables\Columns\TextColumn::make('achievement')
                    ->label(__('widgets.achievement_percentage'))
                    ->getStateUsing(function (InitiativeOperationGoal $record) {
                        $target = $this->extractNumericValue($record->target);
                        if ($target <= 0) {
                            return 0;
                        }
                        $actual = $this->extractNumericValue($record->actual);

                        return round(min(100, ($actual / $target) * 100), 1);
                    })
                    ->formatStateUsing(fn ($state) => number_format($state, 1).'%')
                    ->badge()
                    ->color(fn ($state) => $state >= 80 ? 'success' : ($state >= 50 ? 'warning' : 'danger'))
                    ->alignCenter(),
            ])
            ->striped()
            ->paginated([10, 25, 50])
            ->defaultPaginationPageOption(25);
    }

    protected function getBaseQuery()
    {
        $departmentId = $this->filters['department_id'] ?? null;
        $walletId = $this->filters['performance_wallet_id'] ?? null;
        $initiativeId = $this->filters['initiative_id'] ?? null;

        $query = InitiativeOperationGoal::query()->with(['initiative.performanceWallet.performanceCard']);

        if ($initiativeId) {
            $query->where('initiative_id', $initiativeId);
        } elseif ($walletId) {
            $query->whereHas('initiative', function ($q) use ($walletId) {
                $q->where('performance_wallet_id', $walletId);
            });
        } elseif ($departmentId) {
            $query->whereHas('initiative.performanceWallet.performanceCard', function ($q) use ($departmentId) {
                $q->where('department_id', $departmentId);
            });
        }

        return $query;
    }

    private function extractNumericValue(?string $text): float
    {
        if (! $text) {
            return 0;
        }

        $cleaned = preg_replace('/[^\d.,]/', '', $text);
        if (empty($cleaned)) {
            return 0;
        }
        $cleaned = str_replace(',', '.', $cleaned);
        preg_match('/\d+\.?\d*/', $cleaned, $matches);

        return $matches ? (float) $matches[0] : 0;
    }
}
