<?php

namespace App\Filament\Resources\OrderResource\RelationManagers;

use App\Models\OrderRequirement;
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\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 __('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([
                Tables\Actions\CreateAction::make(),
                // ->visible(fn() => Auth::user()?->can('create_order_requirement')),
            ])
            ->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')),
                        ]),

                    // Tables\Actions\Action::make('download_file')
                    //     ->label(__('order_requirement.download_file'))
                    //     ->icon('heroicon-o-arrow-down-tray')
                    //     ->color('info')
                    //     ->visible(fn(OrderRequirement $record) => $record->getMedia('requirement_file')->count() > 0)
                    //     ->action(function (OrderRequirement $record) {
                    //         $media = $record->getFirstMedia('requirement_file');
                    //         if ($media) {
                    //             return response()->download($media->getPath(), $media->name);
                    //         }
                    //     })
                    //     ->openUrlInNewTab(),

                    Tables\Actions\Action::make('accept')
                        ->label(__('order_requirement.accept'))
                        ->icon('heroicon-o-check-circle')
                        ->color('success')
                        ->visible(
                            fn (OrderRequirement $record) => $record->status !== OrderRequirement::STATUS_ACCEPTED &&
                                $record->status !== OrderRequirement::STATUS_REJECTED &&
                                Auth::user()?->can('accept_order_requirement_order')
                        )
                        ->form([])
                        ->action(function (OrderRequirement $record, array $data): void {
                            $isTechnicalFinancial = in_array($record->name, OrderRequirement::TECHNICAL_FINANCIAL_REQUIREMENTS);

                            $record->accept($data['notes'] ?? '');

                            Notification::make()
                                ->title(__('order_requirement.accepted_successfully'))
                                ->success()
                                ->send();

                            // Show additional notification for technical and financial requirements
                            if ($isTechnicalFinancial) {
                                Notification::make()
                                    ->title(__('order_requirement.others_auto_rejected'))
                                    ->warning()
                                    ->send();
                            }
                        }),

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

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

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

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

                    Tables\Actions\DeleteAction::make()
                        ->visible(fn () => Auth::user()?->can('delete_order_requirement_order')),
                ]),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make()
                        ->visible(fn () => Auth::user()?->can('delete_order_requirement_order')),
                ]),
            ]);
    }

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