<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpReceiptOrders;

use App\Business\Settlement\Enums\ReceiptOrderType;
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\DberpReceiptOrders\Pages\CreateDberpReceiptOrder;
use App\Filament\Resources\DberpReceiptOrders\Pages\EditDberpReceiptOrder;
use App\Filament\Resources\DberpReceiptOrders\Pages\ListDberpReceiptOrders;
use App\Filament\Support\DberpFilamentAttachmentFields;
use App\Filament\Support\DberpFilamentNumberFields;
use App\Models\DberpCustomer;
use App\Models\DberpDictionaryItem;
use App\Models\DberpEmployee;
use App\Models\DberpReceiptOrder;
use App\Models\DberpSalesOrder;
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 DberpReceiptOrderResource extends Resource implements DberpFilamentFormEditability
{
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'code';

    protected static ?int $navigationSort = 40;

    public static function isRecordFormEditableForFilament(Model $record): bool
    {
        return $record instanceof DberpReceiptOrder
            && 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.receipt_code'))
                            ->maxLength(64)
                            ->unique(ignoreRecord: true)
                            ->helperText(__('dberp.hints.auto_code'))
                            ->disabled(fn (?DberpReceiptOrder $record): bool => $record !== null && $record->status !== SettlementDocumentStatus::Draft->value),
                        Select::make('receipt_type')
                            ->label(__('dberp.fields.receipt_type'))
                            ->options(ReceiptOrderType::options())
                            ->default(ReceiptOrderType::Standard->value)
                            ->required()
                            ->disabled(fn (?DberpReceiptOrder $record): bool => $record !== null && $record->status !== SettlementDocumentStatus::Draft->value),
                        Select::make('sales_order_id')
                            ->label(__('dberp.fields.sales_order'))
                            ->options(fn (): array => DberpSalesOrder::query()
                                ->whereNot('status', 'voided')
                                ->orderByDesc('business_time')
                                ->pluck('code', 'id')
                                ->all())
                            ->searchable()
                            ->preload()
                            ->live()
                            ->afterStateUpdated(function (?int $state, Set $set, Get $get): void {
                                static::syncDefaultsFromSalesOrderSelection($state, $set, $get);
                            })
                            ->helperText(__('dberp.hints.receipt_reference'))
                            ->disabled(fn (?DberpReceiptOrder $record): bool => $record !== null && $record->status !== SettlementDocumentStatus::Draft->value),
                        Placeholder::make('_sales_order_settlement_summary')
                            ->label(__('dberp.fields.reference_order_settlement'))
                            ->content(function (Get $get): string {
                                $summary = app(SettlementReceiptPaymentReferenceDefaultsResolver::class)
                                    ->formatSalesOrderSettlementSummary(
                                        filled($get('sales_order_id')) ? (int) $get('sales_order_id') : null,
                                    );

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

                                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 (?DberpReceiptOrder $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 (?DberpReceiptOrder $record): bool => $record !== null && $record->status !== SettlementDocumentStatus::Draft->value),
                        DateTimePicker::make('business_time')
                            ->label(__('dberp.fields.receipt_date'))
                            ->default(now())
                            ->required()
                            ->seconds(false)
                            ->disabled(fn (?DberpReceiptOrder $record): bool => $record !== null && $record->status !== SettlementDocumentStatus::Draft->value),
                        DberpFilamentNumberFields::moneyInput(
                            TextInput::make('amount')
                                ->label(__('dberp.fields.receipt_amount'))
                                ->required(),
                            withHelperText: false,
                        )
                            ->helperText(function (Get $get): ?string {
                                if (! filled($get('sales_order_id'))) {
                                    return null;
                                }

                                $amounts = app(SettlementReceiptPaymentReferenceDefaultsResolver::class)
                                    ->salesOrderSettlementAmounts((int) $get('sales_order_id'));

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

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

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

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

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('business_time', 'desc')
            ->columns([
                TextColumn::make('code')
                    ->label(__('dberp.fields.receipt_code'))
                    ->searchable(),
                TextColumn::make('receipt_type')
                    ->label(__('dberp.fields.receipt_type'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => ReceiptOrderType::tryFrom((string) $state)?->label() ?? (string) $state),
                TextColumn::make('salesOrder.code')
                    ->label(__('dberp.fields.sales_order'))
                    ->searchable(),
                TextColumn::make('customer.name')
                    ->label(__('dberp.fields.customer'))
                    ->searchable(),
                TextColumn::make('paymentMethodItem.label')
                    ->label(__('dberp.fields.receipt_method')),
                TextColumn::make('amount')
                    ->label(__('dberp.fields.receipt_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.receipt_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('customer_id')
                    ->label(__('dberp.fields.customer'))
                    ->relationship('customer', 'name'),
                SelectFilter::make('sales_order_id')
                    ->label(__('dberp.fields.sales_order'))
                    ->relationship('salesOrder', 'code'),
                SelectFilter::make('receipt_type')
                    ->label(__('dberp.fields.receipt_type'))
                    ->options(ReceiptOrderType::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_RECEIPT_ORDER,
            DberpPermissionService::CREATE_RECEIPT_ORDER,
            DberpPermissionService::CONFIRM_RECEIPT_PAYMENT,
            DberpPermissionService::EXPORT,
        ]);
    }

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

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

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

    public static function getPages(): array
    {
        return [
            'index' => ListDberpReceiptOrders::route('/'),
            'create' => CreateDberpReceiptOrder::route('/create'),
            'edit' => EditDberpReceiptOrder::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.receipt_order.label');
    }

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

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

        $order = DberpSalesOrder::query()->find($salesOrderId);

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

        $resolver = app(SettlementReceiptPaymentReferenceDefaultsResolver::class);

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

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

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