<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

namespace App\Filament\Pages;

use App\Business\Sales\CustomerCreditControlService;
use App\Business\Sales\Enums\CreditCheckResult;
use App\Filament\Pages\Concerns\InteractsWithDberpNavigationGroupBreadcrumbs;
use App\Services\DberpPermissionService;
use App\Support\DberpFilamentMasterDataSelectOptions;
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([
                    DberpFilamentMasterDataSelectOptions::applyDeferredSearch(
                        Select::make('customer_id')
                            ->label(__('dberp.fields.customer'))
                            ->nullable(),
                        fn (): array => DberpFilamentMasterDataSelectOptions::customers(enabledOnly: true),
                    ),
                    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'];
    }
}
