<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpSettlementAdjustments;

use App\Business\Settlement\Enums\SettlementAdjustmentDirection;
use App\Business\Settlement\Enums\SettlementAdjustmentStatus;
use App\Business\Settlement\Enums\SettlementAdjustmentType;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Contracts\DberpFilamentFormEditability;
use App\Filament\Resources\DberpSettlementAdjustments\Pages\CreateDberpSettlementAdjustment;
use App\Filament\Resources\DberpSettlementAdjustments\Pages\EditDberpSettlementAdjustment;
use App\Filament\Resources\DberpSettlementAdjustments\Pages\ListDberpSettlementAdjustments;
use App\Filament\Support\DberpFilamentNumberFields;
use App\Models\DberpCustomer;
use App\Models\DberpEmployee;
use App\Models\DberpPayableRecord;
use App\Models\DberpReceivableRecord;
use App\Models\DberpSettlementAdjustment;
use App\Models\DberpSupplier;
use App\Services\DberpPermissionService;
use App\Support\DberpNumberFormatter;
use BackedEnum;
use Filament\Forms\Components\DateTimePicker;
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\Schema;
use Filament\Tables\Columns\TextColumn;
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 DberpSettlementAdjustmentResource extends Resource implements DberpFilamentFormEditability
{
    use InteractsWithDberpPermissions;

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

    protected static ?string $recordTitleAttribute = 'code';

    protected static ?int $navigationSort = 80;

    public static function isRecordFormEditableForFilament(Model $record): bool
    {
        return $record instanceof DberpSettlementAdjustment
            && $record->status === SettlementAdjustmentStatus::Draft->value;
    }

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Section::make(__('dberp.sections.settlement_adjustment'))
                    ->schema([
                        TextInput::make('code')
                            ->label(__('dberp.fields.adjustment_code'))
                            ->disabled()
                            ->dehydrated(false)
                            ->visible(fn (?DberpSettlementAdjustment $record): bool => $record !== null),
                        Select::make('settlement_side')
                            ->label(__('dberp.fields.settlement_side'))
                            ->options(__('dberp.options.settlement_business_side'))
                            ->default('receivable')
                            ->required()
                            ->disabled(fn (?DberpSettlementAdjustment $record): bool => $record !== null && $record->status !== SettlementAdjustmentStatus::Draft->value),
                        Select::make('counterparty_id')
                            ->label(__('dberp.fields.counterparty'))
                            ->options(function (callable $get): array {
                                return $get('settlement_side') === 'payable'
                                    ? DberpSupplier::query()->where('is_enabled', true)->orderBy('sort_order')->orderBy('id')->pluck('name', 'id')->all()
                                    : DberpCustomer::query()->where('is_enabled', true)->orderBy('sort_order')->orderBy('id')->pluck('name', 'id')->all();
                            })
                            ->searchable()
                            ->preload()
                            ->required()
                            ->disabled(fn (?DberpSettlementAdjustment $record): bool => $record !== null && $record->status !== SettlementAdjustmentStatus::Draft->value),
                        Select::make('receivable_record_id')
                            ->label(__('dberp.fields.receivable_record_code'))
                            ->visible(fn (callable $get): bool => $get('settlement_side') === 'receivable')
                            ->options(function (callable $get): array {
                                return DberpReceivableRecord::query()
                                    ->with('customer')
                                    ->where('remaining_amount', '>=', 0)
                                    ->whereNot('record_status', 'voided')
                                    ->when(($get('counterparty_id') ?? 0) > 0, fn (Builder $query): Builder => $query->where('customer_id', (int) $get('counterparty_id')))
                                    ->orderByDesc('business_date')
                                    ->get()
                                    ->mapWithKeys(fn (DberpReceivableRecord $item): array => [$item->getKey() => sprintf('%s / %s / %s', $item->code, $item->customer?->name ?? '-', DberpNumberFormatter::money((float) $item->remaining_amount))])
                                    ->all();
                            })
                            ->searchable()
                            ->required(fn (callable $get): bool => $get('settlement_side') === 'receivable')
                            ->disabled(fn (?DberpSettlementAdjustment $record): bool => $record !== null && $record->status !== SettlementAdjustmentStatus::Draft->value),
                        Select::make('payable_record_id')
                            ->label(__('dberp.fields.payable_record_code'))
                            ->visible(fn (callable $get): bool => $get('settlement_side') === 'payable')
                            ->options(function (callable $get): array {
                                return DberpPayableRecord::query()
                                    ->with('supplier')
                                    ->where('remaining_amount', '>=', 0)
                                    ->whereNot('record_status', 'voided')
                                    ->when(($get('counterparty_id') ?? 0) > 0, fn (Builder $query): Builder => $query->where('supplier_id', (int) $get('counterparty_id')))
                                    ->orderByDesc('business_date')
                                    ->get()
                                    ->mapWithKeys(fn (DberpPayableRecord $item): array => [$item->getKey() => sprintf('%s / %s / %s', $item->code, $item->supplier?->name ?? '-', DberpNumberFormatter::money((float) $item->remaining_amount))])
                                    ->all();
                            })
                            ->searchable()
                            ->required(fn (callable $get): bool => $get('settlement_side') === 'payable')
                            ->disabled(fn (?DberpSettlementAdjustment $record): bool => $record !== null && $record->status !== SettlementAdjustmentStatus::Draft->value),
                        Select::make('adjustment_direction')
                            ->label(__('dberp.fields.adjustment_direction'))
                            ->options(SettlementAdjustmentDirection::options())
                            ->default(SettlementAdjustmentDirection::Increase->value)
                            ->required()
                            ->disabled(fn (?DberpSettlementAdjustment $record): bool => $record !== null && $record->status !== SettlementAdjustmentStatus::Draft->value),
                        Select::make('adjustment_type')
                            ->label(__('dberp.fields.adjustment_type'))
                            ->options(SettlementAdjustmentType::options())
                            ->default(SettlementAdjustmentType::Manual->value)
                            ->required()
                            ->disabled(fn (?DberpSettlementAdjustment $record): bool => $record !== null && $record->status !== SettlementAdjustmentStatus::Draft->value),
                        DateTimePicker::make('business_date')
                            ->label(__('dberp.fields.business_time'))
                            ->default(now())
                            ->seconds(false)
                            ->required()
                            ->disabled(fn (?DberpSettlementAdjustment $record): bool => $record !== null && $record->status !== SettlementAdjustmentStatus::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 (?DberpSettlementAdjustment $record): bool => $record !== null && $record->status !== SettlementAdjustmentStatus::Draft->value),
                        DberpFilamentNumberFields::moneyInput(
                            TextInput::make('amount')
                                ->label(__('dberp.fields.adjustment_amount'))
                                ->required()
                                ->disabled(fn (?DberpSettlementAdjustment $record): bool => $record !== null && $record->status !== SettlementAdjustmentStatus::Draft->value),
                            withHelperText: false,
                        )
                            ->formatStateUsing(fn ($state, ?DberpSettlementAdjustment $record): mixed => $record !== null && $record->status !== SettlementAdjustmentStatus::Draft->value
                                ? DberpNumberFormatter::money($state)
                                : $state),
                        DberpFilamentNumberFields::displayMoney(
                            TextInput::make('effective_amount')
                                ->label(__('dberp.fields.effective_amount'))
                                ->disabled()
                                ->dehydrated(false)
                                ->visible(fn (?DberpSettlementAdjustment $record): bool => $record !== null),
                        ),
                        Textarea::make('remark')
                            ->label(__('dberp.fields.remark'))
                            ->rows(2)
                            ->columnSpanFull()
                            ->disabled(fn (?DberpSettlementAdjustment $record): bool => $record !== null && $record->status !== SettlementAdjustmentStatus::Draft->value),
                    ])
                    ->columns(2),
            ])->columns(1);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('business_date', 'desc')
            ->columns([
                TextColumn::make('code')
                    ->label(__('dberp.fields.adjustment_code'))
                    ->searchable(),
                TextColumn::make('settlement_side')
                    ->label(__('dberp.fields.settlement_side'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => __('dberp.options.settlement_business_side')[$state] ?? (string) $state),
                TextColumn::make('counterparty_id')
                    ->label(__('dberp.fields.counterparty'))
                    ->formatStateUsing(function (?string $state, DberpSettlementAdjustment $record): string {
                        if ($record->settlement_side === 'payable') {
                            return DberpSupplier::query()->whereKey($state)->value('name') ?? (string) $state;
                        }

                        return DberpCustomer::query()->whereKey($state)->value('name') ?? (string) $state;
                    }),
                TextColumn::make('amount')
                    ->label(__('dberp.fields.adjustment_amount'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::money($state)),
                TextColumn::make('effective_amount')
                    ->label(__('dberp.fields.effective_amount'))
                    ->formatStateUsing(fn ($state): string => DberpNumberFormatter::money($state)),
                TextColumn::make('adjustment_direction')
                    ->label(__('dberp.fields.adjustment_direction'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => SettlementAdjustmentDirection::tryFrom((string) $state)?->label() ?? (string) $state),
                TextColumn::make('adjustment_type')
                    ->label(__('dberp.fields.adjustment_type'))
                    ->formatStateUsing(fn (?string $state): string => SettlementAdjustmentType::tryFrom((string) $state)?->label() ?? (string) $state),
                TextColumn::make('status')
                    ->label(__('dberp.fields.status'))
                    ->badge()
                    ->formatStateUsing(fn (?string $state): string => SettlementAdjustmentStatus::tryFrom((string) $state)?->label() ?? (string) $state),
                TextColumn::make('business_date')
                    ->label(__('dberp.fields.business_time'))
                    ->dateTime(),
                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('settlement_side')
                    ->label(__('dberp.fields.settlement_side'))
                    ->options(__('dberp.options.settlement_business_side')),
                SelectFilter::make('status')
                    ->label(__('dberp.fields.status'))
                    ->options(SettlementAdjustmentStatus::options()),
                SelectFilter::make('adjustment_direction')
                    ->label(__('dberp.fields.adjustment_direction'))
                    ->options(SettlementAdjustmentDirection::options()),
                SelectFilter::make('adjustment_type')
                    ->label(__('dberp.fields.adjustment_type'))
                    ->options(SettlementAdjustmentType::options()),
                SelectFilter::make('attention_status')
                    ->label(__('dberp.fields.attention_status'))
                    ->options(__('dberp.options.settlement_attention_status_adjustment'))
                    ->query(function (Builder $query, array $data): Builder {
                        return ($data['value'] ?? null) === 'recent_follow_up'
                            ? $query->where(function (Builder $builder): void {
                                $date = now()->subDays((int) config('dberp.settlement.reminders.follow_up_days', 7))->toDateString();
                                $builder->whereDate('effective_at', '>=', $date)
                                    ->orWhereDate('voided_at', '>=', $date)
                                    ->orWhereDate('updated_at', '>=', $date);
                            })
                            : $query;
                    }),
            ]);
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()->with(['receivableRecord.customer', 'payableRecord.supplier', 'handlerEmployee']);
    }

    public static function canViewAny(): bool
    {
        return static::allowsAnyPermission([
            DberpPermissionService::VIEW_SETTLEMENT_ADJUSTMENT,
            DberpPermissionService::CREATE_SETTLEMENT_ADJUSTMENT,
        ]);
    }

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

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

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

    public static function getPages(): array
    {
        return [
            'index' => ListDberpSettlementAdjustments::route('/'),
            'create' => CreateDberpSettlementAdjustment::route('/create'),
            'edit' => EditDberpSettlementAdjustment::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.settlement_adjustment.label');
    }

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