<?php

namespace App\Filament\Resources\ProjectCharterResource\RelationManagers;

use App\Models\ProjectCharterEscalationRequest;
use App\Models\RiskRegister;
use Filament\Forms;
use Filament\Forms\Components\SpatieMediaLibraryFileUpload;
use Filament\Forms\Form;
use Filament\Notifications\Notification;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Support\Facades\Auth;

class EscalationRequestsRelationManager extends RelationManager
{
    protected static string $relationship = 'escalationRequests';

    public static function getTitle(\Illuminate\Database\Eloquent\Model $ownerRecord, string $pageClass): string
    {
        return __('project_charter_escalation_request.escalation_requests');
    }

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

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

    public function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make(__('project_charter_escalation_request.escalation_requests'))
                    ->schema([
                        Forms\Components\Select::make('risk_register_id')
                            ->label(__('project_charter_escalation_request.risk_register'))
                            ->helperText(__('project_charter_escalation_request.risk_register_help'))
                            ->options(function () {
                                return RiskRegister::where('charter_id', $this->getOwnerRecord()->id)
                                    ->pluck('contingency_plan', 'id');
                            })
                            ->searchable()
                            ->preload(),

                        Forms\Components\Textarea::make('problem')
                            ->label(__('project_charter_escalation_request.problem'))
                            ->helperText(__('project_charter_escalation_request.problem_help'))
                            ->required()
                            ->rows(3)
                            ->columnSpanFull(),

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

                        SpatieMediaLibraryFileUpload::make('escalation_attachments')
                            ->label(__('project_charter_escalation_request.attachments'))
                            ->collection('escalation_attachments')
                            ->visibility('private')
                            ->multiple()
                            ->acceptedFileTypes(['application/pdf', 'image/jpeg', 'image/png', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'])
                            ->maxSize(10240) // 10MB
                            ->columnSpanFull(),
                    ])
                    ->columns(2),
            ]);
    }

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('problem')
            ->columns([
                Tables\Columns\TextColumn::make('problem')
                    ->label(__('project_charter_escalation_request.problem'))
                    ->limit(20)
                    ->wrap()
                    ->searchable(),

                Tables\Columns\TextColumn::make('status')
                    ->label(__('project_charter_escalation_request.status'))
                    ->badge()
                    ->color(fn ($state) => match ($state) {
                        'pending' => 'warning',
                        'resolved' => 'success',
                        'escalated_to_level_2' => 'info',
                        'resolved_level_2' => 'success',
                        default => 'gray',
                    })
                    ->formatStateUsing(fn ($state) => ProjectCharterEscalationRequest::getStatuses()[$state] ?? $state),

                Tables\Columns\TextColumn::make('riskRegister.risk_description')
                    ->label(__('project_charter_escalation_request.risk_register'))
                    ->limit(20)
                    ->placeholder('-'),

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

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

                Tables\Columns\TextColumn::make('level_1_resolved_at')
                    ->label(__('project_charter_escalation_request.resolved_at'))
                    ->date()
                    ->sortable()
                    ->placeholder('-'),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('status')
                    ->label(__('project_charter_escalation_request.status'))
                    ->options(ProjectCharterEscalationRequest::getStatuses()),
            ])
            ->headerActions([
                Tables\Actions\CreateAction::make()
                    ->label(__('project_charter_escalation_request.create_escalation'))
                    ->icon('heroicon-o-exclamation-triangle')
                    ->successNotificationTitle(__('project_charter_escalation_request.escalation_created')),
            ])
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\ViewAction::make()
                        ->form($this->getViewForm()),

                    Tables\Actions\Action::make('resolve_level_1')
                        ->label(__('project_charter_escalation_request.resolve_level_1'))
                        ->icon('heroicon-o-check')
                        ->color('success')
                        ->form([
                            Forms\Components\Textarea::make('resolution_notes')
                                ->label(__('project_charter_escalation_request.resolution_notes'))
                                ->required()
                                ->rows(3)
                                ->placeholder(__('project_charter_escalation_request.resolution_notes_required')),
                        ])
                        ->action(function (ProjectCharterEscalationRequest $record, array $data) {
                            if ($record->resolveLevel1($data['resolution_notes'])) {
                                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();
                            }
                        })
                        ->visible(fn (ProjectCharterEscalationRequest $record) => $record->canResolveLevel1()),

                    Tables\Actions\Action::make('escalate_to_level_2')
                        ->label(__('project_charter_escalation_request.escalate_to_level_2'))
                        ->icon('heroicon-o-arrow-up')
                        ->color('warning')
                        ->form([
                            Forms\Components\Textarea::make('escalation_notes')
                                ->label(__('project_charter_escalation_request.escalation_notes'))
                                ->helperText(__('project_charter_escalation_request.escalation_notes_help'))
                                ->rows(3),
                        ])
                        ->action(function (ProjectCharterEscalationRequest $record, array $data) {
                            if ($record->escalateToLevel2($data['escalation_notes'] ?? '')) {
                                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();
                            }
                        })
                        ->visible(fn (ProjectCharterEscalationRequest $record) => $record->canEscalateToLevel2()),

                    Tables\Actions\Action::make('resolve_level_2')
                        ->label(__('project_charter_escalation_request.resolve_level_2'))
                        ->icon('heroicon-o-check-circle')
                        ->color('success')
                        ->form([
                            Forms\Components\Textarea::make('resolution_notes')
                                ->label(__('project_charter_escalation_request.resolution_notes'))
                                ->required()
                                ->rows(3)
                                ->placeholder(__('project_charter_escalation_request.resolution_notes_required')),
                        ])
                        ->action(function (ProjectCharterEscalationRequest $record, array $data) {
                            if ($record->resolveLevel2($data['resolution_notes'])) {
                                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();
                            }
                        })
                        ->visible(fn (ProjectCharterEscalationRequest $record) => $record->canResolveLevel2()),

                    Tables\Actions\EditAction::make()
                        ->visible(fn (ProjectCharterEscalationRequest $record) => $record->status === ProjectCharterEscalationRequest::STATUS_PENDING),

                    Tables\Actions\DeleteAction::make()
                        ->visible(fn (ProjectCharterEscalationRequest $record) => $record->status === ProjectCharterEscalationRequest::STATUS_PENDING),
                ]),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make()
                        ->visible(fn () => Auth::user()->can('delete_any_project::charter::escalation::request')),
                ]),
            ]);
    }

    protected function getViewForm(): array
    {
        return [
            Forms\Components\Section::make(__('project_charter_escalation_request.escalation_requests'))
                ->schema([
                    Forms\Components\Placeholder::make('problem')
                        ->label(__('project_charter_escalation_request.problem'))
                        ->content(fn (ProjectCharterEscalationRequest $record) => $record->problem),

                    Forms\Components\Placeholder::make('status')
                        ->label(__('project_charter_escalation_request.status'))
                        ->content(fn (ProjectCharterEscalationRequest $record) => ProjectCharterEscalationRequest::getStatuses()[$record->status] ?? $record->status),

                    Forms\Components\Placeholder::make('details')
                        ->label(__('project_charter_escalation_request.details'))
                        ->content(fn (ProjectCharterEscalationRequest $record) => $record->details)
                        ->columnSpanFull(),

                    Forms\Components\Placeholder::make('risk_register')
                        ->label(__('project_charter_escalation_request.risk_register'))
                        ->content(fn (ProjectCharterEscalationRequest $record) => $record->riskRegister?->risk_description ?: '-'),
                ])
                ->columns(2),

            Forms\Components\Section::make(__('project_charter_escalation_request.level_1_resolution_notes'))
                ->schema([
                    Forms\Components\Placeholder::make('level_1_reviewed_by')
                        ->label(__('project_charter_escalation_request.reviewer'))
                        ->content(fn (ProjectCharterEscalationRequest $record) => $record->level1ReviewedBy?->name ?: '-'),

                    Forms\Components\Placeholder::make('level_1_resolved_at')
                        ->label(__('project_charter_escalation_request.resolved_at'))
                        ->content(fn (ProjectCharterEscalationRequest $record) => $record->level_1_resolved_at ? $record->level_1_resolved_at->format('M d, Y H:i') : '-'),

                    Forms\Components\Placeholder::make('level_1_resolution_notes')
                        ->label(__('project_charter_escalation_request.level_1_resolution_notes'))
                        ->content(fn (ProjectCharterEscalationRequest $record) => $record->level_1_resolution_notes ?: '-')
                        ->columnSpanFull(),
                ])
                ->visible(fn (ProjectCharterEscalationRequest $record) => $record->level_1_resolved_at !== null),

            Forms\Components\Section::make(__('project_charter_escalation_request.level_2_resolution_notes'))
                ->schema([
                    Forms\Components\Placeholder::make('level_2_reviewed_by')
                        ->label(__('project_charter_escalation_request.reviewer'))
                        ->content(fn (ProjectCharterEscalationRequest $record) => $record->level2ReviewedBy?->name ?: '-'),

                    Forms\Components\Placeholder::make('level_2_resolved_at')
                        ->label(__('project_charter_escalation_request.resolved_at'))
                        ->content(fn (ProjectCharterEscalationRequest $record) => $record->level_2_resolved_at ? $record->level_2_resolved_at->format('M d, Y H:i') : '-'),

                    Forms\Components\Placeholder::make('level_2_resolution_notes')
                        ->label(__('project_charter_escalation_request.level_2_resolution_notes'))
                        ->content(fn (ProjectCharterEscalationRequest $record) => $record->level_2_resolution_notes ?: '-')
                        ->columnSpanFull(),
                ])
                ->visible(fn (ProjectCharterEscalationRequest $record) => $record->level_2_resolved_at !== null),
        ];
    }

    public function isReadOnly(): bool
    {
        return false;
    }
}
