<?php

declare(strict_types=1);

namespace App\Filament\Pages;

use App\Business\Sales\CustomerCreditControlService;
use App\Business\Sales\Enums\CreditCheckResult;
use App\Filament\Pages\Concerns\InteractsWithDberpNavigationGroupBreadcrumbs;
use App\Models\DberpCustomer;
use App\Services\DberpPermissionService;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Pages\Page;
use Filament\Schemas\Components\Actions;
use Filament\Schemas\Components\Form;
use Filament\Schemas\Schema;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Facades\Auth;
use UnitEnum;

/**
 * @property-read Schema $form
 */
final class DberpCustomerCreditControlPage extends Page
{
    use InteractsWithDberpNavigationGroupBreadcrumbs;

    protected static ?string $slug = 'customer-credit-control';

    protected static ?int $navigationSort = 18;

    protected string $view = 'filament.pages.dberp-customer-credit-control-page';

    /**
     * @var array<string, mixed>|null
     */
    public ?array $data = [];

    /**
     * @var list<array<string, mixed>>
     */
    public array $rows = [];

    /**
     * @var array<string, string|int>
     */
    public array $totals = [];

    public function mount(): void
    {
        $this->form->fill([
            'customer_id' => request()->integer('customer_id') ?: null,
            'credit_check_result' => request()->string('credit_check_result')->toString() ?: null,
            'attention_status' => request()->string('attention_status')->toString() ?: null,
            'pending_amount' => request()->string('pending_amount')->toString() ?: '0.0000',
            'as_of_date' => request()->string('as_of_date')->toString() ?: now()->toDateString(),
        ]);

        $this->refreshOverview();
    }

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

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

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

    public static function canAccess(): bool
    {
        return app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::VIEW_CUSTOMER_CREDIT_CONTROL);
    }

    public function getTitle(): string|Htmlable
    {
        return __('dberp.resources.customer_credit_control.label');
    }

    public function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Form::make([
                    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()
                        ->nullable(),
                    Select::make('credit_check_result')
                        ->label(__('dberp.fields.credit_check_result'))
                        ->options(CreditCheckResult::options())
                        ->nullable(),
                    Select::make('attention_status')
                        ->label(__('dberp.fields.attention_status'))
                        ->options(__('dberp.options.customer_credit_attention_status'))
                        ->nullable(),
                    TextInput::make('pending_amount')
                        ->label(__('dberp.fields.pending_amount'))
                        ->numeric()
                        ->default('0.0000'),
                    DatePicker::make('as_of_date')
                        ->label(__('dberp.fields.as_of_date'))
                        ->default(now()->toDateString())
                        ->required(),
                ])
                    ->columns(5)
                    ->livewireSubmitHandler('refreshOverview')
                    ->footer([
                        Actions::make([
                            Action::make('refreshOverview')
                                ->label(__('dberp.actions.refresh_credit_overview'))
                                ->submit('refreshOverview'),
                        ]),
                    ]),
            ])
            ->statePath('data');
    }

    public function refreshOverview(): void
    {
        $overview = app(CustomerCreditControlService::class)->overview($this->form->getState());
        $this->rows = $overview['rows'];
        $this->totals = $overview['totals'];
    }
}
