<?php

namespace App\Filament\Resources\Invoices\Tables;

use App\Models\Invoice;
use Filament\Actions\Action;
use Filament\Actions\ViewAction;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;

class InvoicesTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->modifyQueryUsing(fn ($query) =>
                $query->select([
                    'id', 'consignment_id', 'invoice_number',
                    'amount_usd', 'amount_kes', 'extra_charge_usd',
                    'amount_paid_kes', 'outstanding_kes',
                    'payment_status', 'due_date', 'created_at',
                ])
                ->with([
                    'consignment:id,customer_name,phone,flight_no,house_waybill_no,container_no,destination',
                ])
                ->latest()
            )
            ->paginated([15, 25, 50])
            ->columns([
                TextColumn::make('invoice_number')
                    ->label('Invoice No.')
                    ->weight('bold')
                    ->copyable()
                    ->searchable(),

                TextColumn::make('consignment.customer_name')
                    ->label('Client')
                    ->searchable(),

                TextColumn::make('consignment.phone')
                    ->label('Phone')
                    ->searchable(),

                TextColumn::make('amount_kes')
                    ->label('Total (KES)')
                    ->formatStateUsing(fn ($state) =>
                        'KES ' . number_format($state, 2)
                    )
                    ->weight('bold'),

                TextColumn::make('amount_paid_kes')
                    ->label('Paid (KES)')
                    ->formatStateUsing(fn ($state) =>
                        'KES ' . number_format($state, 2)
                    )
                    ->color('success'),

                TextColumn::make('outstanding_kes')
                    ->label('Outstanding (KES)')
                    ->formatStateUsing(fn ($state) =>
                        'KES ' . number_format($state, 2)
                    )
                    ->color(fn ($state) =>
                        $state > 0 ? 'danger' : 'success'
                    ),

                TextColumn::make('payment_status')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'paid'    => 'success',
                        'partial' => 'warning',
                        'unpaid'  => 'danger',
                        default   => 'gray',
                    })
                    ->formatStateUsing(fn (string $state): string =>
                        ucfirst($state)
                    ),

                TextColumn::make('due_date')
                    ->date('M d, Y')
                    ->placeholder('—')
                    ->color(fn ($record) =>
                        $record->due_date?->isPast() &&
                        $record->payment_status !== 'paid'
                            ? 'danger' : null
                    ),
            ])
            ->filters([
                SelectFilter::make('payment_status')
                    ->options([
                        'unpaid'  => 'Unpaid',
                        'partial' => 'Partial',
                        'paid'    => 'Paid',
                    ]),

                Filter::make('overdue')
                    ->label('Overdue only')
                    ->query(fn ($query) =>
                        $query->where('due_date', '<', today())
                              ->where('payment_status', '!=', 'paid')
                    ),
            ])
            ->actions([
                ViewAction::make(),

                Action::make('print')
                    ->label('Print')
                    ->icon('heroicon-o-printer')
                    ->color('primary')
                    ->url(fn (Invoice $record): string =>
                        route('documents.print', ['invoice', $record->consignment_id])
                    )
                    ->openUrlInNewTab()
                    ->visible(fn (): bool =>
                        auth()->user()?->hasRole(['super_admin', 'admin']) ?? false
                    ),

                Action::make('record_payment')
                    ->label('Record Payment')
                    ->icon('heroicon-o-banknotes')
                    ->color('success')
                    ->visible(fn (Invoice $record): bool =>
                        $record->payment_status !== 'paid' &&
                        (auth()->user()?->hasPermissionTo('create_payments') ?? false)
                    )
                    ->url(fn (Invoice $record): string =>
                        \App\Filament\Resources\Payments\PaymentResource::getUrl('create') .
                        '?consignment_id=' . $record->consignment_id
                    ),
            ])
            ->defaultSort('created_at', 'desc');
    }
}