<?php

declare(strict_types=1);

namespace App\Filament\Resources\RationReports\Tables;

use App\Filament\Support\SelectOptionLabels;

use App\Models\Report;
use App\Models\Product;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Actions\ForceDeleteBulkAction;
use Filament\Actions\RestoreBulkAction;
use Filament\Actions\ViewAction;
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 RationReportsTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('date')
                    ->label('تاریخ')
                    ->jalaliDate('Y/m/d')
                    ->sortable(),
                TextColumn::make('project.name')
                    ->label('نام پروژه')
                    ->searchable()
                    ->sortable()
                    ->placeholder('-'),
                TextColumn::make('products_summary')
                    ->label('نام محصول تولیدی')
                    ->getStateUsing(fn (Report $record) => $record->items->loadMissing('product')->pluck('product.name')->filter()->join(', ') ?: '-'),
                TextColumn::make('producer.brand_name')
                    ->label('نام خدمات‌دهنده')
                    ->searchable()
                    ->sortable()
                    ->placeholder('-'),
                TextColumn::make('ration_type')
                    ->label('نوع جیره')
                    ->searchable()
                    ->placeholder('-'),
                TextColumn::make('workflow_status')
                    ->label('وضعیت')
                    ->badge()
                    ->formatStateUsing(fn (?string $state) => match ($state ?? '') {
                        Report::WORKFLOW_APPROVED => 'تایید',
                        Report::WORKFLOW_REJECTED => 'رد',
                        Report::WORKFLOW_NEEDS_EDIT => 'ویرایش',
                        default => 'انتظار',
                    })
                    ->color(fn (?string $state) => match ($state ?? '') {
                        Report::WORKFLOW_APPROVED => 'success',
                        Report::WORKFLOW_REJECTED => 'danger',
                        Report::WORKFLOW_NEEDS_EDIT => 'warning',
                        default => 'gray',
                    })
                    ->sortable(),
            ])
            ->filters([
                TrashedFilter::make(),
                SelectFilter::make('project_id')
                    ->label('پروژه')
                    ->relationship('project', 'name')
                    ->getOptionLabelFromRecordUsing(fn ($record) => SelectOptionLabels::project($record))
                    ->searchable()
                    ->preload(),
                SelectFilter::make('producer_id')
                    ->label('نام خدمات‌دهنده')
                    ->relationship('producer', 'brand_name')
                    ->getOptionLabelFromRecordUsing(fn ($record) => SelectOptionLabels::producer($record))
                    ->searchable()
                    ->preload(),
                SelectFilter::make('workflow_status')
                    ->label('وضعیت')
                    ->options([
                        Report::WORKFLOW_PENDING => 'انتظار',
                        Report::WORKFLOW_APPROVED => 'تایید',
                        Report::WORKFLOW_REJECTED => 'رد',
                        Report::WORKFLOW_NEEDS_EDIT => 'ویرایش',
                    ]),
                Filter::make('product_id')
                    ->label('نوع محصول')
                    ->form([
                        \Filament\Forms\Components\Select::make('product_id')
                            ->label('محصول')
                            ->options(fn () => SelectOptionLabels::productOptions())
                            ->searchable()
                            ->placeholder('همه'),
                    ])
                    ->query(function (Builder $q, array $data): Builder {
                        if (filled($data['product_id'] ?? null)) {
                            $q->whereHas('items', fn (Builder $q2) => $q2->where('product_id', $data['product_id']));
                        }
                        return $q;
                    }),
                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('date', '>=', $data['date_from']);
                        }
                        if (filled($data['date_to'] ?? null)) {
                            $q->whereDate('date', '<=', $data['date_to']);
                        }
                        return $q;
                    }),
            ])
            ->recordActions([
                ViewAction::make()->label('مشاهده جزئیات'),
                Action::make('approve')
                    ->label('تایید')
                    ->icon('heroicon-o-check')
                    ->color('success')
                    ->visible(fn (Report $record) => ($record->workflow_status ?? Report::WORKFLOW_PENDING) === Report::WORKFLOW_PENDING)
                    ->action(function (Report $record): void {
                        $record->update(['workflow_status' => Report::WORKFLOW_APPROVED, 'admin_reason' => null]);
                        Notification::make()->title('جیره تایید شد.')->success()->send();
                    }),
                Action::make('reject')
                    ->label('رد')
                    ->icon('heroicon-o-x-mark')
                    ->color('danger')
                    ->visible(fn (Report $record) => ($record->workflow_status ?? Report::WORKFLOW_PENDING) === Report::WORKFLOW_PENDING)
                    ->form([Textarea::make('admin_reason')->label('دلیل رد')->required()->rows(3)])
                    ->action(function (Report $record, array $data): void {
                        $record->update([
                            'workflow_status' => Report::WORKFLOW_REJECTED,
                            'admin_reason' => $data['admin_reason'],
                        ]);
                        Notification::make()->title('جیره رد شد.')->warning()->send();
                    }),
                Action::make('needs_edit')
                    ->label('ویرایش')
                    ->icon('heroicon-o-pencil-square')
                    ->color('warning')
                    ->visible(fn (Report $record) => ($record->workflow_status ?? Report::WORKFLOW_PENDING) === Report::WORKFLOW_PENDING)
                    ->form([Textarea::make('admin_reason')->label('دلیل و موارد اصلاح')->required()->rows(3)])
                    ->action(function (Report $record, array $data): void {
                        $record->update([
                            'workflow_status' => Report::WORKFLOW_NEEDS_EDIT,
                            'admin_reason' => $data['admin_reason'],
                        ]);
                        Notification::make()->title('جیره برای ویرایش ارسال شد.')->warning()->send();
                    }),
                EditAction::make()->label('ویرایش جیره'),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                    ForceDeleteBulkAction::make(),
                    RestoreBulkAction::make(),
                ]),
            ]);
    }
}
