<?php

declare(strict_types=1);

namespace App\Filament\Resources\Comments\Tables;

use App\Filament\Support\SelectOptionLabels;

use App\Models\Comment;
use App\Models\Project;
use App\Models\Product;
use Filament\Actions\DeleteAction;
use Filament\Actions\Action;
use Filament\Forms\Components\DatePicker;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Filament\Notifications\Notification;

class CommentsTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->modifyQueryUsing(fn (Builder $query): Builder => $query->with(['user', 'commentable']))
            ->defaultSort('created_at', 'desc')
            ->columns([
                TextColumn::make('body')->label('متن')->limit(60)->wrap()->searchable(),
                TextColumn::make('commentable_type')->label('موضوع')->badge()->formatStateUsing(fn ($state) => match ($state) {
                    Project::class => 'پروژه',
                    Product::class => 'محصول',
                    default => class_basename($state ?? '') ?: '-',
                }),
                TextColumn::make('commentable_id')->label('شناسه موضوع')->sortable(),
                TextColumn::make('user.getFilamentName')->label('کاربر')->getStateUsing(fn (Comment $record) => $record->user?->getFilamentName())->searchable(['user.first_name', 'user.last_name', 'user.cellphone', 'user.national_code', 'user.email'])->sortable(),
                TextColumn::make('category')->label('دسته')->placeholder('-'),
                TextColumn::make('status')->label('وضعیت')->badge()->formatStateUsing(fn (string $state) => match ($state) {
                    Comment::STATUS_APPROVED => 'تایید',
                    Comment::STATUS_REJECTED => 'رد',
                    Comment::STATUS_BLOCKED => 'بلاک',
                    default => $state,
                })->color(fn (string $state) => match ($state) {
                    Comment::STATUS_APPROVED => 'success',
                    Comment::STATUS_REJECTED => 'danger',
                    Comment::STATUS_BLOCKED => 'gray',
                    default => 'gray',
                }),
                TextColumn::make('created_at')->label('تاریخ')->jalaliDateTime('Y/m/d H:i')->sortable(),
            ])
            ->filters([
                SelectFilter::make('commentable_type')
                    ->label('موضوع دسته‌بندی')
                    ->options([
                        Project::class => 'پروژه',
                        Product::class => 'محصول',
                    ]),
                SelectFilter::make('user_id')
                    ->label('کاربر')
                    ->relationship('user', 'first_name')
                    ->searchable(['first_name', 'last_name', 'cellphone', 'national_code', 'email'])
                    ->getOptionLabelFromRecordUsing(fn ($record) => SelectOptionLabels::user($record)),
                SelectFilter::make('status')
                    ->label('وضعیت')
                    ->options([
                        Comment::STATUS_APPROVED => 'تایید',
                        Comment::STATUS_REJECTED => 'رد',
                        Comment::STATUS_BLOCKED => 'بلاک',
                    ]),
                Filter::make('date_range')
                    ->label('بازه زمانی')
                    ->schema([
                        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;
                    }),
            ])
            ->recordActions([
                Action::make('approve')
                    ->label('تأیید')
                    ->icon('heroicon-o-check')
                    ->color('success')
                    ->visible(fn (Comment $record) => $record->status !== Comment::STATUS_APPROVED)
                    ->action(function (Comment $record): void {
                        $record->update(['status' => Comment::STATUS_APPROVED]);
                        Notification::make()->title('کامنت تأیید شد.')->success()->send();
                    }),
                Action::make('reject')
                    ->label('رد')
                    ->icon('heroicon-o-x-mark')
                    ->color('danger')
                    ->visible(fn (Comment $record) => $record->status !== Comment::STATUS_REJECTED)
                    ->action(function (Comment $record): void {
                        $record->update(['status' => Comment::STATUS_REJECTED]);
                        Notification::make()->title('کامنت رد شد.')->warning()->send();
                    }),
                Action::make('block_user')
                    ->label('بلاک کاربر')
                    ->icon('heroicon-o-no-symbol')
                    ->color('danger')
                    ->visible(fn (Comment $record) => $record->status !== Comment::STATUS_BLOCKED)
                    ->requiresConfirmation()
                    ->action(function (Comment $record): void {
                        $record->update(['status' => Comment::STATUS_BLOCKED]);
                        Notification::make()->title('کاربر از ارسال کامنت نامناسب بلاک شد.')->warning()->send();
                    }),
                DeleteAction::make(),
            ])
            ->defaultSort('created_at', 'desc');
    }
}
