<?php

namespace App\Filament\Resources\StationLicenseResource\RelationManagers;

use App\Models\LicenseRequirement;
use App\Services\PdfMergerService;
use Filament\Forms;
use Filament\Forms\Components\SpatieMediaLibraryFileUpload;
use Filament\Forms\Form;
use Filament\Notifications\Notification;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Table;
use Hugomyb\FilamentMediaAction\Tables\Actions\MediaAction;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class RequirementsRelationManager extends RelationManager
{
    protected static string $relationship = 'requirements';

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

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

    public static function getPluralModelLabel(): string
    {
        return __('license_requirement.requirements');
    }

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

                Forms\Components\Hidden::make('status')
                    ->default(LicenseRequirement::STATUS_PENDING),

                SpatieMediaLibraryFileUpload::make('requirement_file')
                    ->label(__('license_requirement.requirement_file'))
                    ->collection('requirement_file')
                    ->visibility('private')
                    ->directory('license-requirements')
                    ->acceptedFileTypes([
                        'application/pdf',
                    ])
                    ->downloadable()
                    ->maxSize(10240) // 10MB
                    ->helperText(__('license_requirement.file_upload_helper')),
            ]);
    }

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

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

                Tables\Columns\TextColumn::make('file_status')
                    ->label(__('license_requirement.file'))
                    ->getStateUsing(function (LicenseRequirement $record) {
                        return $record->hasRequirementFile() ? __('common.download') : __('license_requirement.no_file');
                    })
                    ->badge()
                    ->color(
                        fn (LicenseRequirement $record) => $record->hasRequirementFile() ? 'success' : 'gray'
                    )
                    ->action(
                        MediaAction::make('file')
                            ->label(__('license_requirement.file'))
                            ->iconButton()
                            ->icon('heroicon-o-document')
                            ->media(
                                fn (LicenseRequirement $record) => $record->requirement_file_url ?: null
                            )
                            ->disabled(fn (LicenseRequirement $record) => ! $record->hasRequirementFile())
                            ->extraModalFooterActions([
                                Tables\Actions\Action::make('open-url')
                                    ->label(__('common.download'))
                                    ->url(fn ($record) => $record->requirement_file_url)
                                    ->openUrlInNewTab(),
                            ])
                    ),

                Tables\Columns\TextColumn::make('created_at')
                    ->label(__('license_requirement.created_at'))
                    ->date()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: false),

                Tables\Columns\TextColumn::make('latest_file_upload_date')
                    ->label(__('license_requirement.latest_file_upload'))
                    ->date()
                    ->toggleable(isToggledHiddenByDefault: false),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('status')
                    ->options(LicenseRequirement::getStatuses())
                    ->label(__('license_requirement.status')),
            ])
            ->headerActions([
                Tables\Actions\CreateAction::make(),
            ])
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\EditAction::make()
                        ->visible(fn () => Auth::user()?->can('upload_license_requirement_file_station::license'))
                        ->form([
                            SpatieMediaLibraryFileUpload::make('requirement_file')
                                ->label(__('license_requirement.requirement_file'))
                                ->collection('requirement_file')
                                ->visibility('private')
                                ->directory('license-requirements')
                                ->acceptedFileTypes([
                                    'application/pdf',
                                ])
                                ->downloadable()
                                ->maxSize(10240) // 10MB
                                ->helperText(__('license_requirement.file_upload_helper'))
                                ->disabled((fn (LicenseRequirement $record) => $record->is_locked)),
                        ]),

                    Tables\Actions\Action::make('accept')
                        ->label(__('license_requirement.accept'))
                        ->icon('heroicon-o-check-circle')
                        ->color('success')
                        ->visible(
                            fn (LicenseRequirement $record) => $record->status !== LicenseRequirement::STATUS_ACCEPTED &&
                                $record->status !== LicenseRequirement::STATUS_REJECTED &&
                                Auth::user()?->can('accept_license_requirement_station::license')
                        )
                        ->form([
                            Forms\Components\Textarea::make('notes')
                                ->label(__('license_requirement.notes'))
                                ->placeholder(__('license_requirement.acceptance_notes'))
                                ->rows(3),
                        ])
                        ->action(function (LicenseRequirement $record, array $data): void {
                            $record->accept($data['notes'] ?? '');

                            Notification::make()
                                ->title(__('license_requirement.accepted_successfully'))
                                ->success()
                                ->send();
                        }),

                    Tables\Actions\Action::make('reject')
                        ->label(__('license_requirement.reject'))
                        ->icon('heroicon-o-x-circle')
                        ->color('danger')
                        ->visible(
                            fn (LicenseRequirement $record) => $record->status !== LicenseRequirement::STATUS_REJECTED &&
                                $record->status !== LicenseRequirement::STATUS_ACCEPTED &&
                                Auth::user()?->can('reject_license_requirement_station::license')
                        )
                        ->form([
                            Forms\Components\Textarea::make('notes')
                                ->label(__('license_requirement.notes'))
                                ->placeholder(__('license_requirement.rejection_reason'))
                                ->required()
                                ->rows(3),
                        ])
                        ->action(function (LicenseRequirement $record, array $data): void {
                            $record->reject($data['notes'] ?? '');

                            Notification::make()
                                ->title(__('license_requirement.rejected_successfully'))
                                ->success()
                                ->send();
                        }),

                    Tables\Actions\Action::make('ask_modification')
                        ->label(__('license_requirement.ask_modification'))
                        ->icon('heroicon-o-pencil-square')
                        ->color('info')
                        ->visible(
                            fn (LicenseRequirement $record) => $record->status !== LicenseRequirement::STATUS_ASK_MODIFICATION &&
                                $record->status !== LicenseRequirement::STATUS_ACCEPTED &&
                                $record->status !== LicenseRequirement::STATUS_REJECTED &&
                                Auth::user()?->can('ask_modification_license_requirement_station::license')
                        )
                        ->form([
                            Forms\Components\Textarea::make('notes')
                                ->label(__('license_requirement.notes'))
                                ->placeholder(__('license_requirement.modification_details'))
                                ->required()
                                ->rows(3),
                        ])
                        ->action(function (LicenseRequirement $record, array $data): void {
                            $record->askModification($data['notes'] ?? '');

                            Notification::make()
                                ->title(__('license_requirement.modification_requested_successfully'))
                                ->success()
                                ->send();
                        }),

                    Tables\Actions\DeleteAction::make()
                        ->visible(fn (LicenseRequirement $record) => Auth::user()?->can('delete_license_requirement_station::license') && ! $record->is_locked
                        ),
                ]),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\BulkAction::make('export_pdfs')
                        ->label(__('license_requirement.export_pdfs'))
                        ->icon('heroicon-o-document-arrow-down')
                        ->color('info')
                        ->requiresConfirmation()
                        ->modalHeading(__('license_requirement.export_pdfs_confirm_title'))
                        ->modalDescription(__('license_requirement.export_pdfs_confirm_message'))
                        ->action(function (Collection $records) {
                            return $this->exportRequirementsPdfs($records);
                        }),
                    Tables\Actions\DeleteBulkAction::make()
                        ->visible(fn () => Auth::user()?->can('delete_license_requirement_station::license')),
                ]),
            ]);
    }

    /**
     * Export selected requirements as a merged PDF
     */
    public function exportRequirementsPdfs(Collection $records)
    {
        $pdfFiles = LicenseRequirement::collectPdfFiles($records);

        if (empty($pdfFiles)) {
            Notification::make()
                ->title(__('license_requirement.no_pdfs_found'))
                ->body(__('license_requirement.no_pdfs_to_export'))
                ->warning()
                ->send();

            return;
        }

        try {
            $stationLicense = $this->getOwnerRecord();
            $filename = "station_license_{$stationLicense->id}_requirements.pdf";
            $mergedPdfPath = PdfMergerService::mergePdfs($pdfFiles, $filename);

            return response()->download($mergedPdfPath, $filename)->deleteFileAfterSend(true);
        } catch (\Exception $e) {
            Notification::make()
                ->title(__('license_requirement.export_failed'))
                ->body(__('license_requirement.export_error_message'))
                ->danger()
                ->send();

            Log::error('PDF export failed', ['error' => $e->getMessage()]);

            return;
        }
    }

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