<?php

namespace App\Filament\Widgets;

use Filament\Notifications\Notification;
use Filament\Support\Assets\Js;
use Filament\Support\RawJs;
use Filament\Widgets\ChartWidget;
use Illuminate\Contracts\View\View;
use Illuminate\Support\HtmlString;

class ItemOverview extends ChartWidget
{
    protected static ?string $heading = 'Hourly Production';

    public $totalCount = 0;


    protected int|string|array $columnSpan = '12';

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

    protected $listeners = ['filtersUpdated' => '$refresh'];

    protected static string $color = 'info';
    protected static ?string $icon = 'heroicon-o-chart-bar';
    protected static ?string $iconColor = 'info';
    protected static ?string $iconBackgroundColor = 'info';
    protected static ?string $label = 'Total Production';
    protected static ?string $badgeColor = 'success';

    protected static ?string $badgeIcon = 'heroicon-o-check-circle';

    protected static ?string $badgeIconPosition = 'after';

    protected static ?string $badgeSize = 'xs';


    public function getData(): array
    {
        $activeFilter = $this->filter;

        $selectedPlant = session('selected_plant') ?? session('select_plant');
        $selectedLine = session('selected_line') ?? session('select_line');

        $selectedStatus = session('selected_status');

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

        $this->dispatch('filtersUpdated', [
        'plant' => $selectedPlant,
        'line' => $selectedLine,
        'filter' => $activeFilter,
        ]);

         // Determine if line is FG Line
        $line = \App\Models\Line::find($selectedLine);
        $isFgLine = $line?->type == 'FG Line';

          // Set date range and groupBy logic
        if ($activeFilter == 'yesterday')
        {
            $startDate = now()->subDay()->setTime(8, 0, 0);
            $endDate = now()->setTime(8, 0, 0);
            $groupBy = 'EXTRACT(HOUR FROM created_at)';
        }
        elseif ($activeFilter == 'this_week')
        {
            $startDate = now()->startOfWeek()->setTime(8, 0, 0);
            $endDate = now()->endOfWeek()->addDay()->setTime(8, 0, 0);
            $groupBy = 'EXTRACT(DOW FROM created_at)';
        }
        elseif ($activeFilter == 'this_month')
        {
            $startDate = now()->startOfMonth();
            $endDate = now()->endOfMonth();
            $groupBy = "FLOOR((EXTRACT(DAY FROM created_at) - 1) / 7) + 1";
        }
        else
        {
            $startDate = now()->setTime(8, 0, 0);
            $endDate = now()->copy()->addDay()->setTime(8, 0, 0);
            $groupBy = 'EXTRACT(HOUR FROM created_at)';
        }

        $baseTable = $isFgLine ? 'quality_validations' : 'production_quantities';

        // $query = \DB::table($baseTable)
        // ->selectRaw("$groupBy AS time_unit, COUNT(*) AS total_quantity")
        // ->where('created_at', '>=', $startDate)
        // ->where('created_at', '<', $endDate)
        // ->where('plant_id', $selectedPlant)
        // ->where('line_id', $selectedLine)
        // ->groupByRaw($groupBy)
        // ->orderByRaw($groupBy)
        // ->pluck('total_quantity', 'time_unit')
        // ->toArray();
        $query = \DB::table($baseTable)
        ->selectRaw("$groupBy AS time_unit, COUNT(*) AS total_quantity")
        ->where('created_at', '>=', $startDate)
        ->where('created_at', '<', $endDate)
        ->where('plant_id', $selectedPlant)
        ->where('line_id', $selectedLine);

        if ($selectedStatus && !$isFgLine) {
            // Only filter success_status for production_quantities (Non-FG)
            $query->where('success_status', $selectedStatus);
        }

        $query = $query->groupByRaw($groupBy)
            ->orderByRaw($groupBy)
            ->pluck('total_quantity', 'time_unit')
            ->toArray();


        if ($activeFilter == 'this_month')
        {
            $weeksCount = ceil($endDate->day / 7);
            $allWeeks = array_fill(1, $weeksCount, 0);
            $data = array_replace($allWeeks, $query);

            $labels = [];
            for ($i = 1; $i <= $weeksCount; $i++) {
                $weekStart = $startDate->copy()->addDays(($i - 1) * 7)->format('d M');
                $weekEnd = $startDate->copy()->addDays($i * 7 - 1)->min($endDate)->format('d M');
                $labels[] = "Week $i ($weekStart - $weekEnd)";
            }

            $orderedData = array_values($data);
        }
        elseif ($activeFilter == 'this_week')
        {
            $labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
            $data = array_fill(0, 7, 0);
            foreach ($query as $dow => $count) {
                $data[$dow] = $count;
            }
            $orderedData = [
                $data[1] ?? 0, $data[2] ?? 0, $data[3] ?? 0,
                $data[4] ?? 0, $data[5] ?? 0, $data[6] ?? 0,
                $data[0] ?? 0,
            ];
        }
        // else
        // {
        //     $allHours = array_fill(0, 24, 0);
        //     $data = array_replace($allHours, $query);

        //     $shiftedKeys = array_merge(range(8, 23), range(0, 7));
        //     $orderedData = array_map(fn($hour) => $data[$hour], $shiftedKeys);

        //     $labels = array_map(fn ($hour) => date("g A", strtotime("$hour:00")), $shiftedKeys);
        // }

        else
        {
            $allHours = array_fill(0, 24, 0);
            $data = array_replace($allHours, $query);

            $shiftedData = [];
            foreach ($data as $hour => $count) {
                $nextHour = ($hour + 1) % 24;
                $shiftedData[$nextHour] = $count;
            }
            $shiftedKeys = array_merge(range(9, 23), range(0, 8));
            $orderedData = array_map(fn($hour) => $shiftedData[$hour] ?? 0, $shiftedKeys);

            $labels = array_map(function($hour) {
                $prevHour = ($hour - 1 + 24) % 24;
                return sprintf("%s",
                    date("g A", strtotime("$hour:00")),
                    date("g", strtotime("$prevHour:00")),
                    date("g A", strtotime("$hour:00"))
                );
            }, $shiftedKeys);
        }

        $this->totalCount = array_sum($orderedData);


        return [
            'datasets' => [
                [
                    'label' => match ($activeFilter) {
                        'this_week' => $isFgLine ? 'Daily FG Count This Week' : 'Daily Production This Week',
                        'this_month' => $isFgLine ? 'Weekly FG Count This Month' : 'Weekly Production This Month',
                        'yesterday' => $isFgLine ? "Yesterday's FG Count" : "Yesterday's Hourly Production",
                        default => $isFgLine ? "Today's FG Count" : "Today's Hourly Production",
                    },
                    'data' => $orderedData,
                    // 'interaction' => [
                    //     'mode' => 'nearest',
                    //     'axis' => 'x',
                    //     'intersect' => false,
                    // ],
                    'borderColor' => 'rgba(75, 192, 192, 1)',
                    'backgroundColor' => 'rgba(75, 192, 192, 0.2)',
                    'fill' => false,
                    'tension' => 0.3,
                ],
            ],
            'labels' => $labels,
        ];
    }

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

    protected function getOptions(): array
    {
        return [
           'plugins' => [
            'datalabels' => [
                'anchor' => 'end', // Change to 'end' to align to the right edge of the bar
                'align' => 'right', // Align text to the right (optional, for label text alignment)
                'offset' => 3, // Move label to the right by ~11px (≈3mm)
                'color' => '#000',
                'font' => [
                    'weight' => 'bold',
                ],
                'formatter' => 'function(value) { return Number(value); }',
            ],
        ],
            'scales' => [
                'y' => [
                    'beginAtZero' => true,
                    'ticks' => [
                        'stepSize' => 0.5,
                    ],
                ],
            ],
        ];
    }

    public function getHeading(): HtmlString|string|null
    {
        // Detect selected line & type
        $selectedLine = session('selected_line') ?? session('select_line');
        $line = \App\Models\Line::find($selectedLine);
        $isFgLine = $line?->type == 'FG Line';

        // Dynamic title and icon
        $title = $isFgLine ? 'FG Line Production' : 'Total Production';
         $titleColor = $isFgLine ? '#16a34a' : '#1e40af';
        //$iconColor = $isFgLine ? 'text-green-500' : 'text-blue-500';
          $iconColor = $isFgLine ? 'text-green-500' : 'text-blue-500';
   //$textColor = $isFgLine ? '#16a34a' : '#3b82f6';
   $textColor = $isFgLine ? '#0f766e' : '#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>
        ';

        $count = number_format($this->totalCount ?? 0);

        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>
        ');
    }




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

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