<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpDocumentQueries;

use App\Business\Report\QueryCenterService;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Resources\Concerns\HasDberpExportAction;
use App\Filament\Resources\DberpDocumentQueries\Pages\ListDberpDocumentQueries;
use App\Models\DberpDocumentQuery;
use App\Models\DberpEmployee;
use App\Services\DberpPermissionService;
use App\Support\DberpDocumentQueryPresentation;
use App\Support\DberpDocumentQuerySourceUrlResolver;
use App\Support\DberpFilamentMasterDataSelectOptions;
use App\Support\DberpNumberFormatter;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Forms\Components\DatePicker;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Builder;
use UnitEnum;

class DberpDocumentQueryResource extends Resource
{
    use HasDberpExportAction;
    use InteractsWithDberpPermissions;

    protected static ?string $model = DberpDocumentQuery::class;

    protected static ?string $recordTitleAttribute = 'code';

    protected static ?int $navigationSort = 10;

    public static function form(Schema $schema): Schema
    {
        return $schema->components([]);
    }

    public static function getEloquentQuery(): Builder
    {
        return app(QueryCenterService::class)->documentQuery();
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('business_time', 'desc')
            ->columns([
                TextColumn::make('document_type')->label(__('dberp.fields.document_type'))->badge()->formatStateUsing(fn (?string $state): string => __('dberp.options.document_type')[$state] ?? (string) $state),
                TextColumn::make('code')->label(__('dberp.fields.document_code'))->searchable(),
                TextColumn::make('status')->label(__('dberp.fields.status'))->badge()->formatStateUsing(fn (?string $state, DberpDocumentQuery $record): string => DberpDocumentQueryPresentation::statusLabel((string) $record->document_type, $state)),
                TextColumn::make('customer.name')->label(__('dberp.fields.customer')),
                TextColumn::make('supplier.name')->label(__('dberp.fields.supplier')),
                TextColumn::make('warehouse.name')->label(__('dberp.fields.warehouse')),
                TextColumn::make('handlerEmployee.name')->label(__('dberp.fields.handler_employee')),
                TextColumn::make('total_quantity')->label(__('dberp.fields.total_quantity'))->formatStateUsing(fn ($state): string => DberpNumberFormatter::quantity($state)),
                TextColumn::make('total_amount')->label(__('dberp.fields.total_amount'))->formatStateUsing(fn ($state): string => DberpNumberFormatter::money($state)),
                TextColumn::make('business_time')->label(__('dberp.fields.business_time'))->dateTime(),
                TextColumn::make('remark')->label(__('dberp.fields.remark'))->limit(40)->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                SelectFilter::make('document_type')->label(__('dberp.fields.document_type'))->options(__('dberp.options.document_type')),
                SelectFilter::make('status')->label(__('dberp.fields.status'))->options(__('dberp.options.common_document_status')),
                SelectFilter::make('customer_id')->label(__('dberp.fields.customer'))->options(fn (): array => DberpFilamentMasterDataSelectOptions::customers()),
                SelectFilter::make('supplier_id')->label(__('dberp.fields.supplier'))->options(fn (): array => DberpFilamentMasterDataSelectOptions::suppliers()),
                SelectFilter::make('warehouse_id')->label(__('dberp.fields.warehouse'))->options(fn (): array => DberpFilamentMasterDataSelectOptions::warehouses(enabledOnly: false)),
                SelectFilter::make('handler_employee_id')->label(__('dberp.fields.handler_employee'))->options(fn (): array => DberpEmployee::selectOptionsForFilament()),
                Filter::make('business_time')
                    ->schema([
                        DatePicker::make('from')->label(__('dberp.fields.date_from')),
                        DatePicker::make('until')->label(__('dberp.fields.date_until')),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when($data['from'] ?? null, fn (Builder $builder, $date): Builder => $builder->whereDate('business_time', '>=', $date))
                            ->when($data['until'] ?? null, fn (Builder $builder, $date): Builder => $builder->whereDate('business_time', '<=', $date));
                    }),
            ])
            ->headerActions([
                static::makeExportAction('document-query'),
            ])
            ->recordActions([
                Action::make('view_source')
                    ->label(__('dberp.actions.view_source_document'))
                    ->url(fn (DberpDocumentQuery $record): ?string => DberpDocumentQuerySourceUrlResolver::editUrl($record))
                    ->visible(fn (DberpDocumentQuery $record): bool => DberpDocumentQuerySourceUrlResolver::editUrl($record) !== null),
            ]);
    }

    public static function getPages(): array
    {
        return ['index' => ListDberpDocumentQueries::route('/')];
    }

    public static function canViewAny(): bool
    {
        return static::allowsPermission(DberpPermissionService::NAV_DOCUMENT_QUERY);
    }

    public static function getNavigationGroup(): string|UnitEnum|null
    {
        return __('dberp.nav.business_query');
    }

    public static function getNavigationIcon(): string|BackedEnum|Htmlable|null
    {
        return null;
    }

    public static function getModelLabel(): string
    {
        return __('dberp.resources.document_query.label');
    }

    public static function getPluralModelLabel(): string
    {
        return __('dberp.resources.document_query.plural');
    }
}
