<?php

namespace App\Filament\Resources\ProjectCharterResource\RelationManagers;

use App\Models\ProjectCharterCompletionRequest;
use Filament\Forms;
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 CompletionRequestsRelationManager extends RelationManager
{
    protected static string $relationship = 'completionRequests';

    protected static ?string $title = null;

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

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

    public static function getModelPluralLabel(): string
    {
        return __('project_charter_completion_request.project_charter_completion_requests');
    }

    public function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('type')
                    ->label(__('project_charter_completion_request.type'))
                    ->options(ProjectCharterCompletionRequest::getTypes())
                    ->required(),

                Forms\Components\Textarea::make('reason')
                    ->label(__('project_charter_completion_request.reason'))
                    ->required()
                    ->rows(4),
            ]);
    }

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('type')
            ->columns([
                Tables\Columns\TextColumn::make('type')
                    ->label(__('project_charter_completion_request.request_type'))
                    ->badge()
                    ->formatStateUsing(fn (string $state): string => ProjectCharterCompletionRequest::getTypes()[$state] ?? $state)
                    ->colors([
                        ProjectCharterCompletionRequest::TYPE_COMPLETE => 'success',
                        ProjectCharterCompletionRequest::TYPE_SUSPEND => 'warning',
                        ProjectCharterCompletionRequest::TYPE_CANCEL => 'danger',
                    ]),

                Tables\Columns\TextColumn::make('status')
                    ->label(__('project_charter_completion_request.request_status'))
                    ->badge()
                    ->formatStateUsing(fn (string $state): string => ProjectCharterCompletionRequest::getStatuses()[$state] ?? $state)
                    ->colors([
                        ProjectCharterCompletionRequest::STATUS_PENDING => 'warning',
                        ProjectCharterCompletionRequest::STATUS_APPROVED => 'success',
                        ProjectCharterCompletionRequest::STATUS_REJECTED => 'danger',
                    ]),

                Tables\Columns\TextColumn::make('reason')
                    ->label(__('project_charter_completion_request.reason'))
                    ->limit(20)
                    ->tooltip(fn ($record) => $record->reason),

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

                Tables\Columns\TextColumn::make('reviewedBy.name')
                    ->label(__('project_charter_completion_request.reviewer'))
                    ->placeholder('-'),

                Tables\Columns\TextColumn::make('created_at')
                    ->label(__('project_charter_completion_request.created_at'))
                    ->date()
                    ->sortable(),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('type')
                    ->label(__('project_charter_completion_request.type'))
                    ->options(ProjectCharterCompletionRequest::getTypes()),

                Tables\Filters\SelectFilter::make('status')
                    ->label(__('project_charter_completion_request.status'))
                    ->options(ProjectCharterCompletionRequest::getStatuses()),
            ])
            ->headerActions([
                // Tables\Actions\CreateAction::make()
                //     ->visible(fn() => $this->getOwnerRecord()->canRequestCompletion() || $this->getOwnerRecord()->canRequestClosure())
                //     ->mutateFormDataUsing(function (array $data): array {
                //         $data['project_charter_id'] = $this->getOwnerRecord()->id;
                //         return $data;
                //     })
                //     ->using(function (array $data): ProjectCharterCompletionRequest {
                //         $projectCharter = $this->getOwnerRecord();

                //         if ($data['type'] === ProjectCharterCompletionRequest::TYPE_COMPLETION) {
                //             $projectCharter->requestCompletion($data['reason']);
                //         } else {
                //             $projectCharter->requestClosure($data['reason']);
                //         }

                //         return $projectCharter->completionRequests()->latest()->first();
                //     })
                //     ->successNotificationTitle(function (array $data) {
                //         return $data['type'] === ProjectCharterCompletionRequest::TYPE_COMPLETION
                //             ? __('project_charter.completion_requested_successfully')
                //             : __('project_charter.closure_requested_successfully');
                //     }),
            ])
            ->actions([
                Tables\Actions\ViewAction::make()
                    ->url(fn ($record) => \App\Filament\Resources\ProjectCharterCompletionRequestResource::getUrl('view', ['record' => $record])),

                Tables\Actions\Action::make('approve')
                    ->label(__('project_charter_completion_request.approve_request'))
                    ->icon('heroicon-o-check-circle')
                    ->color('success')
                    ->visible(
                        fn (ProjectCharterCompletionRequest $record): bool => $record->canApprove() &&
                            Auth::user()->can('approve_completion_request_project::charter::completion::request')
                    )
                    ->form([
                        Forms\Components\Textarea::make('review_notes')
                            ->label(__('project_charter_completion_request.review_notes'))
                            ->rows(3)
                            ->placeholder(__('project_charter_completion_request.approval_notes_placeholder')),
                    ])
                    ->action(function (ProjectCharterCompletionRequest $record, array $data) {
                        if ($record->approve($data['review_notes'] ?? '')) {
                            Notification::make()
                                ->title(__('project_charter_completion_request.request_approved_successfully'))
                                ->success()
                                ->send();
                        } else {
                            Notification::make()
                                ->title(__('project_charter_completion_request.approval_failed'))
                                ->danger()
                                ->send();
                        }
                    }),

                Tables\Actions\Action::make('reject')
                    ->label(__('project_charter_completion_request.reject_request'))
                    ->icon('heroicon-o-x-circle')
                    ->color('danger')
                    ->visible(
                        fn (ProjectCharterCompletionRequest $record): bool => $record->canReject() &&
                            Auth::user()->can('reject_completion_request_project::charter::completion::request')
                    )
                    ->form([
                        Forms\Components\Textarea::make('review_notes')
                            ->label(__('project_charter_completion_request.review_notes'))
                            ->required()
                            ->rows(3)
                            ->placeholder(__('project_charter_completion_request.rejection_notes_placeholder')),
                    ])
                    ->action(function (ProjectCharterCompletionRequest $record, array $data) {
                        if ($record->reject($data['review_notes'])) {
                            Notification::make()
                                ->title(__('project_charter_completion_request.request_rejected_successfully'))
                                ->success()
                                ->send();
                        } else {
                            Notification::make()
                                ->title(__('project_charter_completion_request.rejection_failed'))
                                ->danger()
                                ->send();
                        }
                    }),

                Tables\Actions\EditAction::make()
                    ->visible(
                        fn (ProjectCharterCompletionRequest $record): bool => $record->status === ProjectCharterCompletionRequest::STATUS_PENDING &&
                            Auth::id() === $record->requested_by
                    ),

                Tables\Actions\DeleteAction::make()
                    ->visible(
                        fn (ProjectCharterCompletionRequest $record): bool => $record->status === ProjectCharterCompletionRequest::STATUS_PENDING &&
                            Auth::id() === $record->requested_by
                    ),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->emptyStateIcon('heroicon-o-clipboard-document-check')
            ->emptyStateHeading(__('project_charter_completion_request.no_requests'))
            ->emptyStateDescription(__('project_charter_completion_request.no_requests_description'))
            ->defaultSort('created_at', 'desc');
    }
}
