<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpPaymentOrders;

use App\Business\Settlement\Enums\PaymentOrderType;
use App\Business\Settlement\Enums\SettlementDocumentStatus;
use App\Business\Settlement\Enums\SettlementFundsUsageStatus;
use App\Business\Settlement\SettlementReceiptPaymentReferenceDefaultsResolver;
use App\Business\Settlement\SettlementRuleService;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Contracts\DberpFilamentFormEditability;
use App\Filament\Resources\DberpPaymentOrders\Pages\CreateDberpPaymentOrder;
use App\Filament\Resources\DberpPaymentOrders\Pages\EditDberpPaymentOrder;
use App\Filament\Resources\DberpPaymentOrders\Pages\ListDberpPaymentOrders;
use App\Filament\Support\DberpFilamentAttachmentFields;
use App\Filament\Support\DberpFilamentNumberFields;
use App\Models\DberpDictionaryItem;
use App\Models\DberpEmployee;
use App\Models\DberpPaymentOrder;
use App\Models\DberpPurchaseOrder;
use App\Models\DberpSupplier;
use App\Services\DberpPermissionService;
use App\Support\DberpNumberFormatter;
use BackedEnum;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
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 Illuminate\Database\Eloquent\Model;
use UnitEnum;

class DberpPaymentOrderResource extends Resource implements DberpFilamentFormEditability
{
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'code';

    protected static ?int $navigationSort = 50;

    public static function isRecordFormEditableForFilament(Model $record): bool
    {
        return $record instanceof DberpPaymentOrder
            && DberpFilamentAttachmentFields::isSettlementVoucherEditable($record);
    }

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make(__('dberp.sections.settlement_document'))
                    ->schema([
                        TextInput::make('code')
                            ->label(__('dberp.fields.payment_code'))
                            ->maxLength(64)
                            ->unique(ignoreRecord: true)
                            ->helperText(__('dberp.hints.auto_code'))
                            ->disabled(fn (?DberpPaymentOrder $record): bool => $record !== null && $record->status !== SettlementDocumentStatus::Draft->value),
                        Select::make('payment_type')
                            ->label(__('dberp.fields.payment_type'))
                            ->options(PaymentOrderType::options())
                            ->default(PaymentOrderType::Standard->value)
                            ->required()
                            ->disabled(fn (?DberpPaymentOrder $record): bool => $record !== null && $record->status !== SettlementDocumentStatus::Draft->value),
                        Select::make('purchase_order_id')
                            ->label(__('dberp.fields.purchase_order'))
                            ->options(fn (): array => DberpPurchaseOrder::query()
                                ->whereNot('status', 'voided')
                                ->orderByDesc('business_time')
                                ->pluck('code', 'id')
                                ->all())
                            ->searchable()
                            ->preload()
                            ->live()
                            ->afterStateUpdated(function (?int $state, Set $set, Get $get): void {
                                static::syncDefaultsFromPurchaseOrderSelection($state, $set, $get);
                            })
                            ->helperText(__('dberp.hints.payment_reference'))
                            ->disabled(fn (?DberpPaymentOrder $record): bool => $record !== null && $record->status !== SettlementDocumentStatus::Draft->value),
                        Placeholder::make('_purchase_order_settlement_summary')
                            ->label(__('dberp.fields.reference_order_settlement'))
                            ->content(function (Get $get): string {
                                $summary = app(SettlementReceiptPaymentReferenceDefaultsResolver::class)
                                    ->formatPurchaseOrderSettlementSummary(
                                        filled($get('purchase_order_id')) ? (int) $get('purchase_order_id') : null,
                                    );

                                return $summary !== ''
                                    ? $summary
                                    : (string) __('dberp.hints.reference_order_no_outstanding');
                            })
                            ->visible(fn (Get $get): bool => filled($get('purchase_order_id')))
                            ->columnSpanFull(),
                        Select::make('supplier_id')
                            ->label(__('dberp.fields.supplier'))
                            ->options(fn (): array => DberpSupplier::query()
                                ->where('is_enabled', true)
                                ->orderBy('sort_order')
                                ->orderBy('id')
                                ->pluck('name', 'id')
                                ->all())
                            ->searchable()
                            ->preload()
                            ->required()
                            ->disabled(fn (?DberpPaymentOrder $record): bool => $record !== null && $record->status !== SettlementDocumentStatus::Draft->value),
                        Select::make('payment_method_item_id')
                            ->label(__('dberp.fields.payment_method'))
                            ->options(function (): array {
                                $typeId = app(SettlementRuleService::class)->paymentMethodTypeId();

                                if ($typeId === null) {
                                    return [];
                                }

                                return DberpDictionaryItem::query()
                                    ->where('type_id', $typeId)
                                    ->where('is_enabled', true)
                                    ->orderBy('sort_order')
                                    ->orderBy('id')
                                    ->pluck('label', 'id')
                                    ->all();
                            })
                            ->searchable()
                            ->preload()
                            ->required()
                            ->disabled(fn (?DberpPaymentOrder $record): bool => $record !== null && $record->status !== SettlementDocumentStatus::Draft->value),
                        Select::make('handler_employee_id')
                            ->label(__('dberp.fields.handler_employee'))
                            ->options(fn (): array => DberpEmployee::selectOptionsForFilament(
                                fn (Builder $q) => $q->where('is_enabled', true),
                            ))
                            ->searchable()
                            ->preload()
                            ->disabled(fn (?DberpPaymentOrder $record): bool => $record !== null && $record->status !== SettlementDocumentStatus::Draft->value),
                        DateTimePicker::make('business_time')
                            ->label(__('dberp.fields.payment_date'))
                            ->default(now())
                            ->required()
                            ->seconds(false)
                            ->disabled(fn (?DberpPaymentOrder $record): bool => $record !== null && $record->status !== SettlementDocumentStatus::Draft->value),
                        DberpFilamentNumberFields::moneyInput(
                            TextInput::make('amount')
                                ->label(__('dberp.fields.payment_amount'))
                                ->required(),
                            withHelperText: false,
                        )
                            ->helperText(function (Get $get): ?string {
                                if (! filled($get('purchase_order_id'))) {
                                    return null;
                                }

                                $amounts = app(SettlementReceiptPaymentReferenceDefaultsResolver::class)
                                    ->purchaseOrderSettlementAmounts((int) $get('purchase_order_id'));

                                if ($amounts === null) {
                                    return null;
                                }

                                if ((float) $amounts['unpaid_amount'] <= 0.00005) {
                                    return (string) __('dberp.hints.reference_order_no_outstanding');
                                }

                                return (string) __('dberp.hints.payment_amount_reference_unpaid', [
                                    'amount' => DberpNumberFormatter::money($amounts['unpaid_amount']),
                                ]);
                            })
                            ->disabled(fn (?DberpPaymentOrder $record): bool => $record !== null && $record->status !== SettlementDocumentStatus::Draft->value)
                            ->dehydrated(fn (?DberpPaymentOrder $record): bool => $record === null || $record->status === SettlementDocumentStatus::Draft->value),
                        DberpFilamentNumberFields::displayMoney(
                            TextInput::make('written_off_amount')
                                ->label(__('dberp.fields.written_off_amount'))
                                ->disabled()
                                ->dehydrated(false)
                                ->visible(fn (?DberpPaymentOrder $record): bool => $record !== null),
                        ),
                        DberpFilamentNumberFields::displayMoney(
                            TextInput::make('available_amount')
                                ->label(__('dberp.fields.available_amount'))
                                ->disabled()
                                ->dehydrated(false)
                                ->visible(fn (?DberpPaymentOrder $record): bool => $record !== null),
                        ),
                        DberpFilamentAttachmentFields::voucherAttachments('dberp/settlement/payment-vouchers')
                            ->disabled(fn (?DberpPaymentOrder $record): bool => ! DberpFilamentAttachmentFields::isSettlementVoucherEditable($record)),
                        Textarea::make('remark')
                            ->label(__('dberp.fields.remark'))
                            ->rows(3)
                            ->columnSpanFull()
                            ->disabled(fn (?DberpPaymentOrder $record): bool => $record !== null && $record->status !== SettlementDocumentStatus::Draft->value),
                    ])
                    ->columns(2),
            ])->columns(1);
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()->with([
            'purchaseOrder',
            'supplier',
            'paymentMethodItem',
            'handlerEmployee',
        ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('business_time', 'desc')
            ->columns([
                TextColumn::make('code')
                    ->label(__('dberp.fields.payment_code'))
                    ->searchable(),
                TextColumn::make('payment_type')
                    ->label(__('dberp.fields.payment_type'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => PaymentOrderType::tryFrom((string) $state)?->label() ?? (string) $state),
                TextColumn::make('purchaseOrder.code')
                    ->label(__('dberp.fields.purchase_order'))
                    ->searchable(),
                TextColumn::make('supplier.name')
                    ->label(__('dberp.fields.supplier'))
                    ->searchable(),
                TextColumn::make('paymentMethodItem.label')
                    ->label(__('dberp.fields.payment_method')),
                TextColumn::make('amount')
                    ->label(__('dberp.fields.payment_amount'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::money($state)),
                TextColumn::make('written_off_amount')
                    ->label(__('dberp.fields.written_off_amount'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::money($state)),
                TextColumn::make('available_amount')
                    ->label(__('dberp.fields.available_amount'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::money($state)),
                TextColumn::make('handlerEmployee.name')
                    ->label(__('dberp.fields.handler_employee'))
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('status')
                    ->label(__('dberp.fields.status'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => SettlementDocumentStatus::tryFrom((string) $state)?->label() ?? (string) $state),
                TextColumn::make('write_off_status')
                    ->label(__('dberp.fields.write_off_status'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => SettlementFundsUsageStatus::tryFrom((string) $state)?->label() ?? (string) $state),
                TextColumn::make('business_time')
                    ->label(__('dberp.fields.payment_date'))
                    ->dateTime(),
                TextColumn::make('submitted_at')
                    ->label(__('dberp.fields.submitted_at'))
                    ->dateTime()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('effective_at')
                    ->label(__('dberp.fields.effective_at'))
                    ->dateTime()
                    ->toggleable(isToggledHiddenByDefault: true),
                TextColumn::make('voided_at')
                    ->label(__('dberp.fields.voided_at'))
                    ->dateTime()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                SelectFilter::make('supplier_id')
                    ->label(__('dberp.fields.supplier'))
                    ->relationship('supplier', 'name'),
                SelectFilter::make('purchase_order_id')
                    ->label(__('dberp.fields.purchase_order'))
                    ->relationship('purchaseOrder', 'code'),
                SelectFilter::make('payment_type')
                    ->label(__('dberp.fields.payment_type'))
                    ->options(PaymentOrderType::options()),
                SelectFilter::make('status')
                    ->label(__('dberp.fields.status'))
                    ->options(SettlementDocumentStatus::options()),
                SelectFilter::make('write_off_status')
                    ->label(__('dberp.fields.write_off_status'))
                    ->options(SettlementFundsUsageStatus::options()),
                SelectFilter::make('handler_employee_id')
                    ->label(__('dberp.fields.handler_employee'))
                    ->options(fn (): array => DberpEmployee::selectOptionsForFilament())
                    ->searchable()
                    ->preload(),
                SelectFilter::make('attention_status')
                    ->label(__('dberp.fields.attention_status'))
                    ->options(__('dberp.options.settlement_attention_status_receipt_payment'))
                    ->query(function (Builder $query, array $data): Builder {
                        $value = $data['value'] ?? null;

                        return match ($value) {
                            'large_unwritten' => $query->where('status', SettlementDocumentStatus::Effective->value)
                                ->where('available_amount', '>=', (float) config('dberp.settlement.reminders.large_unwritten_amount', 10000)),
                            'long_unwritten' => $query->where('status', SettlementDocumentStatus::Effective->value)
                                ->where('available_amount', '>', 0)
                                ->whereDate('business_time', '<=', now()->subDays((int) config('dberp.settlement.reminders.long_unwritten_days', 30))->toDateString()),
                            default => $query,
                        };
                    }),
                Filter::make('business_time_range')
                    ->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));
                    }),
            ]);
    }

    public static function canViewAny(): bool
    {
        return static::allowsAnyPermission([
            DberpPermissionService::VIEW_PAYMENT_ORDER,
            DberpPermissionService::CREATE_PAYMENT_ORDER,
            DberpPermissionService::CONFIRM_RECEIPT_PAYMENT,
            DberpPermissionService::EXPORT,
        ]);
    }

    public static function canCreate(): bool
    {
        return static::allowsPermission(DberpPermissionService::CREATE_PAYMENT_ORDER);
    }

    public static function canEdit(Model $record): bool
    {
        return static::allowsAnyPermission([
            DberpPermissionService::CREATE_PAYMENT_ORDER,
            DberpPermissionService::CONFIRM_RECEIPT_PAYMENT,
        ]);
    }

    public static function canDelete(Model $record): bool
    {
        return static::allowsPermission(DberpPermissionService::CREATE_PAYMENT_ORDER);
    }

    public static function getPages(): array
    {
        return [
            'index' => ListDberpPaymentOrders::route('/'),
            'create' => CreateDberpPaymentOrder::route('/create'),
            'edit' => EditDberpPaymentOrder::route('/{record}/edit'),
        ];
    }

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

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

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

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

    protected static function syncDefaultsFromPurchaseOrderSelection(?int $purchaseOrderId, Set $set, ?Get $get = null): void
    {
        if ($purchaseOrderId === null || $purchaseOrderId <= 0) {
            return;
        }

        $order = DberpPurchaseOrder::query()->find($purchaseOrderId);

        if (! $order instanceof DberpPurchaseOrder) {
            return;
        }

        $resolver = app(SettlementReceiptPaymentReferenceDefaultsResolver::class);

        foreach ($resolver->resolveFromPurchaseOrder($order) as $key => $value) {
            if ($value !== null) {
                $set($key, $value);
            }
        }

        if ($get !== null && blank($get('amount'))) {
            $suggestedAmount = $resolver->suggestPaymentAmountFromPurchaseOrder($purchaseOrderId);

            if ($suggestedAmount !== null) {
                $set('amount', $suggestedAmount);
            }
        }
    }
}
