<?php

namespace App\Filament\Widgets;

use App\Enums\Currency;
use App\Enums\PaymentStatus;
use App\Filament\Resources\SaleResource;
use App\Models\Account;
use App\Models\Payment;
use App\Models\Sale;
use Filament\Forms;
use Filament\Forms\Get;
use Filament\Notifications\Notification;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget as BaseWidget;

class OverdueCxCWidget extends BaseWidget
{
    protected static ?string $heading = '🔴 CxC Vencidas';
    protected static ?int $sort = 5;
    protected int | string | array $columnSpan = 1;

    public function table(Table $table): Table
    {
        return $table
            ->query(
                Sale::query()
                    ->where('expected_collect_date', '<', now()->toDateString())
                    ->where('payment_status', '!=', PaymentStatus::Paid->value)
                    ->orderBy('expected_collect_date')
            )
            ->columns([
                Tables\Columns\TextColumn::make('expected_collect_date')
                    ->label('Vencía')
                    ->date('d/m/Y')
                    ->color('danger'),

                Tables\Columns\TextColumn::make('client.name')
                    ->label('Cliente')
                    ->limit(20),

                Tables\Columns\TextColumn::make('aging_days')
                    ->label('Días')
                    ->getStateUsing(fn (Sale $r) => $r->aging_days . 'd')
                    ->color('danger'),

                Tables\Columns\TextColumn::make('balance')
                    ->label('Saldo')
                    ->getStateUsing(fn (Sale $r) => $r->currency->symbol() . number_format($r->balance, 2))
                    ->color('danger'),
            ])
            ->actions([
                Tables\Actions\Action::make('mover')
                    ->label('Mover')
                    ->icon('heroicon-o-calendar')
                    ->color('warning')
                    ->form([
                        Forms\Components\DatePicker::make('nueva_fecha')
                            ->label('Nueva fecha de cobro esperada')
                            ->required()
                            ->default(now()->toDateString())
                            ->minDate(now()->toDateString())
                            ->helperText('Por defecto se mueve a hoy. Cambiá si preferís otro día de esta semana.'),

                        Forms\Components\Textarea::make('note')
                            ->label('Nota de seguimiento (opcional)')
                            ->rows(2)
                            ->placeholder('Ej: Cliente confirmó pago para el jueves'),
                    ])
                    ->action(function (Sale $record, array $data): void {
                        $record->update([
                            'expected_collect_date' => $data['nueva_fecha'],
                            'last_follow_up_date'   => now()->toDateString(),
                            'follow_up_note'        => $data['note'] ?? null,
                        ]);
                        Notification::make()
                            ->title('Cobro reprogramado')
                            ->body("{$record->client?->name} → nueva fecha: " . \Carbon\Carbon::parse($data['nueva_fecha'])->format('d/m/Y'))
                            ->success()
                            ->send();
                    })
                    ->modalHeading(fn (Sale $r) => "Reprogramar cobro — {$r->client?->name}")
                    ->modalDescription(fn (Sale $r) => "Vencía el " . $r->expected_collect_date?->format('d/m/Y') . " · Saldo: " . $r->currency->symbol() . number_format($r->balance, 2))
                    ->modalSubmitActionLabel('Reprogramar')
                    ->modalWidth('md'),

                Tables\Actions\Action::make('pago')
                    ->label('Pago')
                    ->icon('heroicon-o-banknotes')
                    ->color('success')
                    ->fillForm(fn (Sale $record): array => [
                        'amount'       => max(0, round($record->balance, 2)),
                        'currency'     => $record->currency->value,
                        'payment_date' => now()->toDateString(),
                        'account_id'   => Account::whereRaw('LOWER(name) LIKE ?', [
                            $record->currency === Currency::USD ? '%payoneer%' : '%nuna%'
                        ])->first()?->id ?? Account::first()?->id,
                        'note' => '',
                    ])
                    ->form(fn (Sale $record) => [
                        Forms\Components\Placeholder::make('sale_info')
                            ->label('Venta')
                            ->content("{$record->client?->name} — {$record->title}"),

                        Forms\Components\Placeholder::make('balance_info')
                            ->label('Saldo pendiente')
                            ->content($record->currency->symbol() . number_format($record->balance, 2)),

                        Forms\Components\Grid::make(2)->schema([
                            Forms\Components\TextInput::make('amount')
                                ->label('Monto cobrado')
                                ->numeric()
                                ->required()
                                ->step(0.01)
                                ->minValue(0.01)
                                ->prefix(fn (Get $get) => match($get('currency')) { 'BOB' => 'Bs.', default => '$' }),

                            Forms\Components\Select::make('currency')
                                ->label('Moneda')
                                ->options(collect(Currency::cases())->mapWithKeys(fn ($e) => [$e->value => $e->label()]))
                                ->required(),

                            Forms\Components\DatePicker::make('payment_date')
                                ->label('Fecha de pago')
                                ->required()
                                ->default(now()),

                            Forms\Components\Select::make('account_id')
                                ->label('Cuenta destino')
                                ->options(Account::pluck('name', 'id'))
                                ->required()
                                ->searchable(),
                        ]),

                        Forms\Components\TextInput::make('note')
                            ->label('Nota (opcional)')
                            ->maxLength(255),
                    ])
                    ->action(function (Sale $record, array $data): void {
                        Payment::create([
                            'sale_id'            => $record->id,
                            'account_id'         => $data['account_id'],
                            'created_by_user_id' => auth()->id(),
                            'payment_date'       => $data['payment_date'],
                            'amount'             => $data['amount'],
                            'currency'           => Currency::from($data['currency']),
                            'fee_amount'         => 0,
                            'net_amount'         => $data['amount'],
                            'note'               => $data['note'] ?? '',
                        ]);
                        Notification::make()
                            ->title('Pago registrado')
                            ->body("{$record->client?->name} — {$record->currency->symbol()}{$data['amount']}")
                            ->success()
                            ->send();
                    })
                    ->modalHeading(fn (Sale $record) => "Registrar pago — {$record->client?->name}")
                    ->modalSubmitActionLabel('Confirmar pago')
                    ->modalWidth('lg'),

                Tables\Actions\Action::make('ver')
                    ->icon('heroicon-o-eye')
                    ->url(fn (Sale $r) => SaleResource::getUrl('view', ['record' => $r])),
            ])
            ->paginated([5, 10]);
    }
}
