<?php

namespace App\Filament\Widgets;

use App\Enums\PaymentStatus;
use App\Models\Sale;
use App\Models\Payment;
use App\Models\SystemSetting;
use Carbon\Carbon;
use Filament\Widgets\StatsOverviewWidget as BaseWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
use Illuminate\Support\Facades\DB;
use Livewire\Attributes\On;

class KpiStatsWidget extends BaseWidget
{
    protected static ?int $sort = 1;
    protected int | string | array $columnSpan = 'full';
    protected static ?string $pollingInterval = null;

    #[On('dashboardFiltersUpdated')]
    public function onFiltersUpdated(array $filters): void
    {
        $this->filters = $filters;
    }

    protected function getStats(): array
    {
        $rate  = (float) SystemSetting::current()->exchange_rate_usd_bob;

        $desde = $this->filters['desde'] ?? now()->startOfMonth()->toDateString();
        $hasta = $this->filters['hasta'] ?? now()->toDateString();

        $periodoLabel = Carbon::parse($desde)->format('d/m') . ' – ' . Carbon::parse($hasta)->format('d/m/Y');

        // ── Vendido en período ────────────────────────────────────────
        $ventasUsd = Sale::whereBetween('sale_date', [$desde, $hasta])
            ->where('currency', 'USD')->sum('gross_amount');
        $ventasBob = Sale::whereBetween('sale_date', [$desde, $hasta])
            ->where('currency', 'BOB')->sum('gross_amount');
        $ventasTotal = $ventasUsd + ($ventasBob / $rate);

        // ── Cobrado en período ────────────────────────────────────────
        $cobradoUsd = Payment::whereBetween('payment_date', [$desde, $hasta])
            ->where('currency', 'USD')->sum('net_amount');
        $cobradoBob = Payment::whereBetween('payment_date', [$desde, $hasta])
            ->where('currency', 'BOB')->sum('net_amount');
        $cobradoTotal = $cobradoUsd + ($cobradoBob / $rate);

        // ── CxC total (saldo pendiente, sin filtro de fecha) ─────────
        $cxcUsd = Sale::where('payment_status', '!=', PaymentStatus::Paid->value)
            ->where('currency', 'USD')
            ->selectRaw('SUM(gross_amount - collected_amount_cached) as saldo')
            ->value('saldo') ?? 0;
        $cxcBob = Sale::where('payment_status', '!=', PaymentStatus::Paid->value)
            ->where('currency', 'BOB')
            ->selectRaw('SUM(gross_amount - collected_amount_cached) as saldo')
            ->value('saldo') ?? 0;
        $cxcTotal = $cxcUsd + ($cxcBob / $rate);

        // ── Flujo (% cobrado del vendido del período) ─────────────────
        $flujo = $ventasTotal > 0 ? round(($cobradoTotal / $ventasTotal) * 100, 1) : 0;

        return [
            Stat::make('Vendido en período', '$' . number_format($ventasTotal, 2))
                ->description("USD {$ventasUsd} · BOB {$ventasBob} | {$periodoLabel}")
                ->color('primary')
                ->icon('heroicon-o-currency-dollar'),

            Stat::make('Cobrado en período', '$' . number_format($cobradoTotal, 2))
                ->description("USD {$cobradoUsd} · BOB {$cobradoBob} | {$periodoLabel}")
                ->color('success')
                ->icon('heroicon-o-check-circle'),

            Stat::make('CxC Pendiente (total)', '$' . number_format($cxcTotal, 2))
                ->description("USD {$cxcUsd} · BOB {$cxcBob} en saldo abierto")
                ->color('danger')
                ->icon('heroicon-o-clock'),

            Stat::make('Flujo del período', $flujo . '%')
                ->description('% vendido ya cobrado en el período')
                ->color($flujo >= 80 ? 'success' : ($flujo >= 50 ? 'warning' : 'danger'))
                ->icon('heroicon-o-arrow-trending-up'),
        ];
    }
}
