<?php

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

use App\Models\OrderRequirement;
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 AssociationRequirementsRelationManager extends RelationManager
{
    protected static string $relationship = 'requirements';

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

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

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

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

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

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

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

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

                Tables\Columns\TextColumn::make('file_status')
                    ->label(__('order_requirement.file'))
                    ->getStateUsing(function (OrderRequirement $record) {
                        return $record->hasRequirementFile() ? __('common.download') : __('order_requirement.no_file');
                    })
                    ->badge()
                    ->color(
                        fn (OrderRequirement $record) => $record->hasRequirementFile() ? 'success' : 'gray'
                    )
                    ->action(
                        MediaAction::make('file')
                            ->label(__('order_requirement.file'))
                            ->iconButton()
                            ->icon('heroicon-o-document')
                            ->media(
                                fn (OrderRequirement $record) => $record->requirement_file_url ?: null
                            )
                            ->disabled(fn (OrderRequirement $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(__('order_requirement.created_at'))
                    ->date()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('status')
                    ->options(OrderRequirement::getStatuses())
                    ->label(__('order_requirement.status')),
            ])
            ->headerActions([])
            ->actions([
                Tables\Actions\ActionGroup::make([
                    Tables\Actions\EditAction::make()
                        ->visible(fn () => Auth::user()?->can('upload_order_requirement_file_order'))
                        ->form([
                            SpatieMediaLibraryFileUpload::make('requirement_file')
                                ->label(__('order_requirement.requirement_file'))
                                ->collection('requirement_file')
                                ->visibility('private')
                                ->directory('order-requirements')
                                ->acceptedFileTypes([
                                    'application/pdf',
                                    'image/jpeg',
                                    'image/png',
                                    'image/jpg',
                                ])
                                ->downloadable()
                                ->maxSize(10240) // 10MB
                                ->helperText(__('order_requirement.file_upload_helper')),
                        ]),
                ]),
            ])
            ->bulkActions([]);
    }

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