<?php

namespace App\Filament\Pages\Reports;

use App\Filament\Pages\Reports\Concerns\ProvidesInvoiceViewModal;
use App\Filament\Support\StatusLookup;
use App\Models\Lookups\Status;
use App\Models\Sales\Invoice;
use App\Services\CurrentContext;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

/**
 * Ported from ReportController::sales(). Same date window (now the shared
 * date-range preset, Today by default), same branch filter, same summary
 * figures and CSV columns — but the rows come from a native Filament table
 * (server-side pagination) instead of a 200-row capped array.
 */
class SalesReport extends ReportPage
{
    use ProvidesInvoiceViewModal;

    protected static string|\BackedEnum|null $navigationIcon = Heroicon::OutlinedChartBar;

    protected static ?string $navigationLabel = 'Sales Report';

    protected static ?string $slug = 'reports/sales';

    protected static ?string $title = 'Sales Report';

    public static function moduleKey(): string
    {
        return 'reports_sales';
    }

    public function csvFilename(): string
    {
        return 'sales-report.csv';
    }

    public function columns(): array
    {
        return [
            'date' => 'Date',
            'reference' => 'Invoice #',
            'customer' => 'Customer',
            'total' => 'Total',
            'paid' => 'Paid',
            'due' => 'Due',
            'status' => 'Status',
        ];
    }

    protected function reportQuery(): Builder
    {
        return Invoice::query()
            ->when($this->branchFilter(), fn ($q, $branchId) => $q->where('branch_id', $branchId))
            ->with(['customer:id,business_name', 'paymentStatus:id,code,name'])
            ->orderByDesc('created_at');
    }

    public function table(Table $table): Table
    {
        return $this->baseTable($table)
            ->columns([
                TextColumn::make('created_at')->label('Date')->date()->sortable(),
                TextColumn::make('invoice_number')->label('Invoice #')->searchable()->sortable(),
                TextColumn::make('customer.business_name')->label('Customer')->placeholder('Walk-in')->searchable(),
                TextColumn::make('net_total')->label('Total')->money(fn () => app(CurrentContext::class)->currencyCode())->sortable(),
                TextColumn::make('paid_amount')->label('Paid')->money(fn () => app(CurrentContext::class)->currencyCode())->sortable(),
                TextColumn::make('balance')->label('Due')->money(fn () => app(CurrentContext::class)->currencyCode())->sortable(),
                TextColumn::make('paymentStatus.code')->label('Status')
                    ->badge()
                    ->color(fn (string $state): ?string => StatusLookup::colorOf(Status::CTX_INVOICE_PAYMENT, $state))
                    ->formatStateUsing(fn (string $state): string => StatusLookup::nameOf(Status::CTX_INVOICE_PAYMENT, $state)),
            ])
            ->recordActions([$this->invoiceViewAction()]);
    }

    protected function exportRow(Model $record): array
    {
        $inv = $record;

        return [
            'date' => $inv->created_at->toDateString(),
            'reference' => $inv->invoice_number,
            'customer' => $inv->customer?->business_name ?? 'Walk-in',
            'total' => (float) $inv->net_total,
            'paid' => (float) $inv->paid_amount,
            'due' => (float) $inv->balance,
            'status' => $inv->paymentStatus?->code ?? 'unknown',
        ];
    }

    public function summary(): array
    {
        $query = $this->filteredQuery();

        return [
            'Total sales' => 'Rs. '.number_format((float) $query->clone()->sum('net_total'), 2),
            'Total paid' => 'Rs. '.number_format((float) $query->clone()->sum('paid_amount'), 2),
            'Total due' => 'Rs. '.number_format((float) $query->clone()->sum('balance'), 2),
            'Invoices' => (string) $query->clone()->count(),
        ];
    }

    protected function receiptLine(Model $record): array
    {
        $inv = $record;

        return [
            'label' => $inv->created_at->format('d/m/y').' '.$inv->invoice_number.' — '.($inv->customer?->business_name ?? 'Walk-in'),
            'value' => $this->formatAmount($inv->net_total),
        ];
    }

    protected function receiptTotals(): array
    {
        $query = $this->filteredQuery();

        return [
            ['label' => 'Total sales', 'value' => $this->formatAmount($query->clone()->sum('net_total'))],
            ['label' => 'Total paid', 'value' => $this->formatAmount($query->clone()->sum('paid_amount'))],
            ['label' => 'Total due', 'value' => $this->formatAmount($query->clone()->sum('balance'))],
            ['label' => 'Invoices', 'value' => (string) $query->clone()->count()],
        ];
    }
}
