<?php

declare(strict_types=1);

namespace App\Filament\Resources\Discussions\Tables;

use App\Filament\Support\SelectOptionLabels;

use App\Models\Discussion;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
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 DiscussionsTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->modifyQueryUsing(fn (Builder $query): Builder => $query->with([
                'project',
                'messages' => fn ($query) => $query->latest()->limit(1),
            ]))
            ->defaultSort('created_at', 'desc')
            ->columns([
                TextColumn::make('title')->label('نام')->searchable()->sortable()->limit(40),
                TextColumn::make('hashtag')->label('هشتگ')->badge()->placeholder('-')->searchable(),
                TextColumn::make('project.name')->label('پروژه')->searchable()->sortable()->placeholder('-'),
                TextColumn::make('createdBy.getFilamentName')->label('ایجادکننده')->hidden()->getStateUsing(fn (Discussion $record) => $record->createdBy?->getFilamentName())->toggleable(),
                TextColumn::make('messages_count')->label('پیام‌ها')->counts('messages')->sortable(),
                TextColumn::make('last_message_at')
                    ->label('آخرین پیام')
                    ->getStateUsing(fn (Discussion $record) => $record->messages->first()?->created_at)
                    ->jalaliDateTime('Y/m/d H:i')
                    ->placeholder('-')
                    ->toggleable(),
                TextColumn::make('status')->label('وضعیت')->badge()->formatStateUsing(fn (string $state) => match ($state) {
                    Discussion::STATUS_ACTIVE => 'فعال',
                    Discussion::STATUS_ENDED => 'پایان‌یافته',
                    Discussion::STATUS_DELETED => 'حذف شده',
                    default => $state,
                })->color(fn (string $state) => match ($state) {
                    Discussion::STATUS_ACTIVE => 'success',
                    Discussion::STATUS_ENDED => 'gray',
                    Discussion::STATUS_DELETED => 'danger',
                    default => 'gray',
                })->sortable(),
                TextColumn::make('created_at')->label('تاریخ ایجاد')->jalaliDateTime('Y/m/d H:i')->sortable(),
            ])
            ->filters([
                SelectFilter::make('project_id')
                    ->label('پروژه')
                    ->relationship('project', 'name')
                    ->getOptionLabelFromRecordUsing(fn ($record) => SelectOptionLabels::project($record))
                    ->searchable()
                    ->preload(),
                Filter::make('hashtag')
                    ->form([\Filament\Forms\Components\TextInput::make('hashtag')->label('هشتگ')])
                    ->query(fn (Builder $q, array $data) => $q->when(
                        filled($data['hashtag'] ?? null),
                        fn (Builder $q) => $q->where('hashtag', 'like', '%' . $data['hashtag'] . '%')
                    )),
                SelectFilter::make('status')
                    ->label('وضعیت')
                    ->options([
                        Discussion::STATUS_ACTIVE => 'فعال',
                        Discussion::STATUS_ENDED => 'پایان‌یافته',
                        Discussion::STATUS_DELETED => 'حذف شده',
                    ]),
                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('end_discussion')
                    ->label('پایان بحث')
                    ->icon('heroicon-o-stop')
                    ->color('gray')
                    ->visible(fn (Discussion $record) => $record->status === Discussion::STATUS_ACTIVE)
                    ->requiresConfirmation()
                    ->action(function (Discussion $record): void {
                        $record->update(['status' => Discussion::STATUS_ENDED]);
                        Notification::make()->title('بحث پایان یافت.')->success()->send();
                    }),
                EditAction::make(),
                DeleteAction::make(),
            ])
            ->defaultSort('created_at', 'desc');
    }
}
