<?php

namespace App\Filament\Widgets;

use App\Models\Line;
use App\Models\ProductionQuantity;
use App\Models\QualityValidation;
use Filament\Widgets\StatsOverviewWidget as BaseWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;

class ProductionQuantityStat extends BaseWidget
{
    protected $listeners = ['filtersUpdated' => 'updateStats'];

    public $selectedPlant;
    public $selectedLine;
    public $selectedFilter = 'Today';

    public function updateStats($data=null)
    {
         if (!$data) {
                return;
        }
        $this->selectedPlant = $data['plant'] ?? null;
        $this->selectedLine = $data['line'] ?? null;
        //$this->selectedFilter = $data['filter'] ?? 'today';
         $this->selectedFilter = $data['filter'] ?? 'today';

        $this->dispatch('$refresh');

    }


     protected function getStats(): array
    {
        if (!$this->selectedPlant || !$this->selectedLine) {
            return [
                Stat::make('Production Count', 0)
                    ->description('Select Plant & Line')
                    ->color('success'),
            ];
        }

        $line = Line::find($this->selectedLine);

        if (!$line) {
            return [
                Stat::make('Production Count', 0)
                    ->description('Line not found')
                    ->color('success'),
            ];
        }

        $start = now()->setTime(8, 0, 0);
        $end   = now()->copy()->addDay()->setTime(8, 0, 0);

        if ($this->selectedFilter == 'yesterday') {
            $start = now()->subDay()->setTime(8, 0, 0);
            $end   = now()->setTime(8, 0, 0);
        } elseif ($this->selectedFilter == 'this_week') {
            $start = now()->startOfWeek()->setTime(8, 0, 0);
            $end   = now()->endOfWeek()->addDay()->setTime(8, 0, 0);
        } elseif ($this->selectedFilter == 'this_month') {
            $start = now()->startOfMonth()->setTime(8, 0, 0);
            $end   = now()->endOfMonth()->addDay()->setTime(8, 0, 0);
        }

        if ($line->type === 'FG Line') {
            $count = QualityValidation::where('line_id', $line->id)
                ->whereBetween('created_at', [$start, $end])
                ->count();

            return [
                Stat::make('FG Production Count', $count)
                    ->description("FG production for this line")
                    ->color('success')
                    ->icon('heroicon-s-check-circle'),
            ];
        } else {
            $count = ProductionQuantity::where('line_id', $line->id)
                ->whereBetween('created_at', [$start, $end])
                ->count();

            return [
                Stat::make('Total Production Count', $count)
                    ->description("Total production for this line")
                    ->color('primary')
                     ->icon('heroicon-s-cube'),
            ];
        }
    }
}
