<?php

namespace App\Filament\Resources\ProjectCharterResource\RelationManagers;

use Filament\Forms;
use Filament\Forms\Components\SpatieMediaLibraryFileUpload;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\HtmlString;

class DeliverablesRelationManager extends RelationManager
{
    protected static string $relationship = 'deliverables';

    public static function getTitle(Model $ownerRecord, string $pageClass): string
    {
        return __('project_charter_deliverable.deliverables');
    }

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

    public static function getPluralModelLabel(): string
    {
        return __('project_charter_deliverable.deliverables');
    }

    public function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\TextInput::make('name')
                    ->label(__('project_charter_deliverable.name'))
                    ->required()
                    ->maxLength(255),

                // Forms\Components\Textarea::make('description')
                //     ->label(__('project_charter_deliverable.description'))
                //     ->rows(3)
                //     ->maxLength(1000),

                Forms\Components\DatePicker::make('expected_delivery_date')
                    ->label(__('project_charter_deliverable.expected_delivery_date'))
                    ->required()
                    ->afterOrEqual(function () {
                        // Access the ProjectCharter (owner record) start_date
                        return $this->getOwnerRecord()->start_date;
                    })
                    ->beforeOrEqual(function () {
                        // Access the ProjectCharter (owner record) expected_end_date
                        return $this->getOwnerRecord()->expected_end_date;
                    }),

                Forms\Components\TextInput::make('estimated_cost')
                    ->label(__('project_charter_deliverable.estimated_cost'))
                    ->numeric()
                    ->minValue(0)
                    ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                    ->step(0.01)
                    ->reactive()
                    ->helperText(function (Get $get) {
                        $charter = $this->getOwnerRecord();
                        if (! $charter || ! $charter->estimated_cost) {
                            return __('project_charter_deliverable.estimated_cost_helper');
                        }

                        $currentTotal = $charter->deliverables()->sum('estimated_cost') ?? 0;
                        $available = $charter->estimated_cost - $currentTotal;

                        return __('project_charter_deliverable.estimated_cost_helper').' '.
                            __('project_charter.available_budget_info', [
                                'charter_cost' => number_format($charter->estimated_cost, 2),
                                'current_total' => number_format($currentTotal, 2),
                                'available' => number_format(max(0, $available), 2),
                            ]);
                    }),

                SpatieMediaLibraryFileUpload::make('deliverable_files')
                    ->label(__('project_charter_deliverable.file'))
                    ->collection('deliverable_files')
                    ->visibility('private')
                    ->acceptedFileTypes(['application/pdf'])
                    ->maxSize(10240) // 10MB
                    ->downloadable()
                    ->helperText(__('project_charter_deliverable.file_helper'))
                    ->visible(fn ($operation) => $operation === 'edit') // Only show in edit mode
                    ->disabled(fn ($record) => $record && ! $record->canOverwriteFile())
                    ->reactive(),

                // Forms\Components\TextInput::make('payment_number')
                //     ->label(__('project_charter_deliverable.payment_number'))
                //     ->maxLength(255),

                // Forms\Components\TextInput::make('weight')
                //     ->label(__('project_charter_deliverable.weight'))
                //     ->numeric()
                //     ->minValue(0)
                //     ->maxValue(100)
                //     ->suffix('%')
                //     ->helperText(__('project_charter_deliverable.weight_helper')),
            ]);
    }

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

                // Tables\Columns\TextColumn::make('description')
                //     ->label(__('project_charter_deliverable.description'))
                //     ->limit(20)
                //     ->toggleable(),

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

                Tables\Columns\TextColumn::make('estimated_cost')
                    ->label(__('project_charter_deliverable.estimated_cost'))
                    ->numeric(2)
                    ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                    ->sortable()
                    ->icon('heroicon-o-banknotes')
                    ->color('primary'),

                Tables\Columns\TextColumn::make('file_status')
                    ->label(__('project_charter_deliverable.file_status'))
                    ->badge()
                    ->color(fn ($state) => match ($state) {
                        'pending' => 'warning',
                        'approved' => 'success',
                        'rejected' => 'danger',
                        default => 'gray',
                    })
                    ->formatStateUsing(fn ($state) => $state ? __('project_charter_deliverable.file_status_'.$state) : __('project_charter_deliverable.no_file'))
                    ->sortable(),

                Tables\Columns\IconColumn::make('has_file')
                    ->label(__('project_charter_deliverable.has_file'))
                    ->boolean()
                    ->state(fn ($record) => $record->hasFile())
                    ->toggleable(),

                // Tables\Columns\TextColumn::make('payment_number')
                //     ->label(__('project_charter_deliverable.payment_number'))
                //     ->sortable()
                //     ->searchable()
                //     ->toggleable(),

                // Tables\Columns\TextColumn::make('weight')
                //     ->label(__('project_charter_deliverable.weight'))
                //     ->numeric()
                //     ->sortable()
                //     ->suffix('%')
                //     ->toggleable(),

                Tables\Columns\TextColumn::make('created_at')
                    ->label(__('project_charter_deliverable.created_at'))
                    ->date()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                // Tables\Columns\TextColumn::make('completion_status')
                //     ->label(__('project_charter_deliverable.completion_status'))
                //     ->state(function ($state, Model $record) {
                //         return $record->getCompletionStatusAttribute();
                //     })
                //     ->badge()
                //     ->color(fn($state) => match ($state) {
                //         'completed' => 'success',
                //         'in_progress' => 'warning',
                //         'not_started' => 'secondary',
                //         default => 'gray',
                //     }),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('file_status')
                    ->label(__('project_charter_deliverable.file_status'))
                    ->options([
                        'pending' => __('project_charter_deliverable.file_status_pending'),
                        'approved' => __('project_charter_deliverable.file_status_approved'),
                        'rejected' => __('project_charter_deliverable.file_status_rejected'),
                    ])
                    ->placeholder(__('All Statuses')),
            ])
            ->headerActions([
                Tables\Actions\CreateAction::make()
                    ->before(function (array $data, Tables\Actions\CreateAction $action) {
                        // Server-side validation for create action using model method
                        $deliverable = new \App\Models\ProjectCharterDeliverable;
                        $deliverable->project_charter_id = $this->getOwnerRecord()->id;

                        $validation = $deliverable->validateEstimatedCostLimit($data['estimated_cost'] ?? 0);

                        if (! $validation['valid']) {
                            \Filament\Notifications\Notification::make()
                                ->title(__('project_charter.cost_exceeded_title'))
                                ->body(__('project_charter.cost_exceeded_message', [
                                    'charter_cost' => number_format($validation['charter_budget'], 2),
                                    'current_total' => number_format($validation['current_total'], 2),
                                    'available' => number_format($validation['available'], 2),
                                    'requested' => number_format($validation['requested'], 2),
                                ]))
                                ->danger()
                                ->send();

                            $action->halt();
                        }
                    }),
            ])
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\Action::make('manage_completion_reports')
                        ->label(__('completion_report.manage_completion_reports'))
                        ->icon('heroicon-o-document-check')
                        ->color('info')
                        ->visible(fn ($record) => $record->canHaveCompletionReports())
                        ->url(
                            fn ($record): string => \App\Filament\Resources\ProjectCharterDeliverableResource::getUrl('manage_completion_reports', ['record' => $record])
                        ),
                    Tables\Actions\Action::make('approve_file')
                        ->label(__('project_charter_deliverable.approve_file'))
                        ->icon('heroicon-o-check')
                        ->color('success')
                        ->visible(fn ($record) => \Illuminate\Support\Facades\Auth::user()->can('approve_deliverable_file_project::charter') &&
                            $record->file_status === 'pending')
                        ->requiresConfirmation()
                        ->modalHeading(__('project_charter_deliverable.approve_file_confirmation'))
                        ->modalDescription(__('project_charter_deliverable.approve_file_description'))
                        ->action(function ($record) {
                            $record->approveFile(Auth::id());
                            \Filament\Notifications\Notification::make()
                                ->title(__('project_charter_deliverable.file_approved'))
                                ->success()
                                ->send();
                        }),
                    Tables\Actions\Action::make('reject_file')
                        ->label(__('project_charter_deliverable.reject_file'))
                        ->icon('heroicon-o-x-mark')
                        ->color('danger')
                        ->visible(fn ($record) => \Illuminate\Support\Facades\Auth::user()->can('approve_deliverable_file_project::charter') &&
                            $record->file_status === 'pending')
                        ->requiresConfirmation()
                        ->modalHeading(__('project_charter_deliverable.reject_file_confirmation'))
                        ->modalDescription(__('project_charter_deliverable.reject_file_description'))
                        ->form([
                            Forms\Components\Textarea::make('rejection_reason')
                                ->label(__('project_charter_deliverable.rejection_reason'))
                                ->required()
                                ->maxLength(1000)
                                ->rows(3),
                        ])
                        ->action(function ($record, array $data) {
                            $record->rejectFile(Auth::id(), $data['rejection_reason']);
                            \Filament\Notifications\Notification::make()
                                ->title(__('project_charter_deliverable.file_rejected'))
                                ->warning()
                                ->send();
                        }),
                    Tables\Actions\EditAction::make()
                        ->before(function (array $data, $record, Tables\Actions\EditAction $action) {
                            // Server-side validation for edit action using model method
                            $validation = $record->validateEstimatedCostLimit($data['estimated_cost'] ?? 0);

                            if (! $validation['valid']) {
                                \Filament\Notifications\Notification::make()
                                    ->title(__('project_charter.cost_exceeded_title'))
                                    ->body(__('project_charter.cost_exceeded_message', [
                                        'charter_cost' => number_format($validation['charter_budget'], 2),
                                        'current_total' => number_format($validation['current_total'], 2),
                                        'available' => number_format($validation['available'], 2),
                                        'requested' => number_format($validation['requested'], 2),
                                    ]))
                                    ->danger()
                                    ->send();

                                $action->halt();
                            }
                        }),
                    Tables\Actions\DeleteAction::make()
                        ->visible(fn ($record) => $record->file_status !== \App\Models\ProjectCharterDeliverable::FILE_STATUS_APPROVED ||
                            \Illuminate\Support\Facades\Auth::user()->can('delete_after_approval_deliverable_project::charter')),
                ]),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make()
                        ->action(function ($records, $action) {
                            // Check if user has permission to delete approved deliverables
                            $hasSpecialPermission = \Illuminate\Support\Facades\Auth::user()->can('delete_after_approval_deliverable_project::charter');

                            foreach ($records as $record) {
                                // If deliverable is approved and user doesn't have special permission, skip deletion
                                if ($record->file_status === \App\Models\ProjectCharterDeliverable::FILE_STATUS_APPROVED && ! $hasSpecialPermission) {
                                    \Filament\Notifications\Notification::make()
                                        ->title(__('project_charter_deliverable.cannot_delete_approved'))
                                        ->body(__('project_charter_deliverable.cannot_delete_approved_message', ['name' => $record->name]))
                                        ->warning()
                                        ->send();

                                    continue;
                                }

                                $record->delete();
                            }
                        }),
                ]),
            ]);
    }

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