<?php

namespace App\Filament\Resources\Media\Tables;

use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Tables\Columns\ImageColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

class MediaTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->modifyQueryUsing(fn ($query) => $query->where('collection_name', '!=', 'avatars'))
            ->columns([
                ImageColumn::make('url')
                    ->label('Preview')
                    ->getStateUsing(fn ($record) =>
                        // Prefer the stored path produced by Filament's FileUpload (saved in custom_properties),
                        // fall back to Spatie's getUrl() when no stored_path exists.
                        ($record->getCustomProperty('stored_path'))
                            ? Storage::url($record->getCustomProperty('stored_path'))
                            : $record->getUrl()
                    )
                    ->height(40)
                    ->width(40),
                TextColumn::make('name')
                    ->searchable(),
                TextColumn::make('file_name')
                    ->searchable(),
                TextColumn::make('collection_name')
                    ->badge(),
                TextColumn::make('mime_type'),
                TextColumn::make('size')
                    ->formatStateUsing(fn ($state) => number_format($state / 1024, 2).' KB'),
                TextColumn::make('created_at')
                    ->dateTime(),
            ])
            ->filters([
                SelectFilter::make('collection_name')
                    ->options([
                        'images' => 'Images',
                        'documents' => 'Documents',
                    ]),
            ])
            ->recordActions([
                EditAction::make(),
                DeleteAction::make()
                    ->action(function (Media $record) {
                        // Delete the actual stored file path if we saved one, otherwise fall back to the Spatie path.
                        $stored = $record->getCustomProperty('stored_path');
                        if ($stored) {
                            Storage::disk($record->disk)->delete($stored);
                        } else {
                            Storage::disk($record->disk)->delete($record->getPath());
                        }

                        $record->delete();
                    }),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make()
                        ->action(function (Collection $records) {
                            $records->each(function (Media $record) {
                                $stored = $record->getCustomProperty('stored_path');
                                if ($stored) {
                                    Storage::disk($record->disk)->delete($stored);
                                } else {
                                    Storage::disk($record->disk)->delete($record->getPath());
                                }
                                $record->delete();
                            });
                        }),
                ]),
            ]);
    }
}
