<?php

namespace App\Filament\Resources;

use App\Filament\Clusters\DailyOps\DailyOpsCluster;
use App\Filament\Resources\PhotoResource\Pages;
use App\Models\Event;
use App\Models\Photo;
use App\Services\Audit\SuperAdminAuditLogger;
use BackedEnum;
use Filament\Actions;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\KeyValue;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Collection;
use UnitEnum;

class PhotoResource extends Resource
{
    protected static ?string $model = Photo::class;

    protected static ?string $cluster = DailyOpsCluster::class;

    protected static BackedEnum|string|null $navigationIcon = 'heroicon-o-photo';

    protected static UnitEnum|string|null $navigationGroup = null;

    protected static ?int $navigationSort = 30;

    public static function getNavigationGroup(): UnitEnum|string|null
    {
        return __('admin.nav.events');
    }

    public static function form(Schema $form): Schema
    {
        return $form->schema([
            Select::make('event_id')
                ->label(__('admin.photos.fields.event'))
                ->options(Event::query()->orderBy('name')->pluck('name', 'id'))
                ->searchable()
                ->required(),
            FileUpload::make('file_path')
                ->label(__('admin.photos.fields.photo'))
                ->image()
                ->disk('public')
                ->directory('photos')
                ->visibility('public')
                ->required(),
            Toggle::make('is_featured')
                ->label(__('admin.photos.fields.is_featured'))
                ->default(false),
            KeyValue::make('metadata')
                ->label(__('admin.photos.fields.metadata'))
                ->keyLabel(__('admin.common.key'))
                ->valueLabel(__('admin.common.value')),
        ])->columns(2);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\ImageColumn::make('file_path')
                    ->label(__('admin.photos.table.photo'))
                    ->disk('public')
                    ->visibility('public'),
                Tables\Columns\TextColumn::make('id')->sortable(),
                Tables\Columns\TextColumn::make('event.name')
                    ->label(__('admin.photos.table.event'))
                    ->searchable(),
                Tables\Columns\TextColumn::make('likes_count')->label(__('admin.photos.table.likes')),
                Tables\Columns\IconColumn::make('is_featured')->boolean(),
                Tables\Columns\TextColumn::make('created_at')->since(),
            ])
            ->filters([])
            ->actions([
                Actions\EditAction::make()
                    ->after(fn (array $data, Photo $record) => app(SuperAdminAuditLogger::class)->recordModelMutation(
                        'updated',
                        $record,
                        SuperAdminAuditLogger::fieldsMetadata($data),
                        static::class
                    )),
                Actions\Action::make('feature')
                    ->label(__('admin.photos.actions.feature'))
                    ->visible(fn (Photo $record) => ! $record->is_featured)
                    ->action(function (Photo $record): void {
                        $record->update(['is_featured' => true]);

                        app(SuperAdminAuditLogger::class)->record(
                            'photo.featured',
                            $record,
                            SuperAdminAuditLogger::fieldsMetadata(['is_featured']),
                            source: static::class
                        );
                    })
                    ->icon('heroicon-o-star'),
                Actions\Action::make('unfeature')
                    ->label(__('admin.photos.actions.unfeature'))
                    ->visible(fn (Photo $record) => $record->is_featured)
                    ->action(function (Photo $record): void {
                        $record->update(['is_featured' => false]);

                        app(SuperAdminAuditLogger::class)->record(
                            'photo.unfeatured',
                            $record,
                            SuperAdminAuditLogger::fieldsMetadata(['is_featured']),
                            source: static::class
                        );
                    })
                    ->icon('heroicon-o-star'),
                Actions\DeleteAction::make()
                    ->after(fn (Photo $record) => app(SuperAdminAuditLogger::class)->recordModelMutation(
                        'deleted',
                        $record,
                        source: static::class
                    )),
            ])
            ->bulkActions([
                Actions\BulkAction::make('feature')
                    ->label(__('admin.photos.actions.feature_selected'))
                    ->icon('heroicon-o-star')
                    ->action(function ($records): void {
                        $records->each->update(['is_featured' => true]);

                        $logger = app(SuperAdminAuditLogger::class);

                        foreach ($records as $record) {
                            $logger->record(
                                'photo.featured',
                                $record,
                                SuperAdminAuditLogger::fieldsMetadata(['is_featured']),
                                source: static::class
                            );
                        }
                    }),
                Actions\BulkAction::make('unfeature')
                    ->label(__('admin.photos.actions.unfeature_selected'))
                    ->icon('heroicon-o-star')
                    ->action(function ($records): void {
                        $records->each->update(['is_featured' => false]);

                        $logger = app(SuperAdminAuditLogger::class);

                        foreach ($records as $record) {
                            $logger->record(
                                'photo.unfeatured',
                                $record,
                                SuperAdminAuditLogger::fieldsMetadata(['is_featured']),
                                source: static::class
                            );
                        }
                    }),
                Actions\DeleteBulkAction::make()
                    ->after(function (Collection $records): void {
                        $logger = app(SuperAdminAuditLogger::class);

                        foreach ($records as $record) {
                            $logger->recordModelMutation(
                                'deleted',
                                $record,
                                source: static::class
                            );
                        }
                    }),
            ]);
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListPhotos::route('/'),
            'view' => Pages\ViewPhoto::route('/{record}'),
            'edit' => Pages\EditPhoto::route('/{record}/edit'),
        ];
    }
}
