<?php

namespace App\Filament\Widgets;

use App\Models\InvoiceValidation;
use App\Models\Line;
use App\Models\Plant;
use DB;
use Filament\Widgets\ChartWidget;
use Filament\Support\RawJs;

class InvoiceChart extends ChartWidget
{
    protected static ?string $heading = 'Chart';

    protected int|string|array $columnSpan = 12;

    protected $listeners = ['invoiceChart'];


    protected function getData(): array
    {
        $selectedPlant = session('selec_plant');
        $selectedInvoice = session('select_invoice');

        $fromDt = session('from_date');
        $toDt = session('to_date');

        $activeFilter = $this->filter; // Assuming filter is passed and activeFilter can be 'yesterday', 'this_week', 'this_month'

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

        $isCustomDate = !empty($fromDt) && !empty($toDt);

        if (!empty($fromDt) && !empty($toDt)) {
            $startDate = \Carbon\Carbon::parse($fromDt)->setTime(8, 0, 0);
            $endDate = \Carbon\Carbon::parse($toDt)->addDay()->setTime(8, 0, 0);
            $groupBy = 'none';
        }
        else{

            // Define the date range based on the active filter
            if ($activeFilter == 'yesterday') {
                $startDate = now()->subDay()->setTime(8, 0, 0);
                $endDate = now()->setTime(8, 0, 0);
                $groupBy = 'none'; // No grouping by hour
            } elseif ($activeFilter == 'this_week') {
                $startDate = now()->startOfWeek()->setTime(8, 0, 0);
                $endDate = now()->endOfWeek()->addDay()->setTime(8, 0, 0);
                $groupBy = 'day_of_week';
            } elseif ($activeFilter == 'this_month') {
                $startDate = now()->startOfMonth()->setTime(8, 0, 0);
                $endDate = now()->endOfMonth()->setTime(8, 0, 0);
                $groupBy = 'week_of_month';
            } else {
                $startDate = now()->setTime(8, 0, 0);
                $endDate = now()->copy()->addDay()->setTime(8, 0, 0);
                $groupBy = 'none'; // No grouping by hour
            }
        }

        // Get the counts for Imported Invoices (unique invoice numbers) and Completed Invoices
        if ($selectedInvoice == 'individual_material')
        {
            $importedInvoicesCount = InvoiceValidation::where('plant_id', $selectedPlant)
                ->where('quantity', 1)
                ->whereBetween('created_at', [$startDate, $endDate]) // Filter by date range
                ->distinct('invoice_number') // Only distinct invoice numbers
                ->count('invoice_number');

            $completedInvoicesCount = InvoiceValidation::select('invoice_number')
                ->where('plant_id', $selectedPlant)
                ->where('quantity', 1)
                ->whereBetween('updated_at', [$startDate, $endDate])
                ->groupBy('invoice_number')
                ->havingRaw(
                    "COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)"
                )
                ->count();
        }
        elseif ($selectedInvoice == 'serial_invoice')
        {
            $importedInvoicesCount = InvoiceValidation::where('plant_id', $selectedPlant)
                ->whereNull('quantity')
                ->whereBetween('created_at', [$startDate, $endDate])
                ->distinct('invoice_number')
                ->count('invoice_number');

             $completedInvoicesCount = InvoiceValidation::select('invoice_number')
                ->where('plant_id', $selectedPlant)
                ->whereNull('quantity')
                ->whereBetween('created_at', [$startDate, $endDate])
                ->groupBy('invoice_number')
                ->havingRaw(
                    "COUNT(*) = SUM(CASE WHEN scanned_status = 'Scanned' THEN 1 ELSE 0 END)"
                )
                ->count();

        }
        elseif ($selectedInvoice == 'bundle_material')
        {
            $importedInvoicesCount = InvoiceValidation::where('plant_id', $selectedPlant)
                ->where('quantity', '>', 1)
                ->whereBetween('created_at', [$startDate, $endDate]) // Filter by date range
                ->distinct('invoice_number') // Only distinct invoice numbers
                ->count('invoice_number');

            $completedInvoicesCount = InvoiceValidation::select('invoice_number')
                ->where('plant_id', $selectedPlant)
                ->where('quantity', '>', 1)
                ->whereBetween('created_at', [$startDate, $endDate])
                ->groupBy('invoice_number')
                ->havingRaw(
                    "COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)"
                )
                ->count();
        }

        // Prepare the chart data
        $labels = []; // Labels for each bar
        $datasets = []; // Datasets for the chart

        if (!empty($fromDt) && !empty($toDt)) {
            $activeFilter = null;
        }

        if ($isCustomDate || in_array($activeFilter, ['yesterday'])) {
            $labels = ['Imported Invoice', 'Completed Invoice'];
            $datasets = [[
                'label' => 'Invoices',
                'data' => [$importedInvoicesCount, $completedInvoicesCount],
                'backgroundColor' => ['rgba(75, 192, 192, 1)', 'rgba(23, 211, 80, 1)'],
                'fill' => false,
            ]];
        }
        elseif ($isCustomDate || $activeFilter == 'this_week')
        {
            $daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
            $importedInvoicesPerDay = array_fill(0, 7, 0);
            $completedInvoicesPerDay = array_fill(0, 7, 0);

            for ($index = 0; $index < 7; $index++) {
                $dayStart = now()->startOfWeek()->addDays($index)->setTime(8, 0, 0);
                $dayEnd = $dayStart->copy()->addDay()->setTime(8, 0, 0);

                $query = InvoiceValidation::where('plant_id', $selectedPlant);

                // Build completedQuery with only 'invoice_number' in select
                $completedQuery = InvoiceValidation::select('invoice_number')
                    ->where('plant_id', $selectedPlant);

                if ($selectedInvoice == 'individual_material')
                {
                    $query->where('quantity', 1)->whereBetween('created_at', [$dayStart, $dayEnd]);

                    $completedQuery->where('quantity', 1)
                        ->whereBetween('created_at', [$dayStart, $dayEnd])
                        ->groupBy('invoice_number')
                        ->havingRaw(
                            "COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)"
                        );
                }
                elseif ($selectedInvoice == 'serial_invoice')
                {
                    $query->whereNull('quantity')->whereBetween('created_at', [$dayStart, $dayEnd]);

                    $completedQuery->whereNull('quantity')
                        ->whereBetween('created_at', [$dayStart, $dayEnd])
                        ->groupBy('invoice_number')
                        ->havingRaw(
                            "COUNT(*) = SUM(CASE WHEN scanned_status = 'Scanned' THEN 1 ELSE 0 END)"
                        );
                }
                elseif ($selectedInvoice == 'bundle_material')
                {
                    $query->where('quantity', '>', 1)->whereBetween('created_at', [$dayStart, $dayEnd]);

                    $completedQuery->where('quantity', '>', 1)
                        ->whereBetween('created_at', [$dayStart, $dayEnd])
                        ->groupBy('invoice_number')
                        ->havingRaw(
                            "COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)"
                        );
                }

                // Imported invoices count (distinct invoice_number)
                $importedInvoicesPerDay[$index] = $query->distinct('invoice_number')->count('invoice_number');

                $completedInvoicesPerDay[$index] = $completedQuery->count();
            }

            $labels = $daysOfWeek;
            $datasets = [
                [
                    'label' => 'Imported Invoices',
                    'data' => $importedInvoicesPerDay,
                    'backgroundColor' => 'rgba(75, 192, 192, 1)',
                ],
                [
                    'label' => 'Completed Invoices',
                    'data' => $completedInvoicesPerDay,
                    'backgroundColor' => 'rgba(23, 211, 80, 1)',
                ],
            ];
        }
        elseif ($isCustomDate || $activeFilter == 'this_month') {
            $startOfMonth = now()->startOfMonth()->setTime(8, 0, 0);
            $endOfMonth = now()->endOfMonth()->addDay()->setTime(23, 59, 59); // include full last day
            $monthName = $startOfMonth->format('M');

            $labels = [];
            $weekStart = $startOfMonth->copy();
            $importedInvoicesPerWeek = [];
            $completedInvoicesPerWeek = [];

            $weekIndex = 0;
            while ($weekStart <= $endOfMonth) {
                // $weekEnd = $weekStart->copy()->addDays(6);
                $weekEnd = $weekStart->copy()->addDays(6)->endOfDay();

                  // If week end exceeds end of month, limit it
                if ($weekEnd->greaterThan($endOfMonth)) {
                    $weekEnd = $endOfMonth->copy()->endOfDay();
                }

                $startDay = $weekStart->format('j');
                $endDay = $weekEnd->format('j');

                // $startDay = $weekStart->format('j');
                // $weekEndLimit = $weekEnd->copy()->subDay();
                // $actualEnd = $weekEndLimit->greaterThan($endOfMonth) ? $endOfMonth : $weekEndLimit;
                // $endDay = $actualEnd->format('j');

                $labels[] = "{$monthName}({$startDay}-{$endDay})";

                $queryImported = InvoiceValidation::where('plant_id', $selectedPlant)
                    ->whereBetween('created_at', [$weekStart, $weekEnd]);

                if ($selectedInvoice == 'individual_material')
                {
                    $queryImported->where('quantity', 1);
                }
                elseif ($selectedInvoice == 'serial_invoice')
                {
                    $queryImported->whereNull('quantity');
                }
                elseif ($selectedInvoice == 'bundle_material')
                {
                    $queryImported->where('quantity', '>', 1);
                }

                $importedInvoicesPerWeek[$weekIndex] = $queryImported->distinct('invoice_number')->count('invoice_number');

                // --- Completed ---
                $queryCompleted = InvoiceValidation::select('invoice_number')
                    ->where('plant_id', $selectedPlant)
                    ->whereBetween('created_at', [$weekStart, $weekEnd]);

                if ($selectedInvoice == 'individual_material') {
                    $queryCompleted->where('quantity', 1)
                        ->groupBy('invoice_number')
                        ->havingRaw("COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)");
                } elseif ($selectedInvoice == 'serial_invoice') {
                    $queryCompleted->whereNull('quantity')
                        ->groupBy('invoice_number')
                        ->havingRaw("COUNT(*) = SUM(CASE WHEN scanned_status = 'Scanned' THEN 1 ELSE 0 END)");
                } elseif ($selectedInvoice == 'bundle_material') {
                    $queryCompleted->where('quantity', '>', 1)
                        ->groupBy('invoice_number')
                        ->havingRaw("COUNT(*) = SUM(CASE WHEN serial_number IS NOT NULL AND serial_number != '' THEN 1 ELSE 0 END)");
                }

                $completedInvoicesPerWeek[$weekIndex] = $queryCompleted->count();

                // Move to next week
                // $weekStart = $weekEnd;
                $weekStart = $weekEnd->copy()->addDay(1);
                $weekIndex++;
            }

            $datasets = [
                [
                    'label' => 'Imported Invoices',
                    'data' => $importedInvoicesPerWeek,
                    'backgroundColor' => 'rgba(75, 192, 192, 1)',
                ],
                [
                    'label' => 'Completed Invoices',
                    'data' => $completedInvoicesPerWeek,
                    'backgroundColor' => 'rgba(23, 211, 80, 1)',
                ],
            ];
        }
        elseif (!$isCustomDate)
        {
            $labels = ['Imported Invoice', 'Completed Invoice'];
            $datasets = [[
                'label' => 'Invoices',
                'data' => [$importedInvoicesCount, $completedInvoicesCount],
                'backgroundColor' => ['rgba(75, 192, 192, 1)', 'rgba(23, 211, 80, 1)'],
                'fill' => false,
            ]];
        }

        foreach ($datasets as &$dataset)
        {
            $dataset['data'] = array_map(function ($value) {
                return ($value == 0 || is_null($value)) ? null : $value;
            }, $dataset['data']);
        }

        return [
            'datasets' => $datasets,
            'labels' => $labels,
        ];
    }


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

    public static function getDefaultName(): string
    {
        return 'invoice-chart';
    }

    protected function getOptions(): array
    {
        return [
            'plugins' => [
                'datalabels' => [
                    'anchor' => 'start',
                    'align' => 'start',
                    'offset' => -15,
                    'color' => '#000',
                    'font' => [
                        'weight' => 'bold',
                    ],
                    'formatter' => RawJs::make('function(value) {
                        return value;
                    }'),
                ],
            ],
            'scales' => [
                'y' => [
                    'beginAtZero' => true,
                    'ticks' => [
                        'stepSize' => 1,
                    ],
                ],
            ],
        ];
    }

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

    public static function canView(): bool
    {
        //  dd('Checking route:', request()->route()->getName());
        // to avoid showing the widget in other pages
        return request()->routeIs('filament.admin.pages.invoice-dashboard');
    }

}
