<?php

declare(strict_types=1);

namespace App\Filament\Resources\SupportTickets\Tables;

use App\Models\SupportTicket;
use Filament\Actions\ViewAction;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\TextInput;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;

class SupportTicketsTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->modifyQueryUsing(fn (Builder $query): Builder => $query->with(['user'])->withCount('replies'))
            ->defaultSort('created_at', 'desc')
            ->columns([
                TextColumn::make('code')->label('کد')->searchable()->sortable(),
                TextColumn::make('title')->label('عنوان')->searchable()->sortable()->limit(40),
                TextColumn::make('category')
                    ->label('دسته')
                    ->formatStateUsing(fn ($state) => SupportTicket::categoryOptions()[(string) $state] ?? $state)
                    ->badge(),
                TextColumn::make('user.getFilamentName')
                    ->label('کاربر')
                    ->getStateUsing(fn (SupportTicket $record) => $record->user?->getFilamentName())
                    ->searchable(['user.first_name', 'user.last_name', 'user.cellphone', 'user.national_code', 'user.email'])
                    ->sortable(),
                TextColumn::make('status')
                    ->label('وضعیت')
                    ->badge()
                    ->formatStateUsing(fn (?string $state) => SupportTicket::statusOptions()[(string) $state] ?? $state)
                    ->color(fn (?string $state) => match ($state) {
                        SupportTicket::STATUS_OPEN => 'warning',
                        SupportTicket::STATUS_CLOSED => 'gray',
                        SupportTicket::STATUS_READ => 'success',
                        SupportTicket::STATUS_UNREAD => 'danger',
                        default => 'gray',
                    })
                    ->sortable(),
                TextColumn::make('replies_count')->label('پاسخ‌ها')->counts('replies')->sortable(),
                TextColumn::make('closed_at')->label('بسته شده')->jalaliDateTime('Y/m/d H:i')->sortable()->toggleable(),
                TextColumn::make('created_at')->label('تاریخ')->jalaliDateTime('Y/m/d H:i')->sortable(),
            ])
            ->filters([
                SelectFilter::make('category')
                    ->label('دسته‌بندی موضوع')
                    ->options(SupportTicket::categoryOptions()),
                Filter::make('search')
                    ->label('جستجو')
                    ->schema([
                        TextInput::make('search')
                            ->label('نام کاربری، شماره ملی، شماره همراه، ایمیل')
                            ->placeholder('جستجو...'),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        if (blank($data['search'] ?? null)) {
                            return $query;
                        }

                        $search = (string) $data['search'];

                        return $query->where(function (Builder $scope) use ($search): void {
                            $scope->where('title', 'like', "%{$search}%")
                                ->orWhere('code', 'like', "%{$search}%")
                                ->orWhere('body', 'like', "%{$search}%")
                                ->orWhereHas('user', function (Builder $userQuery) use ($search): void {
                                    $userQuery->where('first_name', 'like', "%{$search}%")
                                        ->orWhere('last_name', 'like', "%{$search}%")
                                        ->orWhere('national_code', 'like', "%{$search}%")
                                        ->orWhere('cellphone', 'like', "%{$search}%")
                                        ->orWhere('email', 'like', "%{$search}%");
                                });
                        });
                    }),
                SelectFilter::make('status')
                    ->label('وضعیت')
                    ->options(SupportTicket::statusOptions()),
                Filter::make('date_range')
                    ->label('بازه زمانی')
                    ->schema([
                        DatePicker::make('date_from')->label('از تاریخ')->jalali(),
                        DatePicker::make('date_to')->label('تا تاریخ')->jalali(),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        if (filled($data['date_from'] ?? null)) {
                            $query->whereDate('created_at', '>=', $data['date_from']);
                        }

                        if (filled($data['date_to'] ?? null)) {
                            $query->whereDate('created_at', '<=', $data['date_to']);
                        }

                        return $query;
                    }),
            ])
            ->recordActions([
                ViewAction::make(),
            ])
            ->defaultSort('created_at', 'desc');
    }
}
