<?php

namespace App\Filament\Resources;

use App\Filament\Clusters\MyProjects;
use App\Filament\Resources\ProjectCharterCompletionRequestResource\Pages;
use App\Models\ProjectCharterCompletionRequest;
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\Support\Facades\Auth;

class ProjectCharterCompletionRequestResource extends Resource implements HasShieldPermissions
{
    protected static ?string $model = ProjectCharterCompletionRequest::class;

    protected static ?string $navigationIcon = 'heroicon-o-clipboard-document-check';

    protected static ?int $navigationSort = 2;

    protected static SubNavigationPosition $subNavigationPosition = SubNavigationPosition::Top;

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

    public static function getNavigationLabel(): 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 getPluralModelLabel(): string
    {
        return __('project_charter_completion_request.project_charter_completion_requests');
    }

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

                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),

                Forms\Components\Select::make('status')
                    ->label(__('project_charter_completion_request.status'))
                    ->options(ProjectCharterCompletionRequest::getStatuses())
                    ->default(ProjectCharterCompletionRequest::STATUS_PENDING)
                    ->disabled(),

                Forms\Components\Textarea::make('review_notes')
                    ->label(__('project_charter_completion_request.review_notes'))
                    ->rows(3)
                    ->visible(fn ($context) => $context === 'view'),

                Forms\Components\DateTimePicker::make('reviewed_at')
                    ->label(__('project_charter_completion_request.reviewed_at'))
                    ->disabled()
                    ->visible(fn ($context) => $context === 'view'),

                SpatieMediaLibraryFileUpload::make('closure_attachments')
                    ->label(__('project_charter.closure_attachments'))
                    ->collection('closure_attachments')
                    ->visibility('private')
                    ->multiple()
                    ->acceptedFileTypes(['application/pdf'])
                    ->maxSize(10240) // 10MB
                    ->downloadable()
                    ->helperText(__('project_charter.closure_attachments_helper')),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('projectCharter.name')
                    ->label(__('project_charter_completion_request.charter_name'))
                    ->searchable()
                    ->sortable(),

                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('requestedBy.name')
                    ->label(__('project_charter_completion_request.requester'))
                    ->searchable()
                    ->sortable(),

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

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

                Tables\Columns\TextColumn::make('reviewed_at')
                    ->label(__('project_charter_completion_request.reviewed_at'))
                    ->date()
                    ->sortable()
                    ->placeholder('-'),
            ])
            ->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()),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),

                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();
                        }
                    }),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->defaultSort('created_at', 'desc');
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListProjectCharterCompletionRequests::route('/'),
            'create' => Pages\CreateProjectCharterCompletionRequest::route('/create'),
            'view' => Pages\ViewProjectCharterCompletionRequest::route('/{record}'),
            'edit' => Pages\EditProjectCharterCompletionRequest::route('/{record}/edit'),
        ];
    }

    public static function getPermissionPrefixes(): array
    {
        return [
            'view',
            'view_any',
            'create',
            'update',
            'delete',
            'delete_any',
            'approve_completion_request',
            'reject_completion_request',
        ];
    }
}
