<?php

declare(strict_types=1);

namespace App\Filament\Resources\Faqs\Tables;

use App\Filament\Support\SelectOptionLabels;

use App\Models\Faq;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Actions\ForceDeleteBulkAction;
use Filament\Actions\RestoreBulkAction;
use Filament\Actions\Action;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Textarea;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Filters\TrashedFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Filament\Notifications\Notification;

class FaqsTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('question')->label('پرسش')->limit(50)->searchable()->wrap(),
                TextColumn::make('response')->label('پاسخ')->limit(40)->wrap()->placeholder('-'),
                \App\Filament\Components\Table\ModelTypeTextColumn::create(),
                \App\Filament\Components\Table\ModelTextColumn::create(),
                TextColumn::make('status')->label('وضعیت')->badge()
                    ->formatStateUsing(fn (string $state) => match ($state) {
                        Faq::STATUS_PENDING => 'در انتظار',
                        Faq::STATUS_APPROVED => 'تایید',
                        Faq::STATUS_REJECTED => 'رد',
                        default => $state,
                    })
                    ->color(fn (string $state) => match ($state) {
                        Faq::STATUS_APPROVED => 'success',
                        Faq::STATUS_REJECTED => 'danger',
                        default => 'warning',
                    }),
                \App\Filament\Components\Table\OrderTextColumn::create(),
                \App\Filament\Components\Table\CreatedByTextColumn::create(),
                \App\Filament\Components\Table\CreatedAtTextColumn::create(),
            ])
            ->filters([
                TrashedFilter::make(),
                SelectFilter::make('status')
                    ->label('وضعیت')
                    ->options([
                        Faq::STATUS_PENDING => 'در انتظار',
                        Faq::STATUS_APPROVED => 'تایید',
                        Faq::STATUS_REJECTED => 'رد',
                    ]),
                SelectFilter::make('created_by')
                    ->label('کاربر')
                    ->relationship('createdBy', 'first_name')
                    ->searchable(['first_name', 'last_name', 'cellphone', 'national_code', 'email'])
                    ->getOptionLabelFromRecordUsing(fn ($record) => SelectOptionLabels::user($record)),
                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 (Faq $record) => $record->status !== Faq::STATUS_APPROVED)
                    ->form([Textarea::make('admin_note')->label('یادداشت')->rows(2)])
                    ->action(fn (Faq $record) => static::setStatus($record, Faq::STATUS_APPROVED)),
                Action::make('reject')
                    ->label('رد')
                    ->icon('heroicon-o-x-mark')
                    ->color('danger')
                    ->visible(fn (Faq $record) => $record->status !== Faq::STATUS_REJECTED)
                    ->form([Textarea::make('admin_note')->label('دلیل رد')->required()->rows(2)])
                    ->action(fn (Faq $record, array $data) => static::setStatus($record, Faq::STATUS_REJECTED, $data['admin_note'] ?? null)),
                EditAction::make(),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                    ForceDeleteBulkAction::make(),
                    RestoreBulkAction::make(),
                ]),
            ]);
    }

    private static function setStatus(Faq $record, string $status, ?string $note = null): void
    {
        $record->update(['status' => $status]);
        Notification::make()->title($status === Faq::STATUS_APPROVED ? 'پرسش تایید شد.' : 'پرسش رد شد.')->success()->send();
    }
}
