<?php

namespace App\Filament\Resources;

use App\Filament\Clusters\MyProjects;
use App\Filament\Resources\ProjectCharterEscalationRequestResource\Pages;
use App\Models\ProjectCharterEscalationRequest;
use BezhanSalleh\FilamentShield\Contracts\HasShieldPermissions;
use Filament\Forms;
use Filament\Forms\Components\SpatieMediaLibraryFileUpload;
use Filament\Forms\Form;
use Filament\Notifications\Notification;
use Filament\Pages\SubNavigationPosition;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;

class ProjectCharterEscalationRequestResource extends Resource implements HasShieldPermissions
{
    protected static ?string $model = ProjectCharterEscalationRequest::class;

    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';

    protected static ?int $navigationSort = 3;

    protected static SubNavigationPosition $subNavigationPosition = SubNavigationPosition::Top;

    protected static ?string $cluster = MyProjects::class;

    public static function getNavigationLabel(): string
    {
        return __('project_charter_escalation_request.project_charter_escalation_requests');
    }

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

    public static function getPluralModelLabel(): string
    {
        return __('project_charter_escalation_request.project_charter_escalation_requests');
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make(__('project_charter_escalation_request.basic_information'))
                    ->description(__('project_charter_escalation_request.basic_information_description'))
                    ->schema([
                        Forms\Components\Select::make('project_charter_id')
                            ->label(__('project_charter_escalation_request.project_charter'))
                            ->relationship('projectCharter', 'name')
                            ->searchable()
                            ->preload()
                            ->required()
                            ->columnSpanFull(),

                        Forms\Components\Select::make('risk_register_id')
                            ->label(__('project_charter_escalation_request.risk_register'))
                            ->relationship('riskRegister', 'contingency_plan')
                            ->searchable()
                            ->preload()
                            ->placeholder(__('project_charter_escalation_request.select_related_risk'))
                            ->helperText(__('project_charter_escalation_request.risk_register_help'))
                            ->columnSpanFull(),

                        Forms\Components\TextInput::make('problem')
                            ->label(__('project_charter_escalation_request.problem'))
                            ->required()
                            ->maxLength(255)
                            ->helperText(__('project_charter_escalation_request.problem_help'))
                            ->columnSpanFull(),

                        Forms\Components\Textarea::make('details')
                            ->label(__('project_charter_escalation_request.details'))
                            ->required()
                            ->maxLength(65535)
                            ->rows(4)
                            ->helperText(__('project_charter_escalation_request.details_help'))
                            ->columnSpanFull(),
                    ])
                    ->columns(2),

                Forms\Components\Section::make(__('project_charter_escalation_request.attachments'))
                    ->description(__('project_charter_escalation_request.attachments_description'))
                    ->schema([
                        SpatieMediaLibraryFileUpload::make('attachments')
                            ->label(__('project_charter_escalation_request.supporting_documents'))
                            ->collection('escalation_attachments')
                            ->visibility('private')
                            ->multiple()
                            ->downloadable()
                            ->openable()
                            ->acceptedFileTypes([
                                'application/pdf',
                                'image/jpeg',
                                'image/png',
                                'application/msword',
                                'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                            ])
                            ->maxFiles(5)
                            ->maxSize(10240) // 10MB
                            ->columnSpanFull(),
                    ]),

                Forms\Components\Section::make(__('project_charter_escalation_request.level_1_review'))
                    ->description(__('project_charter_escalation_request.level_1_review_description'))
                    ->schema([
                        Forms\Components\Select::make('status')
                            ->label(__('project_charter_escalation_request.status'))
                            ->options(ProjectCharterEscalationRequest::getStatuses())
                            ->default(ProjectCharterEscalationRequest::STATUS_PENDING)
                            ->disabled(fn ($record) => ! $record || ! Auth::user()->can('approve_level_1_escalation_project::charter::escalation::request')),

                        Forms\Components\Textarea::make('level_1_resolution_notes')
                            ->label(__('project_charter_escalation_request.level_1_resolution_notes'))
                            ->maxLength(65535)
                            ->rows(3)
                            ->disabled(fn ($record) => ! $record || ! Auth::user()->can('approve_level_1_escalation_project::charter::escalation::request'))
                            ->columnSpanFull(),

                        Forms\Components\Placeholder::make('level_1_reviewer_info')
                            ->label(__('project_charter_escalation_request.level_1_reviewer'))
                            ->content(function ($record) {
                                if (! $record || ! $record->level_1_resolved_at) {
                                    return __('project_charter_escalation_request.not_reviewed_yet');
                                }

                                $reviewer = $record->level1ReviewedBy ? $record->level1ReviewedBy->name : __('project_charter_escalation_request.unknown_reviewer');

                                return __('project_charter_escalation_request.reviewed_by_at', [
                                    'reviewer' => $reviewer,
                                    'date' => $record->level_1_resolved_at->format('d M Y H:i'),
                                ]);
                            })
                            ->columnSpanFull(),
                    ])
                    ->visible(fn ($record) => $record && Auth::user()->can('approve_level_1_escalation_project::charter::escalation::request'))
                    ->columns(2),

                Forms\Components\Section::make(__('project_charter_escalation_request.level_2_review'))
                    ->description(__('project_charter_escalation_request.level_2_review_description'))
                    ->schema([
                        Forms\Components\Textarea::make('level_2_resolution_notes')
                            ->label(__('project_charter_escalation_request.level_2_resolution_notes'))
                            ->maxLength(65535)
                            ->rows(3)
                            ->disabled(fn ($record) => ! $record || ! Auth::user()->can('approve_level_2_escalation_project::charter::escalation::request'))
                            ->columnSpanFull(),

                        Forms\Components\Placeholder::make('level_2_reviewer_info')
                            ->label(__('project_charter_escalation_request.level_2_reviewer'))
                            ->content(function ($record) {
                                if (! $record || ! $record->level_2_resolved_at) {
                                    return __('project_charter_escalation_request.not_reviewed_yet');
                                }

                                $reviewer = $record->level2ReviewedBy ? $record->level2ReviewedBy->name : __('project_charter_escalation_request.unknown_reviewer');

                                return __('project_charter_escalation_request.reviewed_by_at', [
                                    'reviewer' => $reviewer,
                                    'date' => $record->level_2_resolved_at->format('d M Y H:i'),
                                ]);
                            })
                            ->columnSpanFull(),
                    ])
                    ->visible(fn ($record) => $record &&
                        $record->status === ProjectCharterEscalationRequest::STATUS_ESCALATED_TO_LEVEL_2 &&
                        Auth::user()->can('approve_level_2_escalation_project::charter::escalation::request'))
                    ->columns(1),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('projectCharter.name')
                    ->label(__('project_charter_escalation_request.project_charter'))
                    ->searchable()
                    ->sortable()
                    ->limit(20)
                    ->tooltip(function (Tables\Columns\TextColumn $column): ?string {
                        $state = $column->getState();

                        return strlen($state) > 30 ? $state : null;
                    }),

                Tables\Columns\TextColumn::make('problem')
                    ->label(__('project_charter_escalation_request.problem'))
                    ->searchable()
                    ->limit(20)
                    ->tooltip(function (Tables\Columns\TextColumn $column): ?string {
                        $state = $column->getState();

                        return strlen($state) > 40 ? $state : null;
                    }),

                Tables\Columns\TextColumn::make('status')
                    ->label(__('project_charter_escalation_request.status'))
                    ->badge()
                    ->formatStateUsing(fn (string $state): string => ProjectCharterEscalationRequest::getStatuses()[$state] ?? $state)
                    ->color(fn (string $state): string => match ($state) {
                        ProjectCharterEscalationRequest::STATUS_PENDING => 'warning',
                        ProjectCharterEscalationRequest::STATUS_RESOLVED => 'success',
                        ProjectCharterEscalationRequest::STATUS_ESCALATED_TO_LEVEL_2 => 'danger',
                        ProjectCharterEscalationRequest::STATUS_RESOLVED_LEVEL_2 => 'success',
                        default => 'gray',
                    })
                    ->sortable(),

                Tables\Columns\TextColumn::make('requestedBy.name')
                    ->label(__('project_charter_escalation_request.requested_by'))
                    ->searchable()
                    ->sortable()
                    ->limit(20),

                Tables\Columns\TextColumn::make('created_at')
                    ->label(__('project_charter_escalation_request.requested_at'))
                    ->date()
                    ->sortable(),

                Tables\Columns\TextColumn::make('riskRegister.contingency_plan')
                    ->label(__('project_charter_escalation_request.related_risk'))
                    ->searchable()
                    ->limit(20)
                    ->placeholder('—')
                    ->toggleable(isToggledHiddenByDefault: true),

                Tables\Columns\TextColumn::make('level1ReviewedBy.name')
                    ->label(__('project_charter_escalation_request.level_1_reviewer'))
                    ->searchable()
                    ->sortable()
                    ->placeholder('—')
                    ->toggleable(isToggledHiddenByDefault: true),

                Tables\Columns\TextColumn::make('level_1_resolved_at')
                    ->label(__('project_charter_escalation_request.level_1_resolved_at'))
                    ->date()
                    ->sortable()
                    ->placeholder('—')
                    ->toggleable(isToggledHiddenByDefault: true),

                Tables\Columns\TextColumn::make('level2ReviewedBy.name')
                    ->label(__('project_charter_escalation_request.level_2_reviewer'))
                    ->searchable()
                    ->sortable()
                    ->placeholder('—')
                    ->toggleable(isToggledHiddenByDefault: true),

                Tables\Columns\TextColumn::make('level_2_resolved_at')
                    ->label(__('project_charter_escalation_request.level_2_resolved_at'))
                    ->date()
                    ->sortable()
                    ->placeholder('—')
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('status')
                    ->label(__('project_charter_escalation_request.status'))
                    ->options(ProjectCharterEscalationRequest::getStatuses()),

                Tables\Filters\SelectFilter::make('project_charter_id')
                    ->label(__('project_charter_escalation_request.project_charter'))
                    ->relationship('projectCharter', 'name')
                    ->searchable()
                    ->preload(),

                Tables\Filters\Filter::make('my_requests')
                    ->label(__('project_charter_escalation_request.my_requests'))
                    ->query(fn (Builder $query): Builder => $query->where('requested_by', Auth::id()))
                    ->toggle(),

                Tables\Filters\Filter::make('pending_level_1')
                    ->label(__('project_charter_escalation_request.pending_level_1'))
                    ->query(fn (Builder $query): Builder => $query->where('status', ProjectCharterEscalationRequest::STATUS_PENDING))
                    ->toggle(),

                Tables\Filters\Filter::make('pending_level_2')
                    ->label(__('project_charter_escalation_request.pending_level_2'))
                    ->query(fn (Builder $query): Builder => $query->where('status', ProjectCharterEscalationRequest::STATUS_ESCALATED_TO_LEVEL_2))
                    ->toggle(),
            ])
            ->actions([
                Tables\Actions\Action::make('resolve_level_1')
                    ->label(__('project_charter_escalation_request.resolve_level_1'))
                    ->icon('heroicon-o-check-circle')
                    ->color('success')
                    ->visible(fn (ProjectCharterEscalationRequest $record): bool => $record->canResolveLevel1())
                    ->form([
                        Forms\Components\Textarea::make('resolution_notes')
                            ->label(__('project_charter_escalation_request.resolution_notes'))
                            ->placeholder(__('project_charter_escalation_request.resolution_notes_placeholder'))
                            ->required()
                            ->maxLength(65535)
                            ->rows(3),
                    ])
                    ->action(function (ProjectCharterEscalationRequest $record, array $data): void {
                        $result = $record->resolveLevel1($data['resolution_notes']);

                        if ($result) {
                            Notification::make()
                                ->title(__('project_charter_escalation_request.escalation_resolved_level_1'))
                                ->success()
                                ->send();
                        } else {
                            Notification::make()
                                ->title(__('project_charter_escalation_request.cannot_resolve'))
                                ->danger()
                                ->send();
                        }
                    }),

                Tables\Actions\Action::make('escalate_to_level_2')
                    ->label(__('project_charter_escalation_request.escalate_to_level_2'))
                    ->icon('heroicon-o-arrow-up')
                    ->color('warning')
                    ->visible(fn (ProjectCharterEscalationRequest $record): bool => $record->canEscalateToLevel2())
                    ->form([
                        Forms\Components\Textarea::make('escalation_notes')
                            ->label(__('project_charter_escalation_request.escalation_notes'))
                            ->placeholder(__('project_charter_escalation_request.escalation_notes_placeholder'))
                            ->maxLength(65535)
                            ->rows(3),
                    ])
                    ->action(function (ProjectCharterEscalationRequest $record, array $data): void {
                        $result = $record->escalateToLevel2($data['escalation_notes'] ?? '');

                        if ($result) {
                            Notification::make()
                                ->title(__('project_charter_escalation_request.escalation_escalated_to_level_2'))
                                ->success()
                                ->send();
                        } else {
                            Notification::make()
                                ->title(__('project_charter_escalation_request.cannot_escalate'))
                                ->danger()
                                ->send();
                        }
                    }),

                Tables\Actions\Action::make('resolve_level_2')
                    ->label(__('project_charter_escalation_request.resolve_level_2'))
                    ->icon('heroicon-o-check-circle')
                    ->color('success')
                    ->visible(fn (ProjectCharterEscalationRequest $record): bool => $record->canResolveLevel2())
                    ->form([
                        Forms\Components\Textarea::make('resolution_notes')
                            ->label(__('project_charter_escalation_request.resolution_notes'))
                            ->placeholder(__('project_charter_escalation_request.resolution_notes_placeholder'))
                            ->required()
                            ->maxLength(65535)
                            ->rows(3),
                    ])
                    ->action(function (ProjectCharterEscalationRequest $record, array $data): void {
                        $result = $record->resolveLevel2($data['resolution_notes']);

                        if ($result) {
                            Notification::make()
                                ->title(__('project_charter_escalation_request.escalation_resolved_level_2'))
                                ->success()
                                ->send();
                        } else {
                            Notification::make()
                                ->title(__('project_charter_escalation_request.cannot_resolve'))
                                ->danger()
                                ->send();
                        }
                    }),

                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make()
                    ->visible(
                        fn (ProjectCharterEscalationRequest $record): bool => Auth::user()->can('update', $record) && ! $record->isResolved()
                    ),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make()
                        ->visible(fn (): bool => Auth::user()->can('delete_any_project::charter::escalation::request')),
                ]),
            ])
            ->defaultSort('created_at', 'desc')
            ->striped()
            ->paginated([10, 25, 50, 100]);
    }

    public static function canCreate(): bool
    {
        return false;
    }

    public static function getRelations(): array
    {
        return [
            //
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListProjectCharterEscalationRequests::route('/'),
            'create' => Pages\CreateProjectCharterEscalationRequest::route('/create'),
            'view' => Pages\ViewProjectCharterEscalationRequest::route('/{record}'),
            'edit' => Pages\EditProjectCharterEscalationRequest::route('/{record}/edit'),
        ];
    }

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

            // Approval permissions
            'approve_level_1_escalation',
            'approve_level_2_escalation',
        ];
    }
}
