<?php

declare(strict_types=1);

namespace App\Filament\Pages;

use App\Business\Purchase\Enums\PurchaseInquiryQuoteStatus;
use App\Business\Purchase\PurchaseInquiryComparisonService;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Pages\Concerns\InteractsWithDberpNavigationGroupBreadcrumbs;
use App\Models\DberpPurchaseRequest;
use App\Models\DberpSupplier;
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\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 DberpPurchaseInquiryComparisonPage extends Page
{
    use InteractsWithDberpNavigationGroupBreadcrumbs;
    use InteractsWithDberpPermissions;

    protected static ?string $slug = 'purchase-inquiry-comparison';

    protected static ?int $navigationSort = 12;

    protected string $view = 'filament.pages.dberp-purchase-inquiry-comparison-page';

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

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

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

    public function mount(): void
    {
        $this->form->fill([
            'purchase_request_id' => request()->integer('purchase_request_id') ?: null,
            'product_id' => request()->integer('product_id') ?: null,
            'supplier_id' => request()->integer('supplier_id') ?: null,
            'status' => request()->string('status')->toString() ?: null,
            'recommended_only' => request()->boolean('recommended_only') ? '1' : '0',
            'quote_date_from' => request()->string('quote_date_from')->toString() ?: null,
            'quote_date_until' => request()->string('quote_date_until')->toString() ?: null,
            'valid_until' => request()->string('valid_until')->toString() ?: null,
        ]);

        $this->refreshOverview();
    }

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

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

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

    public static function canAccess(): bool
    {
        return Auth::check() && self::allowsPermission(DberpPermissionService::NAV_PURCHASE_INQUIRY_COMPARISON);
    }

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

    public function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Form::make([
                    Select::make('purchase_request_id')
                        ->label(__('dberp.fields.purchase_request'))
                        ->options(fn (): array => DberpPurchaseRequest::query()->orderByDesc('request_time')->pluck('code', 'id')->all())
                        ->searchable()
                        ->preload()
                        ->nullable(),
                    Select::make('product_id')
                        ->label(__('dberp.fields.product'))
                        ->options(fn (): array => DberpFilamentMasterDataSelectOptions::products(enabledOnly: true))
                        ->searchable()
                        ->preload()
                        ->nullable(),
                    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()
                        ->nullable(),
                    Select::make('status')
                        ->label(__('dberp.fields.status'))
                        ->options(PurchaseInquiryQuoteStatus::options())
                        ->nullable(),
                    Select::make('recommended_only')
                        ->label(__('dberp.fields.is_recommended'))
                        ->options([
                            '0' => '全部',
                            '1' => '仅建议成交',
                        ])
                        ->default('0')
                        ->nullable(),
                    DatePicker::make('quote_date_from')
                        ->label(__('dberp.fields.quote_date_from')),
                    DatePicker::make('quote_date_until')
                        ->label(__('dberp.fields.quote_date_until')),
                    DatePicker::make('valid_until')
                        ->label(__('dberp.fields.valid_until_before')),
                ])
                    ->columns(4)
                    ->livewireSubmitHandler('refreshOverview')
                    ->footer([
                        Actions::make([
                            Action::make('refreshOverview')
                                ->label(__('dberp.actions.refresh_purchase_inquiry_comparison'))
                                ->submit('refreshOverview'),
                        ]),
                    ]),
            ])
            ->statePath('data');
    }

    public function refreshOverview(): void
    {
        $payload = $this->form->getState();
        $payload['recommended_only'] = ($payload['recommended_only'] ?? '0') === '1';

        $overview = app(PurchaseInquiryComparisonService::class)->overview($payload);

        $this->rows = $overview['rows'];
        $this->totals = $overview['totals'];
    }
}
