<?php

namespace App\Filament\Resources;

use App\Filament\Resources\PerformanceCardResource\Pages;
use App\Models\PerformanceCard;
use App\Models\SekayaValue;
use BezhanSalleh\FilamentShield\Contracts\HasShieldPermissions;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Pages\SubNavigationPosition;
use Filament\Resources\Pages\Page;
use Filament\Resources\Resource;
use Filament\Support\Enums\FontWeight;
use Filament\Tables;
use Filament\Tables\Columns\Layout\Stack;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;

class PerformanceCardResource extends Resource implements HasShieldPermissions
{
    protected static ?string $model = PerformanceCard::class;

    protected static ?string $navigationIcon = 'heroicon-o-chart-bar';

    protected static ?int $navigationSort = 3;

    protected static SubNavigationPosition $subNavigationPosition = SubNavigationPosition::Top;

    public static function getNavigationLabel(): string
    {
        return __('performance_card.performance_cards');
    }

    public static function getModelLabel(): string
    {
        return __('performance_card.performance_card');
    }

    public static function getPluralModelLabel(): string
    {
        return __('performance_card.performance_cards');
    }

    public static function getNavigationGroup(): ?string
    {
        return __('common.navigation.group.project_management');
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make(__('performance_card.basic_information'))
                    ->schema([
                        Forms\Components\Select::make('department_id')
                            ->label(__('performance_card.department'))
                            ->relationship('department', 'name')
                            ->required()
                            ->preload()
                            ->searchable()
                            ->helperText(__('performance_card.department_helper')),

                        Forms\Components\Select::make('project_manner')
                            ->label(__('performance_card.project_manner'))
                            ->required()
                            ->options(PerformanceCard::getProjectManners())
                            ->default(PerformanceCard::PROJECT_MANNER_DEVELOPMENTAL),

                        Forms\Components\Textarea::make('goal')
                            ->label(__('performance_card.goal'))
                            ->required()
                            ->rows(3)
                            ->maxLength(1000)
                            ->helperText(__('performance_card.goal_helper')),
                    ])
                    ->columns(1),

                Forms\Components\Section::make(__('performance_card.relationships'))
                    ->schema([
                        Forms\Components\Select::make('products')
                            ->label(__('performance_card.products'))
                            ->multiple()
                            ->relationship(
                                'products',
                                'name',
                                fn (Builder $query) => $query->where('type', SekayaValue::TYPE_PERFORMANCE_CARD_PRODUCT)
                            )
                            ->preload()
                            ->searchable()
                            ->helperText(__('performance_card.products_helper')),

                        Forms\Components\Select::make('assignees')
                            ->label(__('performance_card.assignees'))
                            ->multiple()
                            ->relationship('assignees', 'name', fn (Builder $query) => $query->whereNull('association_id'))
                            ->preload()
                            ->searchable()
                            ->helperText(__('performance_card.assignees_helper')),
                    ])
                    ->columns(1),

                Forms\Components\Section::make(__('performance_card.card_results'))
                    ->schema([
                        Forms\Components\Repeater::make('results')
                            // ->label(__('performance_card.results'))
                            ->relationship('results')
                            ->simple(
                                Forms\Components\TextInput::make('result')
                                    ->label(__('performance_card.result'))
                                    ->required()
                                    ->maxLength(500),
                            ),
                        // ->reorderable(false)
                        // ->collapsible()
                        // ->itemLabel(fn(array $state): ?string => $state['result'] ?
                        //     \Illuminate\Support\Str::limit($state['result'], 50) : null)
                        // ->helperText(__('performance_card.results_helper')),
                    ])
                    ->columns(1),

                ...self::getWalletForm(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Stack::make([
                    // ID field
                    Tables\Columns\TextColumn::make('id')
                        ->label(__('performance_card.id'))
                        ->formatStateUsing(
                            fn (string $state): string => '#'.$state
                        )
                        ->badge()
                        ->color('gray')
                        ->weight(FontWeight::Bold),

                    // Project manner field
                    Tables\Columns\TextColumn::make('project_manner')
                        ->label(__('performance_card.project_manner'))
                        ->formatStateUsing(
                            fn (string $state): string => __('performance_card.project_manner').': '.(PerformanceCard::getProjectManners()[$state] ?? $state)
                        )
                        ->badge()
                        ->color(fn (string $state): string => match ($state) {
                            PerformanceCard::PROJECT_MANNER_DEVELOPMENTAL => 'success',
                            PerformanceCard::PROJECT_MANNER_SUPPORT => 'info',
                            PerformanceCard::PROJECT_MANNER_EMPOWERMENT => 'warning',
                            PerformanceCard::PROJECT_MANNER_INVESTMENT => 'primary',
                            default => 'gray',
                        }),

                    // Department field
                    Tables\Columns\TextColumn::make('department.name')
                        ->label(__('performance_card.department'))
                        ->formatStateUsing(
                            fn (?string $state): string => __('performance_card.department').': '.($state ?? 'غير محدد')
                        )
                        ->icon('heroicon-o-building-office')
                        ->weight(FontWeight::SemiBold)
                        ->searchable(),

                    // Wallet name field (NEW)
                    Tables\Columns\TextColumn::make('wallet.name')
                        ->label(__('performance_wallet.wallet_name'))
                        ->formatStateUsing(
                            fn (?string $state): string => __('performance_wallet.wallet_name').': '.($state ?? '-')
                        )
                        ->icon('heroicon-o-wallet')
                        ->color(fn (?string $state): string => $state ? 'success' : 'gray')
                        ->weight(FontWeight::SemiBold),

                    // Initiatives count field
                    Tables\Columns\TextColumn::make('initiatives_count')
                        ->label(__('performance_card.initiatives_count'))
                        ->formatStateUsing(
                            fn (int $state): string => trans_choice('common.initiatives_count', $state)
                        )
                        ->counts('initiatives')
                        ->color('primary')
                        ->icon('heroicon-o-light-bulb'),

                    // Goal field - REMOVED as requested
                    // Tables\Columns\TextColumn::make('goal')
                    //     ->label(__('performance_card.goal'))
                    //     ->formatStateUsing(function (?string $state): string {
                    //         $goalLabel = __('performance_card.goal');
                    //         if (! $state) {
                    //             return $goalLabel.': غير محدد';
                    //         }
                    //         $truncated = strlen($state) > 120 ? substr($state, 0, 120).'...' : $state;

                    //         return $goalLabel.': '.$truncated;
                    //     })
                    //     ->tooltip(function (Tables\Columns\TextColumn $column): ?string {
                    //         $state = $column->getRecord()->goal;
                    //         if (! $state || strlen($state) <= 120) {
                    //             return null;
                    //         }

                    //         return __('performance_card.goal').': '.$state;
                    //     })
                    //     ->searchable()
                    //     ->icon('heroicon-o-flag')
                    //     ->color('gray')
                    //     ->wrap(),
                ])
                    ->space(3)
                    ->extraAttributes(['class' => 'p-6']),
            ])
            ->contentGrid([
                'sm' => 1,
                'md' => 2,
                'lg' => 2,
                'xl' => 3,
                '2xl' => 4,
            ])
            ->filters([
                // Project manner filter
                Tables\Filters\SelectFilter::make('project_manner')
                    ->label(__('performance_card.project_manner'))
                    ->options(PerformanceCard::getProjectManners())
                    ->placeholder('جميع الأنماط'),

                // Department filter
                Tables\Filters\SelectFilter::make('department')
                    ->label(__('performance_card.department'))
                    ->relationship('department', 'name')
                    ->searchable()
                    ->preload()
                    ->placeholder('جميع الإدارات'),
            ])
            ->actions([
                // Tables\Actions\ActionGroup::make([
                //     Tables\Actions\ViewAction::make(),
                //     Tables\Actions\EditAction::make(),
                //     Tables\Actions\DeleteAction::make(),
                // ]),
            ])
            ->bulkActions([
                // Tables\Actions\BulkActionGroup::make([
                //     Tables\Actions\DeleteBulkAction::make(),
                // ]),
            ])
            ->defaultSort('created_at', 'desc')
            ->paginated([10, 25, 50, 100]);
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListPerformanceCards::route('/'),
            'create' => Pages\CreatePerformanceCard::route('/create'),
            'view' => Pages\ViewPerformanceCard::route('/{record}'),
            'edit' => Pages\EditPerformanceCard::route('/{record}/edit'),
            'view_initiatives' => Pages\ViewInitiativesPerformanceCard::route('/{record}/initiatives'),
            'view_wallet' => Pages\ViewWalletPerformanceCard::route('/{record}/wallet'),
        ];
    }

    public static function getRecordSubNavigation(Page $page): array
    {
        $navigationItems = [
            Pages\ViewPerformanceCard::class,
        ];

        if ($page->getRecord()->wallet) {
            $navigationItems[] = Pages\ViewWalletPerformanceCard::class;
            $navigationItems[] = Pages\ViewInitiativesPerformanceCard::class;
        }

        return $page->generateNavigationItems($navigationItems);
    }

    private static function getWalletForm(): array
    {
        return [
            Forms\Components\Section::make(__('performance_wallet.performance_wallet'))
                ->relationship('wallet')
                ->hidden(fn (string $operation): bool => $operation === 'create')
                ->schema([

                    Forms\Components\TextInput::make('name')
                        ->label(__('performance_wallet.name'))
                        ->required()
                        ->maxLength(255)
                        ->helperText(__('performance_wallet.name_helper')),

                    Forms\Components\DatePicker::make('start_date')
                        ->label(__('performance_wallet.start_date'))
                        ->required()
                        ->helperText(__('performance_wallet.date_range_helper')),

                    Forms\Components\DatePicker::make('expected_end_date')
                        ->label(__('performance_wallet.expected_end_date'))
                        ->required()
                        ->after('start_date'),

                    Forms\Components\Textarea::make('description')
                        ->label(__('performance_wallet.description'))
                        ->required()
                        ->rows(4)
                        ->maxLength(1000)
                        ->helperText(__('performance_wallet.description_helper')),
                ])
                ->columns(2),
        ];
    }

    public static function getPermissionPrefixes(): array
    {
        return [
            'view',
            'view_any',
            'create',
            'update',
            'restore',
            'restore_any',
            'replicate',
            'reorder',
            'delete',
            'delete_any',
            'force_delete',
            'force_delete_any',

            // custom
            'view_all',
        ];
    }
}
