<?php

namespace App\Filament\Resources;

use App\Filament\Clusters\MyProjects;
use App\Filament\Resources\ProjectCharterChangeRequestResource\Pages;
use App\Models\ProjectCharterChangeRequest;
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 ProjectCharterChangeRequestResource extends Resource implements HasShieldPermissions
{
    protected static ?string $model = ProjectCharterChangeRequest::class;

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

    protected static ?int $navigationSort = 4;

    protected static SubNavigationPosition $subNavigationPosition = SubNavigationPosition::Top;

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

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

                        Forms\Components\Select::make('change_type')
                            ->label(__('project_charter_change_request.change_type'))
                            ->options(ProjectCharterChangeRequest::getChangeTypes())
                            ->required()
                            ->live()
                            ->afterStateUpdated(function (Forms\Set $set, $state) {
                                // Reset conditional fields when change type changes
                                if ($state !== ProjectCharterChangeRequest::CHANGE_TYPE_SCOPE) {
                                    $set('includes_duration_change', false);
                                    $set('includes_cost_change', false);
                                }
                            }),

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

                Forms\Components\Section::make(__('project_charter_change_request.scope_changes'))
                    ->description(__('project_charter_change_request.scope_changes_description'))
                    ->schema([
                        Forms\Components\Textarea::make('scope_changes')
                            ->label(__('project_charter_change_request.scope_changes_details'))
                            ->required()
                            ->maxLength(65535)
                            ->rows(4)
                            ->columnSpanFull(),

                        Forms\Components\Checkbox::make('includes_duration_change')
                            ->label(__('project_charter_change_request.includes_duration_change'))
                            ->live(),

                        Forms\Components\Checkbox::make('includes_cost_change')
                            ->label(__('project_charter_change_request.includes_cost_change'))
                            ->live(),
                    ])
                    ->visible(fn (Forms\Get $get): bool => $get('change_type') === ProjectCharterChangeRequest::CHANGE_TYPE_SCOPE)
                    ->columns(2),

                Forms\Components\Section::make(__('project_charter_change_request.duration_changes'))
                    ->description(__('project_charter_change_request.duration_changes_description'))
                    ->schema([
                        Forms\Components\DatePicker::make('new_start_date')
                            ->label(__('project_charter_change_request.new_start_date'))
                            ->native(false),

                        Forms\Components\DatePicker::make('new_end_date')
                            ->label(__('project_charter_change_request.new_end_date'))
                            ->native(false)
                            ->after('new_start_date'),

                        Forms\Components\TextInput::make('additional_duration_days')
                            ->label(__('project_charter_change_request.additional_duration_days'))
                            ->numeric()
                            ->minValue(0)
                            ->suffix(__('project_charter_change_request.days'))
                            ->columnSpanFull(),
                    ])
                    ->visible(function (Forms\Get $get): bool {
                        $changeType = $get('change_type');

                        return $changeType === ProjectCharterChangeRequest::CHANGE_TYPE_DURATION ||
                            ($changeType === ProjectCharterChangeRequest::CHANGE_TYPE_SCOPE && $get('includes_duration_change'));
                    })
                    ->columns(2),

                Forms\Components\Section::make(__('project_charter_change_request.cost_changes'))
                    ->description(__('project_charter_change_request.cost_changes_description'))
                    ->schema([
                        Forms\Components\TextInput::make('additional_cost')
                            ->label(__('project_charter_change_request.additional_cost'))
                            ->numeric()
                            ->minValue(0)
                            ->prefix('SAR')
                            ->step(0.01),

                        Forms\Components\Textarea::make('cost_breakdown')
                            ->label(__('project_charter_change_request.cost_breakdown'))
                            ->maxLength(65535)
                            ->rows(3)
                            ->columnSpanFull(),
                    ])
                    ->visible(function (Forms\Get $get): bool {
                        $changeType = $get('change_type');

                        return $changeType === ProjectCharterChangeRequest::CHANGE_TYPE_COST ||
                            ($changeType === ProjectCharterChangeRequest::CHANGE_TYPE_SCOPE && $get('includes_cost_change'));
                    })
                    ->columns(2),

                Forms\Components\Section::make(__('project_charter_change_request.attachments'))
                    ->description(__('project_charter_change_request.attachments_description'))
                    ->schema([
                        SpatieMediaLibraryFileUpload::make('attachments')
                            ->label(__('project_charter_change_request.supporting_documents'))
                            ->collection('change_request_attachments')
                            ->visibility('private')
                            ->multiple()
                            ->downloadable()
                            ->openable()
                            ->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)
                            ->maxSize(10240) // 10MB
                            ->columnSpanFull(),
                    ]),

                Forms\Components\Section::make(__('project_charter_change_request.review_information'))
                    ->description(__('project_charter_change_request.review_information_description'))
                    ->schema([
                        Forms\Components\Select::make('status')
                            ->label(__('project_charter_change_request.status'))
                            ->options(ProjectCharterChangeRequest::getStatuses())
                            ->default(ProjectCharterChangeRequest::STATUS_PENDING)
                            ->disabled(fn ($record) => ! $record || ! Auth::user()->can('approve_change_request_project::charter::change::request')),

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

                        Forms\Components\Placeholder::make('reviewed_info')
                            ->label(__('project_charter_change_request.review_details'))
                            ->content(function ($record) {
                                if (! $record || ! $record->reviewed_at) {
                                    return __('project_charter_change_request.not_reviewed_yet');
                                }

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

                                return __('project_charter_change_request.reviewed_by_at', [
                                    'reviewer' => $reviewer,
                                    'date' => $record->reviewed_at->format('d M Y H:i'),
                                ]);
                            })
                            ->columnSpanFull(),

                        SpatieMediaLibraryFileUpload::make('final_approval_attachments_display')
                            ->label(__('project_charter_change_request.final_approval_attachments'))
                            ->collection('final_approval_attachments')
                            ->visibility('private')
                            ->multiple()
                            ->disabled()
                            ->visible(fn ($record) => $record && $record->getFinalApprovalAttachments()->count() > 0)
                            ->columnSpanFull(),
                    ])
                    ->visible(fn ($record) => $record && Auth::user()->can('approve_change_request_project::charter::change::request'))
                    ->columns(2),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('projectCharter.name')
                    ->label(__('project_charter_change_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('change_type')
                    ->label(__('project_charter_change_request.change_type'))
                    ->badge()
                    ->formatStateUsing(fn (string $state): string => ProjectCharterChangeRequest::getChangeTypes()[$state] ?? $state)
                    ->color(fn (string $state): string => match ($state) {
                        ProjectCharterChangeRequest::CHANGE_TYPE_SCOPE => 'info',
                        ProjectCharterChangeRequest::CHANGE_TYPE_DURATION => 'warning',
                        ProjectCharterChangeRequest::CHANGE_TYPE_COST => 'danger',
                        default => 'gray',
                    })
                    ->sortable(),

                Tables\Columns\TextColumn::make('status')
                    ->label(__('project_charter_change_request.status'))
                    ->badge()
                    ->formatStateUsing(fn (string $state): string => ProjectCharterChangeRequest::getStatuses()[$state] ?? $state)
                    ->color(fn (string $state): string => match ($state) {
                        ProjectCharterChangeRequest::STATUS_PENDING => 'warning',
                        ProjectCharterChangeRequest::STATUS_FIRST_APPROVED => 'info',
                        ProjectCharterChangeRequest::STATUS_APPROVED => 'success',
                        ProjectCharterChangeRequest::STATUS_REJECTED => 'danger',
                        default => 'gray',
                    })
                    ->sortable(),

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

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

                Tables\Columns\TextColumn::make('additional_cost')
                    ->label(__('project_charter_change_request.additional_cost'))
                    ->money('SAR')
                    ->sortable()
                    ->placeholder('—')
                    ->toggleable(isToggledHiddenByDefault: true),

                Tables\Columns\TextColumn::make('additional_duration_days')
                    ->label(__('project_charter_change_request.additional_duration_days'))
                    ->formatStateUsing(fn ($state) => $state ? $state.' '.__('project_charter_change_request.days') : '—')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),

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

                Tables\Columns\TextColumn::make('firstApprovedBy.name')
                    ->label(__('project_charter_change_request.first_approved_by'))
                    ->searchable()
                    ->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('reviewed_at')
                    ->label(__('project_charter_change_request.reviewed_at'))
                    ->date()
                    ->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('final_approved_at')
                    ->label(__('project_charter_change_request.final_approved_at'))
                    ->date()
                    ->sortable()
                    ->placeholder('—')
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('change_type')
                    ->label(__('project_charter_change_request.change_type'))
                    ->options(ProjectCharterChangeRequest::getChangeTypes()),

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

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

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

                Tables\Filters\Filter::make('pending_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(),
            ])
            ->actions([
                Tables\Actions\Action::make('first_approve')
                    ->label(__('project_charter_change_request.first_approve'))
                    ->icon('heroicon-o-check-circle')
                    ->color('info')
                    ->visible(fn (ProjectCharterChangeRequest $record): bool => $record->canFirstApprove())
                    ->form([
                        Forms\Components\Textarea::make('approval_notes')
                            ->label(__('project_charter_change_request.first_approval_notes'))
                            ->placeholder(__('project_charter_change_request.first_approval_notes_placeholder'))
                            ->maxLength(65535)
                            ->rows(3),
                    ])
                    ->action(function (ProjectCharterChangeRequest $record, array $data): void {
                        $result = $record->firstApprove($data['approval_notes'] ?? '');

                        if ($result) {
                            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();
                        }
                    }),

                Tables\Actions\Action::make('final_approve')
                    ->label(__('project_charter_change_request.final_approve'))
                    ->icon('heroicon-o-check-circle')
                    ->color('success')
                    ->visible(fn (ProjectCharterChangeRequest $record): bool => $record->canFinalApprove())
                    ->form([
                        Forms\Components\Textarea::make('approval_notes')
                            ->label(__('project_charter_change_request.final_approval_notes'))
                            ->placeholder(__('project_charter_change_request.final_approval_notes_placeholder'))
                            ->maxLength(65535)
                            ->rows(3),

                        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): void {
                        $result = $record->finalApprove($data['approval_notes'] ?? '');

                        if ($result) {
                            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();
                        }
                    }),

                Tables\Actions\Action::make('reject')
                    ->label(__('project_charter_change_request.reject'))
                    ->icon('heroicon-o-x-circle')
                    ->color('danger')
                    ->visible(fn (ProjectCharterChangeRequest $record): bool => $record->canReject())
                    ->form([
                        Forms\Components\Textarea::make('review_notes')
                            ->label(__('project_charter_change_request.review_notes'))
                            ->placeholder(__('project_charter_change_request.rejection_reason_placeholder'))
                            ->required()
                            ->maxLength(65535)
                            ->rows(3),
                    ])
                    ->action(function (ProjectCharterChangeRequest $record, array $data): void {
                        $result = $record->reject($data['review_notes']);

                        if ($result) {
                            Notification::make()
                                ->title(__('project_charter_change_request.change_request_rejected'))
                                ->success()
                                ->send();
                        } else {
                            Notification::make()
                                ->title(__('project_charter_change_request.rejection_failed'))
                                ->danger()
                                ->send();
                        }
                    }),

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

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

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListProjectCharterChangeRequests::route('/'),
            'create' => Pages\CreateProjectCharterChangeRequest::route('/create'),
            'view' => Pages\ViewProjectCharterChangeRequest::route('/{record}'),
            'edit' => Pages\EditProjectCharterChangeRequest::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_change_request',      // First approval (تأكيد)
            'final_approve_change_request', // Final approval (اعتماد)
        ];
    }
}
