<?php

namespace App\Filament\Resources\ProjectCharterDeliverableResource\Pages;

use App\Filament\Resources\ExchangeRequestResource;
use App\Filament\Resources\ProjectCharterDeliverableResource;
use App\Models\CompletionReport;
use Carbon\Carbon;
use Filament\Forms;
use Filament\Forms\Components\SpatieMediaLibraryFileUpload;
use Filament\Forms\Form;
use Filament\Resources\Pages\ManageRelatedRecords;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Support\HtmlString;

class ManageCompletionReports extends ManageRelatedRecords
{
    protected static string $resource = ProjectCharterDeliverableResource::class;

    protected static string $relationship = 'completionReports';

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

    public static function getNavigationLabel(): string
    {
        return __('completion_report.manage_completion_reports');
    }

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

    public static function getPluralModelLabel(): string
    {
        return __('completion_report.completion_reports');
    }

    public function getTitle(): string
    {
        return __('completion_report.completion_reports');
    }

    public function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make(__('completion_report.report_details'))
                    ->description(__('completion_report.report_details_description'))
                    ->schema([
                        Forms\Components\Textarea::make('description')
                            ->label(__('completion_report.description'))
                            ->required()
                            ->rows(2)
                            ->maxLength(1000)
                            ->helperText(__('completion_report.description_helper')),

                        Forms\Components\DatePicker::make('delivery_date')
                            ->label(__('completion_report.delivery_date'))
                            ->required()
                            ->helperText(__('completion_report.delivery_date_helper')),

                        Forms\Components\Hidden::make('status')
                            ->default(fn () => CompletionReport::STATUS_PENDING),
                    ])
                    ->columns(1),

                Forms\Components\Section::make(__('completion_report.financial_information'))
                    ->description(__('completion_report.financial_information_description'))
                    ->schema([
                        Forms\Components\TextInput::make('value')
                            ->label(__('completion_report.value'))
                            ->numeric()
                            ->step(0.01)
                            ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                            ->required()
                            ->reactive()
                            ->afterStateUpdated(function ($state, $set, $get, $livewire) {
                                if ($state && $livewire->getOwnerRecord()) {
                                    $deliverable = $livewire->getOwnerRecord();
                                    $otherReportsSum = $deliverable->completionReports()
                                        ->when($livewire->getMountedTableActionRecord(), function ($query) use ($livewire) {
                                            return $query->where('id', '!=', $livewire->getMountedTableActionRecord()->id);
                                        })
                                        ->sum('value');

                                    $remainingBudget = $deliverable->estimated_cost - $otherReportsSum;
                                    $set('helper_text', __('completion_report.remaining_budget_info', [
                                        'remaining_budget' => number_format($remainingBudget, 2),
                                        'deliverable_estimated_cost' => number_format($deliverable->estimated_cost, 2),
                                    ]));
                                }
                            })
                            ->helperText(function ($get, $livewire) {
                                if ($livewire->getOwnerRecord()) {
                                    $deliverable = $livewire->getOwnerRecord();
                                    $otherReportsSum = $deliverable->completionReports()
                                        ->when($livewire->getMountedTableActionRecord(), function ($query) use ($livewire) {
                                            return $query->where('id', '!=', $livewire->getMountedTableActionRecord()->id);
                                        })
                                        ->sum('value');

                                    $remainingBudget = $deliverable->estimated_cost - $otherReportsSum;

                                    return __('completion_report.remaining_budget_info', [
                                        'remaining_budget' => number_format($remainingBudget, 2),
                                        'deliverable_estimated_cost' => number_format($deliverable->estimated_cost, 2),
                                    ]);
                                }

                                return __('completion_report.value_helper');
                            }),

                        Forms\Components\Hidden::make('helper_text'),

                        SpatieMediaLibraryFileUpload::make('pdf_file')
                            ->label(__('completion_report.pdf_file'))
                            ->collection('pdf_file')
                            ->visibility('private')
                            ->acceptedFileTypes(['application/pdf'])
                            ->maxSize(10240) // 10MB
                            ->downloadable()
                            ->helperText(__('completion_report.pdf_file_helper'))
                            ->required(),

                        SpatieMediaLibraryFileUpload::make('cr_files')
                            ->label(__('completion_report.cr_files'))
                            ->collection('cr_files')
                            ->visibility('private')
                            ->multiple()
                            ->acceptedFileTypes([
                                'application/pdf',
                                'image/jpeg',
                                'image/png',
                                'image/jpg',
                            ])
                            ->maxSize(10240) // 10MB per file
                            ->maxFiles(5) // Limit to 5 files
                            ->downloadable(),
                    ])
                    ->columns(1),
            ]);
    }

    public function table(Table $table): Table
    {
        return $table
            ->recordTitleAttribute('description')
            ->modelLabel(__('completion_report.completion_report'))
            ->pluralModelLabel(__('completion_report.completion_reports'))
            ->columns([
                Tables\Columns\TextColumn::make('id')
                    ->label('ID')
                    ->badge()
                    ->color('gray')
                    ->prefix('#')
                    ->sortable(),

                Tables\Columns\TextColumn::make('description')
                    ->label(__('completion_report.description'))
                    ->searchable()
                    ->limit(20)
                    ->tooltip(function (Tables\Columns\TextColumn $column): ?string {
                        $state = $column->getState();

                        return strlen($state) > 50 ? $state : null;
                    }),

                Tables\Columns\TextColumn::make('value')
                    ->label(__('completion_report.value'))
                    ->numeric(2)
                    ->prefix(new HtmlString('<span class="icon-saudi_riyal"></span>'))
                    ->sortable(),

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

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

                Tables\Columns\IconColumn::make('pdf_file')
                    ->label(__('completion_report.pdf_file'))
                    ->boolean()
                    ->getStateUsing(fn ($record) => $record->hasMedia('pdf_file'))
                    ->trueIcon('heroicon-o-document')
                    ->falseIcon('heroicon-o-x-circle')
                    ->trueColor('success')
                    ->falseColor('danger'),

                Tables\Columns\TextColumn::make('activeExchangeRequest.status')
                    ->label(__('exchange_request.status'))
                    ->badge()
                    ->color(function ($state) {
                        return match ($state) {
                            \App\Models\ExchangeRequest::STATUS_CREATED => 'gray',
                            \App\Models\ExchangeRequest::STATUS_FINANCIAL_APPROVED => 'info',
                            \App\Models\ExchangeRequest::STATUS_SHARED_SERVICES_APPROVED => 'warning',
                            \App\Models\ExchangeRequest::STATUS_CEO_APPROVED => 'primary',
                            \App\Models\ExchangeRequest::STATUS_TRANSACTION_APPROVED => 'success',
                            \App\Models\ExchangeRequest::STATUS_APPROVED => 'success',
                            \App\Models\ExchangeRequest::STATUS_REJECTED => 'danger',
                            default => 'gray',
                        };
                    })
                    ->formatStateUsing(function ($state, $record) {
                        if (! $record->activeExchangeRequest) {
                            return __('exchange_request.no_exchange_request');
                        }

                        return \App\Models\ExchangeRequest::getStatuses()[$state] ?? $state;
                    })
                    ->url(
                        fn (CompletionReport $record): ?string => $record->activeExchangeRequest
                            ? ExchangeRequestResource::getUrl('view', ['record' => $record->activeExchangeRequest->id])
                            : null
                    )
                    ->tooltip(__('exchange_request.click_to_view'))
                    ->sortable(),

                Tables\Columns\TextColumn::make('created_at')
                    ->label(__('completion_report.created_at'))
                    ->date()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('status')
                    ->label(__('completion_report.status'))
                    ->options(CompletionReport::getStatuses()),
            ])
            ->headerActions([
                Tables\Actions\CreateAction::make()
                    ->label(__('completion_report.create_completion_report'))
                    ->icon('heroicon-o-plus')
                    ->mutateFormDataUsing(function (array $data): array {
                        // Set the project_charter_deliverable_id from the parent record
                        $data['project_charter_deliverable_id'] = $this->getOwnerRecord()->id;

                        return $data;
                    })
                    ->before(function (array $data, Tables\Actions\CreateAction $action) {
                        // Create a temporary completion report for validation
                        $completionReport = new \App\Models\CompletionReport;
                        $completionReport->fill($data);
                        $completionReport->projectCharterDeliverable()->associate($this->getOwnerRecord());

                        $validation = $completionReport->validateValueAgainstDeliverableEstimatedCost();

                        if (! $validation['success']) {
                            \Filament\Notifications\Notification::make()
                                ->title(__('completion_report.validation_failed'))
                                ->body($validation['message'])
                                ->danger()
                                ->send();

                            $action->halt();
                        }
                    })
                    ->successNotificationTitle(__('completion_report.created_successfully')),
            ])
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\ViewAction::make(),

                    Tables\Actions\Action::make('approve')
                        ->label(__('completion_report.approve'))
                        ->icon('heroicon-o-check-circle')
                        ->color('success')
                        ->action(function (CompletionReport $record) {
                            if ($record->approve()) {
                                $this->replaceMountedAction('approve');

                                \Filament\Notifications\Notification::make()
                                    ->title(__('completion_report.approved_successfully'))
                                    ->success()
                                    ->send();
                            }
                        })
                        ->visible(fn (CompletionReport $record): bool => $record->canApprove()),

                    Tables\Actions\Action::make('reject')
                        ->label(__('completion_report.reject'))
                        ->icon('heroicon-o-x-circle')
                        ->color('danger')
                        ->action(function (CompletionReport $record) {
                            if ($record->reject()) {
                                $this->replaceMountedAction('reject');

                                \Filament\Notifications\Notification::make()
                                    ->title(__('completion_report.rejected_successfully'))
                                    ->success()
                                    ->send();
                            }
                        })
                        ->visible(fn (CompletionReport $record): bool => $record->canReject()),

                    Tables\Actions\Action::make('create_exchange_request')
                        ->label(__('exchange_request.create_exchange_request'))
                        ->icon('heroicon-o-currency-dollar')
                        ->color('primary')
                        ->form([
                            Forms\Components\Section::make(__('exchange_request.additional_files'))
                                ->description(__('exchange_request.additional_files_description'))
                                ->schema([
                                    SpatieMediaLibraryFileUpload::make('er_files')
                                        ->label(__('exchange_request.files'))
                                        ->collection('er_files')
                                        ->visibility('private')
                                        ->multiple()
                                        ->acceptedFileTypes([
                                            'application/pdf',
                                            'image/jpeg',
                                            'image/png',
                                            'image/jpg',
                                        ])
                                        ->maxSize(10240) // 10MB per file
                                        ->maxFiles(5) // Limit to 5 files
                                        ->downloadable()
                                        ->helperText(__('exchange_request.files_helper')),
                                ])
                                ->columns(1),
                        ])
                        ->action(function (array $data, CompletionReport $record) {
                            $exchangeRequest = $record->exchangeRequest()->create([
                                'status' => \App\Models\ExchangeRequest::STATUS_CREATED,
                            ]);

                            \Filament\Notifications\Notification::make()
                                ->title(__('exchange_request.created_successfully'))
                                ->success()
                                ->send();
                        })
                        ->modalHeading(__('exchange_request.create_exchange_request'))
                        ->modalSubmitActionLabel(__('exchange_request.create'))
                        ->visible(
                            fn (CompletionReport $record): bool => $record->status === CompletionReport::STATUS_APPROVED &&
                                ! $record->hasActiveExchangeRequest()
                        ),

                    Tables\Actions\Action::make('view_exchange_request')
                        ->label(__('exchange_request.view_exchange_request'))
                        ->icon('heroicon-o-eye')
                        ->color('info')
                        ->url(
                            fn (CompletionReport $record): ?string => $record->activeExchangeRequest
                                ? ExchangeRequestResource::getUrl('view', ['record' => $record->activeExchangeRequest->id])
                                : null
                        )
                        ->visible(fn (CompletionReport $record): bool => $record->hasActiveExchangeRequest()),

                    Tables\Actions\Action::make('download_pdf')
                        ->label(__('completion_report.download_pdf'))
                        ->icon('heroicon-o-arrow-down-tray')
                        ->color('info')
                        ->url(fn (CompletionReport $record): ?string => $record->getPdfFile()?->getTemporaryUrl(Carbon::now()->addMinutes(5)))
                        ->openUrlInNewTab()
                        ->visible(fn (CompletionReport $record): bool => $record->hasMedia('pdf_file')),

                    Tables\Actions\EditAction::make()
                        ->before(function (array $data, Tables\Actions\EditAction $action) {
                            $record = $action->getRecord();

                            // Update the record with new data for validation
                            $record->fill($data);

                            $validation = $record->validateValueAgainstDeliverableEstimatedCost();

                            if (! $validation['success']) {
                                \Filament\Notifications\Notification::make()
                                    ->title(__('completion_report.validation_failed'))
                                    ->body($validation['message'])
                                    ->danger()
                                    ->send();

                                $action->halt();
                            }
                        })
                        ->visible(fn (CompletionReport $record): bool => $record->status === CompletionReport::STATUS_PENDING),

                    Tables\Actions\DeleteAction::make()
                        ->visible(fn (CompletionReport $record): bool => $record->status === CompletionReport::STATUS_PENDING),
                ]),
            ])
            ->emptyStateIcon('heroicon-o-document-check')
            ->emptyStateHeading(__('completion_report.no_completion_reports'))
            ->emptyStateActions([
                Tables\Actions\CreateAction::make()
                    ->label(__('completion_report.create_completion_report'))
                    ->icon('heroicon-o-plus')
                    ->mutateFormDataUsing(function (array $data): array {
                        $data['project_charter_deliverable_id'] = $this->getOwnerRecord()->id;

                        return $data;
                    })
                    ->before(function (array $data, Tables\Actions\CreateAction $action) {
                        // Create a temporary completion report for validation
                        $completionReport = new \App\Models\CompletionReport;
                        $completionReport->fill($data);
                        $completionReport->projectCharterDeliverable()->associate($this->getOwnerRecord());

                        $validation = $completionReport->validateValueAgainstDeliverableEstimatedCost();

                        if (! $validation['success']) {
                            \Filament\Notifications\Notification::make()
                                ->title(__('completion_report.validation_failed'))
                                ->body($validation['message'])
                                ->danger()
                                ->send();

                            $action->halt();
                        }
                    })
                    ->successNotificationTitle(__('completion_report.created_successfully')),
            ])
            ->defaultSort('created_at', 'desc');
    }
}
