<?php

namespace App\Filament\Widgets;

use App\Models\Line;
use App\Models\ProductionQuantity;
use App\Models\QualityValidation;
use Filament\Widgets\ChartWidget;
use Filament\Support\RawJs;
use Illuminate\Support\HtmlString;

class CumulativeChart extends ChartWidget
{
    protected static ?string $heading = 'Production Line Count';

    //protected $listeners = ['cumulativeChart'];

    protected static ?string $maxHeight = '400px';


    protected int|string|array $columnSpan = 12;


    // protected function getData(): array
    // {
    //     $selectedPlant = session('selected_plant');
    //     $activeFilter = $this->filter;

    //     // Define date range based on filter
    //     switch ($activeFilter) {
    //         case 'yesterday':
    //             $startDate = now()->subDay()->startOfDay();
    //             $endDate = now()->subDay()->endOfDay();
    //             break;
    //         case 'this_week':
    //             $startDate = now()->startOfWeek();
    //             $endDate = now()->endOfWeek();
    //             break;
    //         case 'this_month':
    //             $startDate = now()->startOfMonth();
    //             $endDate = now()->endOfMonth();
    //             break;
    //         default: // today
    //             $startDate = now()->startOfDay();
    //             $endDate = now()->endOfDay();
    //             break;
    //     }

    //     // Get all lines for selected plant
    //     $lines = Line::where('plant_id', $selectedPlant)
    //         ->pluck('name', 'id')
    //         ->toArray();

    //     // Get total production per line in the date range
    //     $production = \DB::table('production_quantities')
    //         ->select('line_id', \DB::raw('COUNT(*) as total_quantity'))
    //         ->whereBetween('created_at', [$startDate, $endDate])
    //         ->whereIn('line_id', array_keys($lines))
    //         ->groupBy('line_id')
    //         ->pluck('total_quantity', 'line_id')
    //         ->toArray();

    //     // Match quantities with lines (fill 0 if missing)
    //     $labels = [];
    //     $data = [];

    //     foreach ($lines as $lineId => $lineName) {
    //         $labels[] = $lineName;
    //         $data[] = $production[$lineId] ?? 0;
    //     }

    //     return [
    //         'labels' => $labels,
    //         'datasets' => [
    //             [
    //                 'label' => match ($activeFilter) {
    //                     'yesterday' => "Production Quantity (Yesterday)",
    //                     'this_week' => "Daily Production This Week",
    //                     'this_month' => "Weekly Production This Month",
    //                     default => "Today's Production",
    //             },
    //                 'data' => $data,
    //             ],
    //         ],
    //     ];
    // }



    protected function getData(): array
    {
        $selectedPlant = session('selected_plant');
       // $selectedStatus = session('success_status');
        $activeFilter = $this->filter;

        //  if (!$selectedPlant || !$selectedStatus) {
        //     return [
        //         'labels' => [],
        //         'datasets' => [],
        //     ];
        // }
         if (!$selectedPlant) {
            return [
                'labels' => [],
                'datasets' => [],
            ];
        }

        switch ($activeFilter)
        {
            case 'yesterday':
                $startDate = now()->subDay()->setTime(8, 0, 0);
                $endDate = now()->setTime(8, 0, 0);
                $groupBy = 'EXTRACT(HOUR FROM created_at)';
                break;

            case 'this_week':
                $startDate = now()->startOfWeek()->setTime(8, 0, 0);
                $endDate = now()->endOfWeek()->addDay()->setTime(8, 0, 0);
                $groupBy = 'EXTRACT(DOW FROM created_at)';
                break;

            case 'this_month':
                $startDate = now()->startOfMonth()->setTime(8, 0, 0);
                $endDate = now()->endOfMonth()->addDay()->setTime(8, 0, 0);
                $groupBy = "FLOOR((EXTRACT(DAY FROM created_at) - 1) / 7) + 1";
                break;

            default: // today
                $startDate = now()->setTime(8, 0, 0);
                $endDate = now()->copy()->addDay()->setTime(8, 0, 0);
                $groupBy = 'EXTRACT(HOUR FROM created_at)';
                break;
        }

        // Get lines with names and types
        $lines = Line::where('plant_id', $selectedPlant)->get(['id', 'name', 'type']);

        $lineNames = [];
        $fgLineIds = [];
        $nonFgLineIds = [];

        foreach ($lines as $line)
        {
            $lineNames[$line->id] = $line->name;

            if ($line->type == 'FG Line')
            {
                $fgLineIds[] = $line->id;
            }
            else
            {
                $nonFgLineIds[] = $line->id;
            }
        }

        //FG production from quality_validations
        $fgProduction = QualityValidation::select('line_id', \DB::raw('COUNT(*) as total_quantity'))
           // ->whereBetween('created_at', [$startDate, $endDate])
            ->where('created_at', '>=', $startDate)
            ->where('created_at', '<', $endDate)
            ->whereIn('line_id', $fgLineIds)
            ->groupBy('line_id')
            ->pluck('total_quantity', 'line_id')
            ->toArray();

        $nonFgQuery = ProductionQuantity::select('line_id', \DB::raw('COUNT(*) as total_quantity'))
            ->whereBetween('created_at', [$startDate, $endDate])
            ->whereIn('line_id', $nonFgLineIds);

        // if ($selectedStatus) {
        //     $nonFgQuery->where('success_status', $selectedStatus);
        // }

        $nonFgProduction = $nonFgQuery->groupBy('line_id')
            ->pluck('total_quantity', 'line_id')
            ->toArray();


        //Non-FG production from production_quantities
        // $nonFgProduction = ProductionQuantity::select('line_id', \DB::raw('COUNT(*) as total_quantity'))
        //     ->whereBetween('created_at', [$startDate, $endDate])
        //     ->whereIn('line_id', $nonFgLineIds)
        //     ->groupBy('line_id')
        //     ->pluck('total_quantity', 'line_id')
        //     ->toArray();

        //Separate FG and non-FG into different datasets
        $labels = [];
        $fgData = [];
        $nonFgData = [];

        foreach ($lineNames as $lineId => $lineName) {
            $labels[] = $lineName;

            if (in_array($lineId, $fgLineIds))
            {
                $fgData[] = $fgProduction[$lineId] ?? 0;
                $nonFgData[] = null;
            }
            else
            {
                $nonFgData[] = $nonFgProduction[$lineId] ?? 0;
                $fgData[] = null;
            }
        }

        $nonFgData = array_map(function ($value) {
        return ($value == 0 || is_null($value)) ? null : $value;
            }, $nonFgData);

            $fgData = array_map(function ($value) {
                return ($value == 0 || is_null($value)) ? null : $value;
            }, $fgData);


        return [
            'labels' => $labels,
            'datasets' => array_filter([
                [
                    'label' => match ($activeFilter) {
                        'yesterday' => "Production Quantity (Yesterday)",
                        'this_week' => "Daily Production This Week",
                        'this_month' => "Weekly Production This Month",
                        default => "Today's Production",
                    },
                    'data' => $nonFgData,
                    //'backgroundColor' => '#3b82f6', // Blue for non-FG
                ],
                [
                    'label' => match ($activeFilter) {
                        'yesterday' => "FG Count (Yesterday)",
                        'this_week' => "FG Count This Week",
                        'this_month' => "FG Count This Month",
                        default => "Today's FG Count",
                    },
                    'data' => $fgData,
                    // 'backgroundColor' => '#ef4444', // Red for FG
                ],

            ]),

        ];

    }

    protected function getType(): string
    {
        return 'bar';
    }

    protected function getFilters(): ?array
    {
        return [
            'today' => 'Today',
            'yesterday' => 'Yesterday',
            'this_week'=> 'This Week',
            'this_month'=> 'This Month',
        ];
    }

    protected function getOptions(): array
    {
        return [
            // 'plugins' => [
            //     'datalabels' => false,
            // ],
                'plugins' => [
                'datalabels' => [
                    'anchor' => 'start',      // Positions the label relative to the top of the bar
                    'align' => 'start',       // Aligns the label above the bar
                    'offset' => -15,          // Adjust if needed (positive moves up, negative moves down)
                    'color' => '#000',
                    'font' => [
                        'weight' => 'bold',
                    ],
                    'formatter' => RawJs::make('function(value) {
                        return value;
                    }'),
                ],
            ],
            'scales' => [
                'y' => [
                    'beginAtZero' => true, //Start Y-axis from 0
                    'ticks' => [
                        'stepSize' => 0.5,
                    ],
                ],
            ],
        ];
    }

    public function getHeading(): HtmlString|string|null
    {
        $selectedPlant = session('selected_plant');

        // Dynamic title and colors
        $title = 'Total Production';
        $titleColor = '#1e40af';
        $iconColor = 'text-blue-500';
        $textColor = '#b45309';

        $iconSvg = '
            <svg xmlns="http://www.w3.org/2000/svg"
                class="w-8 h-8 ' . $iconColor . '" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                <path stroke-linecap="round" stroke-linejoin="round" d="M3 3v18h18M7 13h2v5H7zm4-8h2v13h-2zm4 5h2v8h-2z" />
            </svg>
        ';

        // Get chart data for the selected plant
        $data = $this->getData();
        $fgData = $data['datasets'][1]['data'] ?? [];
        $nonFgData = $data['datasets'][0]['data'] ?? [];

        // Sum all non-null values for cumulative total
        $totalCount = array_sum(array_filter($fgData, fn($v) => !is_null($v)))
                    + array_sum(array_filter($nonFgData, fn($v) => !is_null($v)));

        $count = number_format($totalCount);

        return new HtmlString('
            <div class="flex items-center justify-between px-4 py-2 bg-white rounded-lg shadow-sm">
                <div class="flex items-center space-x-3">
                    ' . $iconSvg . '
                    <div style="margin-left: 12px; color: ' . $textColor . '; ">
                        <p style="color:' . $titleColor . '; font-weight: 600;">' . e($title) . '</p>
                        <h2 class="text-3xl font-extrabold text-gray-800">' . $count . '</h2>
                    </div>
                </div>
            </div>
        ');
    }



    // public static function canView(): bool
    // {
    //     return request()->routeIs([
    //         'filament.pages.hourly-production',
    //         'filament.admin.resources.production-quantities.create',
    //     ]);
    // }

}
