<?php

namespace App\Filament\Pages;

use App\Filament\Resources\PaymentResource;
use App\Filament\Resources\RenewalResource;
use App\Filament\Resources\SaleResource;
use App\Filament\Widgets\CollectionsChartWidget;
use App\Filament\Widgets\KpiStatsWidget;
use App\Filament\Widgets\OverdueCxCWidget;
use App\Filament\Widgets\SalesChartWidget;
use App\Filament\Widgets\UpcomingRenewalsWidget;
use App\Filament\Widgets\WeeklyCollectionsWidget;
use Filament\Actions\Action;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Form;
use Filament\Pages\Dashboard as BaseDashboard;
use Filament\Pages\Dashboard\Concerns\HasFiltersForm;

class Dashboard extends BaseDashboard
{
    use HasFiltersForm;

    protected static ?string $navigationIcon  = 'heroicon-o-home';
    protected static ?string $navigationLabel = 'Dashboard';
    protected static ?int    $navigationSort  = -1;

    public function filtersForm(Form $form): Form
    {
        return $form->schema([
            Select::make('preset')
                ->label('Período')
                ->options([
                    'month'     => 'Este mes',
                    'lastmonth' => 'Mes anterior',
                    'weeks8'    => 'Últimas 8 semanas',
                    'months3'   => 'Últimos 3 meses',
                    'months6'   => 'Últimos 6 meses',
                    'year'      => 'Este año',
                    'custom'    => 'Personalizado',
                ])
                ->default('month')
                ->live()
                ->afterStateUpdated(function ($state, callable $set) {
                    if ($state === 'custom') return;
                    [$from, $to] = self::presetDates($state);
                    $set('desde', $from);
                    $set('hasta', $to);
                    // Despachar con los valores exactos ya conocidos (evita timing issues)
                    $this->dispatch('dashboardFiltersUpdated', filters: [
                        'preset' => $state,
                        'desde'  => $from,
                        'hasta'  => $to,
                    ]);
                }),

            DatePicker::make('desde')
                ->label('Desde')
                ->default(now()->startOfMonth()->toDateString())
                ->live()
                ->afterStateUpdated(function ($state, callable $set, callable $get) {
                    $set('preset', 'custom');
                    $this->dispatch('dashboardFiltersUpdated', filters: [
                        'preset' => 'custom',
                        'desde'  => $state,
                        'hasta'  => $get('hasta'),
                    ]);
                }),

            DatePicker::make('hasta')
                ->label('Hasta')
                ->default(now()->toDateString())
                ->live()
                ->afterStateUpdated(function ($state, callable $set, callable $get) {
                    $set('preset', 'custom');
                    $this->dispatch('dashboardFiltersUpdated', filters: [
                        'preset' => 'custom',
                        'desde'  => $get('desde'),
                        'hasta'  => $state,
                    ]);
                }),
        ]);
    }

    public static function presetDates(string $preset): array
    {
        return match ($preset) {
            'lastmonth' => [
                now()->subMonth()->startOfMonth()->toDateString(),
                now()->subMonth()->endOfMonth()->toDateString(),
            ],
            'weeks8' => [
                now()->subWeeks(7)->startOfWeek()->toDateString(),
                now()->toDateString(),
            ],
            'months3' => [
                now()->subMonths(3)->startOfMonth()->toDateString(),
                now()->toDateString(),
            ],
            'months6' => [
                now()->subMonths(6)->startOfMonth()->toDateString(),
                now()->toDateString(),
            ],
            'year' => [
                now()->startOfYear()->toDateString(),
                now()->toDateString(),
            ],
            default => [ // 'month'
                now()->startOfMonth()->toDateString(),
                now()->toDateString(),
            ],
        };
    }

    public function getWidgets(): array
    {
        return [
            KpiStatsWidget::class,
            SalesChartWidget::class,
            CollectionsChartWidget::class,
            WeeklyCollectionsWidget::class,
            OverdueCxCWidget::class,
            UpcomingRenewalsWidget::class,
        ];
    }

    public function getColumns(): int | array
    {
        return 2;
    }

    protected function getHeaderActions(): array
    {
        return [
            Action::make('nueva_venta')
                ->label('+ Nueva venta')
                ->url(SaleResource::getUrl('create'))
                ->icon('heroicon-o-currency-dollar')
                ->color('primary'),

            Action::make('nuevo_pago')
                ->label('+ Registrar pago')
                ->url(PaymentResource::getUrl('create'))
                ->icon('heroicon-o-credit-card')
                ->color('success'),

            Action::make('ver_cxc')
                ->label('Ver todas las CxC')
                ->url(SaleResource::getUrl('index'))
                ->icon('heroicon-o-clock')
                ->color('warning'),

            Action::make('ver_renovaciones')
                ->label('Ver renovaciones')
                ->url(RenewalResource::getUrl('index'))
                ->icon('heroicon-o-arrow-path')
                ->color('gray'),
        ];
    }
}
