<?php

namespace App\Filament\Resources\ProjectCharterResource\RelationManagers;

use App\Models\ProjectCharterChangeRequest;
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\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;

class ChangeRequestsRelationManager extends RelationManager
{
    protected static string $relationship = 'changeRequests';

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

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

    public static function getPluralModelLabel(): string
    {
        return __('project_charter_change_request.project_charter_change_requests');
    }

    public function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make(__('project_charter_change_request.basic_information'))
                    ->schema([
                        Forms\Components\Select::make('change_type')
                            ->label(__('project_charter_change_request.change_type'))
                            ->options(ProjectCharterChangeRequest::getChangeTypes())
                            ->required()
                            ->live()
                            ->afterStateUpdated(fn ($state, callable $set) => $set('type_changed', true)),

                        Forms\Components\Textarea::make('justification')
                            ->label(__('project_charter_change_request.justification'))
                            ->required()
                            ->rows(3)
                            ->columnSpanFull(),
                    ])
                    ->columns(2),

                // Scope Changes Section
                Forms\Components\Section::make(__('project_charter_change_request.scope_details'))
                    ->schema([
                        Forms\Components\Textarea::make('scope_changes')
                            ->label(__('project_charter_change_request.scope_changes'))
                            ->required()
                            ->rows(4)
                            ->columnSpanFull(),
                    ])
                    ->visible(fn ($get) => $get('change_type') === 'scope'),

                // Duration Changes Section
                Forms\Components\Section::make(__('project_charter_change_request.duration_changes'))
                    ->schema([
                        Forms\Components\DatePicker::make('new_start_date')
                            ->label(__('project_charter_change_request.new_start_date')),

                        Forms\Components\DatePicker::make('new_end_date')
                            ->label(__('project_charter_change_request.new_end_date'))
                            ->required(),

                        Forms\Components\Textarea::make('duration_justification')
                            ->label(__('project_charter_change_request.duration_justification'))
                            ->required()
                            ->rows(3)
                            ->columnSpanFull(),
                    ])
                    ->columns(2)
                    ->visible(fn ($get) => $get('change_type') === 'duration'),

                // Cost Changes Section
                Forms\Components\Section::make(__('project_charter_change_request.cost_changes'))
                    ->schema([
                        Forms\Components\TextInput::make('additional_cost')
                            ->label(__('project_charter_change_request.additional_cost'))
                            ->numeric()
                            ->required()
                            ->suffix('SAR')
                            ->step(0.01),

                        Forms\Components\TextInput::make('cost_category')
                            ->label(__('project_charter_change_request.cost_category'))
                            ->maxLength(255),

                        Forms\Components\Textarea::make('cost_justification')
                            ->label(__('project_charter_change_request.cost_justification'))
                            ->required()
                            ->rows(3)
                            ->columnSpanFull(),
                    ])
                    ->columns(2)
                    ->visible(fn ($get) => $get('change_type') === 'cost'),

                // Attachments Section
                Forms\Components\Section::make(__('project_charter_change_request.attachments'))
                    ->schema([
                        SpatieMediaLibraryFileUpload::make('change_request_attachments')
                            ->label(__('project_charter_change_request.change_request_attachments'))
                            ->helperText(__('project_charter_change_request.change_request_attachments_helper'))
                            ->collection('change_request_attachments')
                            ->visibility('private')
                            ->multiple()
                            ->acceptedFileTypes(['application/pdf', 'image/jpeg', 'image/png'])
                            ->maxSize(10240) // 10MB
                            ->columnSpanFull(),
                    ]),
            ]);
    }

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('change_type')
            ->columns([
                Tables\Columns\TextColumn::make('change_type')
                    ->label(__('project_charter_change_request.change_type'))
                    ->badge()
                    ->color(fn ($state) => match ($state) {
                        'scope' => 'info',
                        'duration' => 'warning',
                        'cost' => 'success',
                        default => 'gray',
                    })
                    ->formatStateUsing(fn ($state) => ProjectCharterChangeRequest::getChangeTypes()[$state] ?? $state),

                Tables\Columns\TextColumn::make('status')
                    ->label(__('project_charter_change_request.status'))
                    ->badge()
                    ->color(fn ($state) => match ($state) {
                        'pending' => 'warning',
                        'first_approved' => 'info',
                        'approved' => 'success',
                        'rejected' => 'danger',
                        default => 'gray',
                    })
                    ->formatStateUsing(fn ($state) => ProjectCharterChangeRequest::getStatuses()[$state] ?? $state),

                Tables\Columns\TextColumn::make('change_summary')
                    ->label(__('project_charter_change_request.change_summary'))
                    ->state(function (ProjectCharterChangeRequest $record): string {
                        $summary = $record->getChangesSummary();

                        return collect($summary)->map(fn ($value, $key) => "{$key}: {$value}")->join(', ') ?: '-';
                    })
                    ->limit(20)
                    ->wrap(),

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

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

                Tables\Columns\TextColumn::make('reviewed_at')
                    ->label(__('project_charter_change_request.reviewed_at'))
                    ->date()
                    ->sortable()
                    ->placeholder('-'),

                Tables\Columns\TextColumn::make('firstApprovedBy.name')
                    ->label(__('project_charter_change_request.first_approved_by'))
                    ->searchable()
                    ->sortable()
                    ->placeholder('-')
                    ->toggleable(isToggledHiddenByDefault: true),

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

                Tables\Columns\TextColumn::make('finalApprovedBy.name')
                    ->label(__('project_charter_change_request.final_approved_by'))
                    ->searchable()
                    ->sortable()
                    ->placeholder('-')
                    ->toggleable(isToggledHiddenByDefault: true),

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

                Tables\Filters\SelectFilter::make('change_type')
                    ->label(__('project_charter_change_request.change_type'))
                    ->options(ProjectCharterChangeRequest::getChangeTypes()),

                Tables\Filters\Filter::make('pending_first_approval')
                    ->label(__('project_charter_change_request.pending_approval'))
                    ->query(fn (Builder $query): Builder => $query->where('status', ProjectCharterChangeRequest::STATUS_PENDING))
                    ->toggle(),

                Tables\Filters\Filter::make('pending_final_approval')
                    ->label(__('project_charter_change_request.pending_final_approval'))
                    ->query(fn (Builder $query): Builder => $query->where('status', ProjectCharterChangeRequest::STATUS_FIRST_APPROVED))
                    ->toggle(),
            ])
            ->headerActions([
                Tables\Actions\CreateAction::make()
                    ->label(__('project_charter_change_request.create_change_request'))
                    ->icon('heroicon-o-document-text')
                    ->successNotificationTitle(__('project_charter_change_request.change_request_created')),
            ])
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\ViewAction::make()
                        ->form($this->getViewForm()),

                    Tables\Actions\Action::make('first_approve')
                        ->label(__('project_charter_change_request.first_approve'))
                        ->icon('heroicon-o-check')
                        ->color('info')
                        ->form([
                            Forms\Components\Textarea::make('approval_notes')
                                ->label(__('project_charter_change_request.first_approval_notes'))
                                ->rows(3)
                                ->placeholder(__('project_charter_change_request.first_approval_notes_placeholder')),
                        ])
                        ->action(function (ProjectCharterChangeRequest $record, array $data) {
                            if ($record->firstApprove($data['approval_notes'] ?? '')) {
                                Notification::make()
                                    ->title(__('project_charter_change_request.change_request_first_approved'))
                                    ->success()
                                    ->send();
                            } else {
                                Notification::make()
                                    ->title(__('project_charter_change_request.first_approval_failed'))
                                    ->danger()
                                    ->send();
                            }
                        })
                        ->visible(fn (ProjectCharterChangeRequest $record) => $record->canFirstApprove()),

                    Tables\Actions\Action::make('final_approve')
                        ->label(__('project_charter_change_request.final_approve'))
                        ->icon('heroicon-o-check-circle')
                        ->color('success')
                        ->form([
                            Forms\Components\Textarea::make('approval_notes')
                                ->label(__('project_charter_change_request.final_approval_notes'))
                                ->rows(3)
                                ->placeholder(__('project_charter_change_request.final_approval_notes_placeholder')),

                            SpatieMediaLibraryFileUpload::make('final_approval_attachments')
                                ->label(__('project_charter_change_request.final_approval_attachments'))
                                ->collection('final_approval_attachments')
                                ->visibility('private')
                                ->multiple()
                                ->acceptedFileTypes(['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'image/jpeg', 'image/png', 'image/gif'])
                                ->maxFiles(5)
                                ->helperText(__('project_charter_change_request.final_approval_attachments_help')),
                        ])
                        ->action(function (ProjectCharterChangeRequest $record, array $data) {
                            if ($record->finalApprove($data['approval_notes'] ?? '')) {
                                Notification::make()
                                    ->title(__('project_charter_change_request.change_request_final_approved'))
                                    ->success()
                                    ->send();
                            } else {
                                Notification::make()
                                    ->title(__('project_charter_change_request.final_approval_failed'))
                                    ->danger()
                                    ->send();
                            }
                        })
                        ->visible(fn (ProjectCharterChangeRequest $record) => $record->canFinalApprove()),

                    Tables\Actions\Action::make('reject')
                        ->label(__('project_charter_change_request.reject_change_request'))
                        ->icon('heroicon-o-x-mark')
                        ->color('danger')
                        ->form([
                            Forms\Components\Textarea::make('review_notes')
                                ->label(__('project_charter_change_request.review_notes'))
                                ->required()
                                ->rows(3)
                                ->placeholder(__('project_charter_change_request.review_notes_placeholder')),
                        ])
                        ->action(function (ProjectCharterChangeRequest $record, array $data) {
                            if ($record->reject($data['review_notes'])) {
                                Notification::make()
                                    ->title(__('project_charter_change_request.change_request_rejected'))
                                    ->success()
                                    ->send();
                            } else {
                                Notification::make()
                                    ->title(__('project_charter_change_request.cannot_reject'))
                                    ->danger()
                                    ->send();
                            }
                        })
                        ->visible(fn (ProjectCharterChangeRequest $record) => $record->canReject()),

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

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

    protected function getViewForm(): array
    {
        return [
            Forms\Components\Section::make(__('project_charter_change_request.change_details'))
                ->schema([
                    Forms\Components\Placeholder::make('change_type')
                        ->label(__('project_charter_change_request.change_type'))
                        ->content(fn (ProjectCharterChangeRequest $record) => ProjectCharterChangeRequest::getChangeTypes()[$record->change_type] ?? $record->change_type),

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

                    Forms\Components\Placeholder::make('justification')
                        ->label(__('project_charter_change_request.justification'))
                        ->content(fn (ProjectCharterChangeRequest $record) => $record->justification ?: '-')
                        ->columnSpanFull(),
                ])
                ->columns(2),

            Forms\Components\Section::make(__('project_charter_change_request.review_information'))
                ->schema([
                    Forms\Components\Placeholder::make('requested_by')
                        ->label(__('project_charter_change_request.requested_by'))
                        ->content(fn (ProjectCharterChangeRequest $record) => $record->requestedBy?->name ?: '-'),

                    Forms\Components\Placeholder::make('reviewed_by')
                        ->label(__('project_charter_change_request.reviewed_by'))
                        ->content(fn (ProjectCharterChangeRequest $record) => $record->reviewedBy?->name ?: '-'),

                    Forms\Components\Placeholder::make('first_approved_by')
                        ->label(__('project_charter_change_request.first_approved_by'))
                        ->content(fn (ProjectCharterChangeRequest $record) => $record->firstApprovedBy?->name ?: '-'),

                    Forms\Components\Placeholder::make('first_approved_at')
                        ->label(__('project_charter_change_request.first_approved_at'))
                        ->content(fn (ProjectCharterChangeRequest $record) => $record->first_approved_at?->format('M d, Y H:i') ?: '-'),

                    Forms\Components\Placeholder::make('final_approved_by')
                        ->label(__('project_charter_change_request.final_approved_by'))
                        ->content(fn (ProjectCharterChangeRequest $record) => $record->finalApprovedBy?->name ?: '-'),

                    Forms\Components\Placeholder::make('final_approved_at')
                        ->label(__('project_charter_change_request.final_approved_at'))
                        ->content(fn (ProjectCharterChangeRequest $record) => $record->final_approved_at?->format('M d, Y H:i') ?: '-'),

                    Forms\Components\Placeholder::make('first_approval_notes')
                        ->label(__('project_charter_change_request.first_approval_notes'))
                        ->content(fn (ProjectCharterChangeRequest $record) => $record->first_approval_notes ?: '-')
                        ->columnSpanFull()
                        ->visible(fn (ProjectCharterChangeRequest $record) => ! empty($record->first_approval_notes)),

                    Forms\Components\Placeholder::make('final_approval_notes')
                        ->label(__('project_charter_change_request.final_approval_notes'))
                        ->content(fn (ProjectCharterChangeRequest $record) => $record->final_approval_notes ?: '-')
                        ->columnSpanFull()
                        ->visible(fn (ProjectCharterChangeRequest $record) => ! empty($record->final_approval_notes)),

                    SpatieMediaLibraryFileUpload::make('final_approval_attachments_display')
                        ->label(__('project_charter_change_request.final_approval_attachments'))
                        ->collection('final_approval_attachments')
                        ->visibility('private')
                        ->multiple()
                        ->disabled()
                        ->visible(fn (ProjectCharterChangeRequest $record) => $record->getFinalApprovalAttachments()->count() > 0)
                        ->columnSpanFull(),

                    Forms\Components\Placeholder::make('review_notes')
                        ->label(__('project_charter_change_request.review_notes'))
                        ->content(fn (ProjectCharterChangeRequest $record) => $record->review_notes ?: '-')
                        ->columnSpanFull()
                        ->visible(fn (ProjectCharterChangeRequest $record) => ! empty($record->review_notes)),
                ])
                ->columns(2)
                ->visible(fn (ProjectCharterChangeRequest $record) => $record->status !== ProjectCharterChangeRequest::STATUS_PENDING),
        ];
    }

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