<?php

declare(strict_types=1);

namespace App\Filament\Resources\Producers\Tables;

use App\Filament\Support\SelectOptionLabels;

use App\Models\Producer;
use Filament\Actions\Action;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Actions\ForceDeleteBulkAction;
use Filament\Actions\RestoreBulkAction;
use Filament\Forms\Components\Textarea;
use Filament\Notifications\Notification;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Filters\TrashedFilter;
use Filament\Tables\Table;

class ProducersTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->modifyQueryUsing(fn ($query) => $query->with(['user', 'province']))
            ->defaultSort('created_at', 'desc')
            ->columns([
                TextColumn::make('brand_name')
                    ->label('نام برند')
                    ->searchable()
                    ->sortable(),
                TextColumn::make('user.first_name')
                    ->label('نام')
                    ->searchable(),
                TextColumn::make('user.cellphone')
                    ->label('موبایل')
                    ->searchable(),
                TextColumn::make('activity_main_category')
                    ->label('دسته اصلی')
                    ->searchable(),
                TextColumn::make('status')
                    ->label('وضعیت')
                    ->badge()
                    ->sortable()
                    ->formatStateUsing(fn (?string $state) => Producer::statusOptions()[$state] ?? $state ?? '-')
                    ->color(fn (?string $state) => match ($state) {
                        Producer::STATUS_APPROVED => 'success',
                        Producer::STATUS_PENDING => 'warning',
                        Producer::STATUS_NEEDS_EDIT => 'info',
                        Producer::STATUS_REJECTED, Producer::STATUS_BLOCKED => 'danger',
                        default => 'gray',
                    }),
                TextColumn::make('admin_reason')->label('دلیل ادمین')->limit(30)->toggleable()->toggledHiddenByDefault(),
                TextColumn::make('province.name')->label('استان')->toggleable(),
                TextColumn::make('created_at')->label('تاریخ')->jalaliDateTime('Y/m/d')->sortable(),
            ])
            ->filters([
                TrashedFilter::make(),
                SelectFilter::make('status')->label('وضعیت')->options(Producer::statusOptions()),
                SelectFilter::make('work_province_id')
                    ->label('استان')
                    ->relationship('province', 'name')
                    ->getOptionLabelFromRecordUsing(fn ($record) => SelectOptionLabels::generic($record, 'name', 'استان'))
                    ->searchable()
                    ->preload(),
            ])
            ->recordActions([
                EditAction::make(),
                Action::make('approve')
                    ->label('تایید')
                    ->icon('heroicon-o-check')
                    ->color('success')
                    ->visible(fn (Producer $p) => $p->status !== Producer::STATUS_APPROVED)
                    ->action(function (Producer $record): void {
                        $record->update([
                            'status' => Producer::STATUS_APPROVED,
                            'admin_reason' => null,
                            'reviewed_by' => auth()->id(),
                            'reviewed_at' => now(),
                        ]);
                        $record->user?->syncRoles([\App\Models\User::ROLE_PRODUCER, \App\Models\User::ROLE_USER]);
                        $record->user?->update(['account_type' => \App\Models\User::ACCOUNT_PRODUCER]);
                        Notification::make()->title('تولیدکننده تایید شد.')->success()->send();
                    }),
                Action::make('reject')
                    ->label('رد')
                    ->icon('heroicon-o-x-mark')
                    ->color('danger')
                    ->visible(fn (Producer $p) => $p->status === Producer::STATUS_PENDING)
                    ->form([Textarea::make('admin_reason')->label('دلیل رد')->required()->rows(3)])
                    ->action(function (Producer $record, array $data): void {
                        $record->update([
                            'status' => Producer::STATUS_REJECTED,
                            'admin_reason' => $data['admin_reason'],
                            'reviewed_by' => auth()->id(),
                            'reviewed_at' => now(),
                        ]);
                        Notification::make()->title('تولیدکننده رد شد.')->warning()->send();
                    }),
                Action::make('needs_edit')
                    ->label('نیاز به ویرایش')
                    ->icon('heroicon-o-pencil-square')
                    ->color('warning')
                    ->visible(fn (Producer $p) => $p->status === Producer::STATUS_PENDING)
                    ->form([Textarea::make('admin_reason')->label('موارد اصلاح')->required()->rows(3)])
                    ->action(function (Producer $record, array $data): void {
                        $record->update([
                            'status' => Producer::STATUS_NEEDS_EDIT,
                            'admin_reason' => $data['admin_reason'],
                            'reviewed_by' => auth()->id(),
                            'reviewed_at' => now(),
                        ]);
                        Notification::make()->title('برای ویرایش ارجاع شد.')->warning()->send();
                    }),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                    ForceDeleteBulkAction::make(),
                    RestoreBulkAction::make(),
                ]),
            ]);
    }
}
