<?php

namespace App\Filament\AssociationAdmin\Resources\AssociationWellLicenseResource\RelationManagers;

use App\Models\LicenseRequirement;
use Filament\Forms;
use Filament\Forms\Components\SpatieMediaLibraryFileUpload;
use Filament\Forms\Form;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables;
use Filament\Tables\Table;
use Hugomyb\FilamentMediaAction\Tables\Actions\MediaAction;
use Illuminate\Support\Facades\Auth;

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_well::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')),
                        ]),
                ]),
            ])
            ->bulkActions([
            ]);
    }

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