<?php

declare(strict_types=1);

namespace App\Filament\Pages;

use App\Business\Report\SettlementAnalysisReportService;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Pages\Concerns\CachesDberpReportAnalysisResults;
use App\Filament\Pages\Concerns\HasDberpAnalysisPageCsvExport;
use App\Filament\Pages\Concerns\InteractsWithDberpReportPage;
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 DberpSettlementAnalysisPage extends Page
{
    use CachesDberpReportAnalysisResults;
    use HasDberpAnalysisPageCsvExport;
    use InteractsWithDberpPermissions;
    use InteractsWithDberpReportPage;

    private const REPORT_KEY = 'settlement-analysis';

    protected static ?string $slug = 'settlement-analysis';

    protected static ?int $navigationSort = 80;

    protected string $view = 'filament.pages.dberp-settlement-analysis-page';

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

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

    /**
     * @var list<array{date: string, amount: string}>
     */
    public array $receiptTrend = [];

    /**
     * @var list<array{date: string, amount: string}>
     */
    public array $paymentTrend = [];

    /**
     * @var list<array{id: int, name: string, amount: string}>
     */
    public array $topCustomers = [];

    /**
     * @var list<array{id: int, name: string, amount: string}>
     */
    public array $topSuppliers = [];

    /**
     * @var array<string, string>
     */
    public array $receivableAging = [];

    /**
     * @var array<string, string>
     */
    public array $payableAging = [];

    public function mount(): void
    {
        $this->form->fill([
            'business_time_from' => now()->startOfMonth()->toDateString(),
            'business_time_until' => now()->toDateString(),
            'as_of_date' => now()->toDateString(),
            'customer_id' => null,
            'supplier_id' => null,
        ]);

        $this->refreshData();
    }

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

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

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

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

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

    public function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Form::make([
                    DatePicker::make('business_time_from')
                        ->label(__('dberp.fields.business_time_from'))
                        ->default(now()->startOfMonth()->toDateString()),
                    DatePicker::make('business_time_until')
                        ->label(__('dberp.fields.business_time_until'))
                        ->default(now()->toDateString()),
                    DatePicker::make('as_of_date')
                        ->label(__('dberp.fields.as_of_date'))
                        ->default(now()->toDateString())
                        ->helperText(__('dberp.resources.settlement_analysis.as_of_hint')),
                    Select::make('customer_id')
                        ->label(__('dberp.fields.customer'))
                        ->options(fn (): array => DberpFilamentMasterDataSelectOptions::customers(enabledOnly: true))
                        ->searchable()
                        ->preload()
                        ->nullable(),
                    Select::make('supplier_id')
                        ->label(__('dberp.fields.supplier'))
                        ->options(fn (): array => DberpFilamentMasterDataSelectOptions::suppliers(enabledOnly: true))
                        ->searchable()
                        ->preload()
                        ->nullable(),
                ])
                    ->columns(3)
                    ->livewireSubmitHandler('refreshData')
                    ->footer([
                        Actions::make([
                            Action::make('refreshData')
                                ->label(__('dberp.actions.refresh_analysis'))
                                ->submit('refreshData'),
                        ]),
                    ]),
            ])
            ->statePath('data');
    }

    public function refreshData(): void
    {
        $service = app(SettlementAnalysisReportService::class);
        $filters = $service->normalizeFilters($this->form->getState());

        /** @var array{
         *     summary: array<string, int|string|float>,
         *     receiptTrend: list<array<string, string>>,
         *     paymentTrend: list<array<string, string>>,
         *     topCustomers: list<array<string, mixed>>,
         *     topSuppliers: list<array<string, mixed>>,
         *     receivableAging: list<array<string, mixed>>,
         *     payableAging: list<array<string, mixed>>
         * } $payload */
        $payload = $this->rememberReportAnalysis(self::REPORT_KEY, $filters, fn (): array => [
            'summary' => $service->summary($filters),
            'receiptTrend' => $service->dailyReceiptTrend($filters),
            'paymentTrend' => $service->dailyPaymentTrend($filters),
            'topCustomers' => $service->topCustomersByRemaining($filters, 8),
            'topSuppliers' => $service->topSuppliersByRemaining($filters, 8),
            'receivableAging' => $service->receivableAgingBuckets($filters),
            'payableAging' => $service->payableAgingBuckets($filters),
        ]);

        $this->summary = $payload['summary'];
        $this->receiptTrend = $payload['receiptTrend'];
        $this->paymentTrend = $payload['paymentTrend'];
        $this->topCustomers = $payload['topCustomers'];
        $this->topSuppliers = $payload['topSuppliers'];
        $this->receivableAging = $payload['receivableAging'];
        $this->payableAging = $payload['payableAging'];
    }

    protected function reportExportKey(): string
    {
        return self::REPORT_KEY;
    }
}
