<?php

declare(strict_types=1);

namespace App\Filament\Resources\ConsultationRequests\Tables;

use App\Filament\Support\SelectOptionLabels;

use App\Models\ConsultationRequest;
use Filament\Actions\ViewAction;
use Filament\Actions\Action;
use Filament\Forms\Components\Textarea;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Filament\Notifications\Notification;

class ConsultationRequestsTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->modifyQueryUsing(fn ($query) => $query->with(['producer', 'expert']))
            ->defaultSort('created_at', 'desc')
            ->columns([
                TextColumn::make('id')->label('#')->sortable(),
                TextColumn::make('producer.brand_name')
                    ->label('نام تولیدکننده')
                    ->searchable()
                    ->sortable()
                    ->placeholder('-'),
                TextColumn::make('expert.display_name')
                    ->label('نام خدمات‌دهنده انتخاب‌شده')
                    ->getStateUsing(fn (ConsultationRequest $record) => $record->expert?->display_name ?? '-')
                    ->searchable()
                    ->placeholder('-'),
                TextColumn::make('type')
                    ->label('نوع مشاوره')
                    ->badge()
                    ->formatStateUsing(fn (?string $state) => ConsultationRequest::typeOptions()[$state] ?? $state ?? '-'),
                TextColumn::make('format')
                    ->label('نحوه برگزاری')
                    ->badge()
                    ->color('gray')
                    ->formatStateUsing(fn (?string $state) => ConsultationRequest::formatOptions()[$state] ?? $state ?? '-'),
                TextColumn::make('priority')
                    ->label('اولویت')
                    ->badge()
                    ->formatStateUsing(fn (?string $state) => ConsultationRequest::priorityOptions()[$state] ?? $state ?? '-')
                    ->color(fn (?string $state) => match ($state) {
                        ConsultationRequest::PRIORITY_EMERGENCY => 'danger',
                        ConsultationRequest::PRIORITY_URGENT => 'warning',
                        ConsultationRequest::PRIORITY_LOW => 'gray',
                        default => 'info',
                    }),
                TextColumn::make('status')
                    ->label('وضعیت')
                    ->badge()
                    ->formatStateUsing(fn (?string $state) => ConsultationRequest::statusOptions()[$state] ?? $state ?? '-')
                    ->color(fn (?string $state) => match ($state) {
                        ConsultationRequest::STATUS_APPROVED => 'success',
                        ConsultationRequest::STATUS_REJECTED => 'danger',
                        ConsultationRequest::STATUS_CLOSED => 'gray',
                        default => 'warning',
                    })
                    ->sortable(),
                TextColumn::make('created_at')
                    ->label('تاریخ')
                    ->jalaliDateTime('Y/m/d H:i')
                    ->sortable(),
            ])
            ->filters([
                SelectFilter::make('status')
                    ->label('وضعیت')
                    ->options(ConsultationRequest::statusOptions()),
                SelectFilter::make('type')
                    ->label('نوع مشاوره')
                    ->options(ConsultationRequest::typeOptions()),
                SelectFilter::make('priority')
                    ->label('اولویت')
                    ->options(ConsultationRequest::priorityOptions()),
                SelectFilter::make('expert_id')
                    ->label('خدمات‌دهنده')
                    ->relationship('expert', 'brand_name')
                    ->getOptionLabelFromRecordUsing(fn ($record) => SelectOptionLabels::expert($record))
                    ->searchable()
                    ->preload(),
                SelectFilter::make('producer_id')
                    ->label('تولیدکننده')
                    ->relationship('producer', 'brand_name')
                    ->getOptionLabelFromRecordUsing(fn ($record) => SelectOptionLabels::producer($record))
                    ->searchable()
                    ->preload(),
            ])
            ->recordActions([
                ViewAction::make()->label('مشاهده جزئیات'),
                Action::make('approve')
                    ->label('تایید')
                    ->icon('heroicon-o-check')
                    ->color('success')
                    ->visible(fn (ConsultationRequest $record) => $record->status === ConsultationRequest::STATUS_PENDING)
                    ->action(function (ConsultationRequest $record): void {
                        $record->update(['status' => ConsultationRequest::STATUS_APPROVED]);
                        Notification::make()->title('درخواست تایید شد. پیام به خدمات‌دهنده ارسال می‌شود.')->success()->send();
                    }),
                Action::make('reject')
                    ->label('رد')
                    ->icon('heroicon-o-x-mark')
                    ->color('danger')
                    ->visible(fn (ConsultationRequest $record) => $record->status === ConsultationRequest::STATUS_PENDING)
                    ->form([Textarea::make('admin_notes')->label('دلیل رد (اختیاری)')->rows(2)])
                    ->action(function (ConsultationRequest $record, array $data): void {
                        $record->update([
                            'status' => ConsultationRequest::STATUS_REJECTED,
                            'admin_notes' => $data['admin_notes'] ?? null,
                        ]);
                        Notification::make()->title('درخواست رد شد.')->warning()->send();
                    }),
                Action::make('close')
                    ->label('بستن پرونده')
                    ->icon('heroicon-o-lock-closed')
                    ->color('gray')
                    ->visible(fn (ConsultationRequest $record) => $record->status === ConsultationRequest::STATUS_APPROVED)
                    ->form([Textarea::make('admin_notes')->label('یادداشت پایانی (اختیاری)')->rows(2)])
                    ->action(function (ConsultationRequest $record, array $data): void {
                        $record->update([
                            'status' => ConsultationRequest::STATUS_CLOSED,
                            'closed_at' => now(),
                            'closed_by' => \Illuminate\Support\Facades\Auth::id(),
                            'admin_notes' => ($record->admin_notes ?? '') . "\n" . ($data['admin_notes'] ?? ''),
                        ]);
                        Notification::make()->title('پرونده بسته شد.')->success()->send();
                    }),
            ]);
    }
}
