<?php

declare(strict_types=1);

namespace App\Filament\Resources\HealthReports\Tables;

use App\Filament\Support\SelectOptionLabels;

use App\Models\Report;
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\Select;
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;
use App\Models\Product;
use App\Services\HealthTreatmentSyncService;

class HealthReportsTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('title')
                    ->label('عنوان')
                    ->searchable()
                    ->sortable()
                    ->limit(35),
                TextColumn::make('project.name')
                    ->label('پروژه')
                    ->searchable()
                    ->sortable()
                    ->placeholder('-'),
                TextColumn::make('producer.brand_name')
                    ->label('خدمات‌دهنده')
                    ->searchable()
                    ->sortable()
                    ->placeholder('-'),
                TextColumn::make('disease_name')
                    ->label('نام بیماری')
                    ->searchable()
                    ->placeholder('-'),
                TextColumn::make('report_type')
                    ->label('نوع گزارش')
                    ->badge()
                    ->formatStateUsing(fn (?string $state) => Report::healthReportTypes()[$state] ?? $state ?? '-')
                    ->color(fn (?string $state) => match ($state) {
                        Report::HEALTH_TYPE_TREATMENT => 'success',
                        Report::HEALTH_TYPE_DEHORNING => 'info',
                        Report::HEALTH_TYPE_REMOVE_PRODUCT => 'danger',
                        default => 'gray',
                    }),
                TextColumn::make('items_count')
                    ->label('تعداد محصول')
                    ->counts('items')
                    ->badge()
                    ->placeholder('0'),
                TextColumn::make('total_cost')
                    ->label('مبلغ کل')
                    ->numeric()
                    ->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(),
                TextColumn::make('report_at')
                    ->label('تاریخ/زمان')
                    ->jalaliDateTime('Y/m/d H:i')
                    ->sortable(),
                TextColumn::make('status')
                    ->label('وضعیت')
                    ->badge()
                    ->formatStateUsing(fn (?string $state) => match ($state ?? '') {
                        'draft' => 'پیش‌نویس',
                        'published' => 'منتشر شده',
                        'archived' => 'بایگانی',
                        default => $state ?? '-',
                    })
                    ->color(fn (?string $state) => match ($state ?? '') {
                        'published' => 'success',
                        'archived' => 'warning',
                        default => 'gray',
                    }),
            ])
            ->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('report_type')
                    ->label('نوع گزارش')
                    ->options(Report::healthReportTypes()),
                Filter::make('product_id')
                    ->label('محصول (کد/نام دام)')
                    ->form([
                        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;
                    }),
                SelectFilter::make('workflow_status')
                    ->label('وضعیت رسیدگی')
                    ->options([
                        Report::WORKFLOW_PENDING => 'انتظار',
                        Report::WORKFLOW_APPROVED => 'تایید',
                        Report::WORKFLOW_REJECTED => 'رد',
                        Report::WORKFLOW_NEEDS_EDIT => 'ویرایش',
                    ]),
                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('report_at', '>=', $data['date_from']);
                        }
                        if (filled($data['date_to'] ?? null)) {
                            $q->whereDate('report_at', '<=', $data['date_to']);
                        }
                        return $q;
                    }),
            ])
            ->recordActions([
                ViewAction::make(),
                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, 'status' => 'published', 'admin_reason' => null]);
                        app(HealthTreatmentSyncService::class)->syncFromApprovedReport(
                            $record->fresh(['items.product.breed', 'producer'])
                        );
                        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(),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                    ForceDeleteBulkAction::make(),
                    RestoreBulkAction::make(),
                ]),
            ]);
    }
}
