<?php

declare(strict_types=1);

namespace App\Filament\Resources\MediaItems\Tables;

use App\Filament\Support\SelectOptionLabels;

use App\Models\MediaItem;
use App\Models\MediaCategory;
use Filament\Actions\ViewAction;
use Filament\Actions\EditAction;
use Filament\Actions\Action;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Textarea;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\ImageColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\TrashedFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Filament\Notifications\Notification;

class MediaItemsTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->modifyQueryUsing(fn (Builder $query): Builder => $query->with(['project', 'category', 'subcategory']))
            ->defaultSort('created_at', 'desc')
            ->columns([
                ImageColumn::make('file_path')
                    ->label('پیش‌نمایش')
                    ->disk('public')
                    ->visibility('public')
                    ->circular()
                    ->getStateUsing(fn (MediaItem $record): ?string => $record->type === MediaItem::TYPE_IMAGE && $record->file_path ? $record->file_path : null),
                TextColumn::make('name')->label('نام')->searchable()->sortable()->limit(30)->placeholder('-'),
                TextColumn::make('project.name')->label('پروژه')->searchable()->placeholder('-'),
                TextColumn::make('type')
                    ->label('نوع فایل')
                    ->badge()
                    ->formatStateUsing(fn (?string $state) => MediaItem::typeOptions()[$state] ?? $state ?? '-'),
                TextColumn::make('category.name')->label('دسته‌بندی')->placeholder('-'),
                TextColumn::make('subcategory.name')->label('زیردسته')->placeholder('-'),
                TextColumn::make('uploader_type')
                    ->label('ارسال‌کننده')
                    ->badge()
                    ->color('gray')
                    ->formatStateUsing(fn (?string $state) => MediaItem::uploaderTypeOptions()[$state] ?? $state ?? '-'),
                TextColumn::make('status')
                    ->label('وضعیت')
                    ->badge()
                    ->formatStateUsing(fn (?string $state) => MediaItem::statusOptions()[$state] ?? $state ?? '-')
                    ->color(fn (?string $state) => match ($state) {
                        MediaItem::STATUS_APPROVED => 'success',
                        MediaItem::STATUS_REJECTED => 'danger',
                        MediaItem::STATUS_NEEDS_EDIT => 'warning',
                        default => 'gray',
                    })
                    ->sortable(),
                TextColumn::make('created_at')->label('تاریخ')->jalaliDateTime('Y/m/d H:i')->sortable(),
            ])
            ->filters([
                TrashedFilter::make(),
                Filter::make('date_range')
                    ->label('تاریخ')
                    ->form([
                        DatePicker::make('date_from')->label('از')->jalali(),
                        DatePicker::make('date_to')->label('تا')->jalali(),
                    ])
                    ->query(function (Builder $q, array $data): Builder {
                        if (filled($data['date_from'] ?? null)) {
                            $q->whereDate('created_at', '>=', $data['date_from']);
                        }
                        if (filled($data['date_to'] ?? null)) {
                            $q->whereDate('created_at', '<=', $data['date_to']);
                        }
                        return $q;
                    }),
                SelectFilter::make('type')
                    ->label('نوع فایل')
                    ->options(MediaItem::typeOptions()),
                SelectFilter::make('uploader_type')
                    ->label('ارسال‌کننده')
                    ->options(MediaItem::uploaderTypeOptions()),
                SelectFilter::make('status')
                    ->label('وضعیت')
                    ->options(MediaItem::statusOptions()),
                SelectFilter::make('project_id')
                    ->label('پروژه')
                    ->relationship('project', 'name')
                    ->getOptionLabelFromRecordUsing(fn ($record) => SelectOptionLabels::project($record))
                    ->searchable()
                    ->preload(),
                SelectFilter::make('category_id')
                    ->label('دسته‌بندی')
                    ->options(fn () => SelectOptionLabels::mediaCategoryOptions(
                        MediaCategory::query()->whereNull('parent_id')
                    ))
                    ->searchable(),
            ])
            ->recordActions([
                ViewAction::make()->label('مشاهده'),
                Action::make('approve')
                    ->label('تایید')
                    ->icon('heroicon-o-check')
                    ->color('success')
                    ->visible(fn (MediaItem $record) => $record->status === MediaItem::STATUS_PENDING)
                    ->action(function (MediaItem $record): void {
                        $record->update(['status' => MediaItem::STATUS_APPROVED, 'admin_reason' => null]);
                        Notification::make()->title('فایل تایید شد.')->success()->send();
                    }),
                Action::make('reject')
                    ->label('رد')
                    ->icon('heroicon-o-x-mark')
                    ->color('danger')
                    ->visible(fn (MediaItem $record) => $record->status === MediaItem::STATUS_PENDING)
                    ->form([Textarea::make('admin_reason')->label('دلیل رد')->required()->rows(2)])
                    ->action(function (MediaItem $record, array $data): void {
                        $record->update([
                            'status' => MediaItem::STATUS_REJECTED,
                            'admin_reason' => $data['admin_reason'],
                        ]);
                        Notification::make()->title('فایل رد شد.')->warning()->send();
                    }),
                Action::make('needs_edit')
                    ->label('درخواست ویرایش')
                    ->icon('heroicon-o-pencil-square')
                    ->color('warning')
                    ->visible(fn (MediaItem $record) => $record->status === MediaItem::STATUS_PENDING)
                    ->form([Textarea::make('admin_reason')->label('دلیل و موارد اصلاح')->required()->rows(2)])
                    ->action(function (MediaItem $record, array $data): void {
                        $record->update([
                            'status' => MediaItem::STATUS_NEEDS_EDIT,
                            'admin_reason' => $data['admin_reason'],
                        ]);
                        Notification::make()->title('درخواست ویرایش ارسال شد.')->warning()->send();
                    }),
                EditAction::make(),
            ])
            ->defaultSort('created_at', 'desc');
    }
}
