<?php

namespace App\Filament\Widgets;

use App\Models\InvoiceDataValidation;
use App\Models\InvoiceOutValidation;
use App\Models\InvoiceValidation;
use Filament\Widgets\ChartWidget;
use Filament\Support\RawJs;

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

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

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

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

        if ($selectedDistribution == 'Direct Sale')
        {

            $totalInvoices = InvoiceDataValidation::where('plant_id', $selectedPlant)
                ->where('distribution_channel_desc', $selectedDistribution)
                ->whereBetween('document_date', [$startDate, $endDate])
                ->distinct('document_number')
                ->pluck('document_number')
                ->toArray();

            if (empty($totalInvoices)) {
                return [
                    'labels' => ['Total', 'Went Out', 'Pending'],
                    'datasets' => [
                        [
                            'label' => 'Invoice Count',
                            'data' => [0, 0, 0],
                            'backgroundColor' => ['#60A5FA', '#34D399', '#F87171'],
                        ],
                    ],
                ];
            }

            $wentOutInvoices = InvoiceOutValidation::where('plant_id', $selectedPlant)
                ->whereIn('qr_code', $totalInvoices)
                ->whereBetween('scanned_at', [$startDate, $endDate])
                ->distinct('qr_code')
                ->pluck('qr_code')
                ->toArray();

            $totalCount = count($totalInvoices);
            $wentOutCount = count($wentOutInvoices);
            $pendingCount = $totalCount - $wentOutCount;

            return [
                'labels' => ['Total Invoices', 'Went Out', 'Pending'],
                'datasets' => [
                    [
                        'label' => ucfirst(str_replace('_', ' ', $activeFilter)),
                        'data' => [$totalCount, $wentOutCount, $pendingCount],
                        'backgroundColor' => ['#60A5FA', '#34D399', '#F87171'], // blue, green, red
                    ],
                ],
            ];
        }
        elseif ($selectedDistribution == 'Branch Sale')
        {
            $totalInvoices = InvoiceDataValidation::where('plant_id', $selectedPlant)
                ->where('distribution_channel_desc', $selectedDistribution)
                ->whereBetween('document_date', [$startDate, $endDate])
                ->distinct('document_number')
                ->pluck('document_number')
                ->toArray();

            if (empty($totalInvoices)) {
                return [
                    'labels' => ['Total', 'Went Out', 'Pending'],
                    'datasets' => [
                        [
                            'label' => 'Invoice Count',
                            'data' => [0, 0, 0],
                            'backgroundColor' => ['#60A5FA', '#34D399', '#F87171'],
                        ],
                    ],
                ];
            }

            $wentOutInvoices = InvoiceOutValidation::where('plant_id', $selectedPlant)
                ->whereIn('qr_code', $totalInvoices)
                ->whereBetween('scanned_at', [$startDate, $endDate])
                ->distinct('qr_code')
                ->pluck('qr_code')
                ->toArray();

            $totalCount = count($totalInvoices);
            $wentOutCount = count($wentOutInvoices);
            $pendingCount = $totalCount - $wentOutCount;

            return [
                'labels' => ['Total Invoices', 'Went Out', 'Pending'],
                'datasets' => [
                    [
                        'label' => ucfirst(str_replace('_', ' ', $activeFilter)),
                        'data' => [$totalCount, $wentOutCount, $pendingCount],
                        'backgroundColor' => ['#60A5FA', '#34D399', '#F87171'], // blue, green, red
                    ],
                ],
            ];
        }
        elseif ($selectedDistribution == 'Internal Transfer')
        {
            $totalInvoices = InvoiceDataValidation::where('plant_id', $selectedPlant)
                ->where('distribution_channel_desc', $selectedDistribution)
                ->whereBetween('document_date', [$startDate, $endDate])
                ->distinct('document_number')
                ->pluck('document_number')
                ->toArray();

            if (empty($totalInvoices)) {
                return [
                    'labels' => ['Total', 'Went Out', 'Pending'],
                    'datasets' => [
                        [
                            'label' => 'Invoice Count',
                            'data' => [0, 0, 0],
                            'backgroundColor' => ['#60A5FA', '#34D399', '#F87171'],
                        ],
                    ],
                ];
            }

            $wentOutInvoices = InvoiceOutValidation::where('plant_id', $selectedPlant)
                ->whereIn('qr_code', $totalInvoices)
                ->whereBetween('scanned_at', [$startDate, $endDate])
                ->distinct('qr_code')
                ->pluck('qr_code')
                ->toArray();

            $totalCount = count($totalInvoices);
            $wentOutCount = count($wentOutInvoices);
            $pendingCount = $totalCount - $wentOutCount;

            return [
                'labels' => ['Total Invoices', 'Went Out', 'Pending'],
                'datasets' => [
                    [
                        'label' => ucfirst(str_replace('_', ' ', $activeFilter)),
                        'data' => [$totalCount, $wentOutCount, $pendingCount],
                        'backgroundColor' => ['#60A5FA', '#34D399', '#F87171'], // blue, green, red
                    ],
                ],
            ];
        }
        elseif ($selectedDistribution == 'WOS')
        {
            $totalInvoices = InvoiceDataValidation::where('plant_id', $selectedPlant)
                ->where('distribution_channel_desc', $selectedDistribution)
                ->whereBetween('document_date', [$startDate, $endDate])
                ->distinct('document_number')
                ->pluck('document_number')
                ->toArray();

            if (empty($totalInvoices)) {
                return [
                    'labels' => ['Total', 'Went Out', 'Pending'],
                    'datasets' => [
                        [
                            'label' => 'Invoice Count',
                            'data' => [0, 0, 0],
                            'backgroundColor' => ['#60A5FA', '#34D399', '#F87171'],
                        ],
                    ],
                ];
            }

            $wentOutInvoices = InvoiceOutValidation::where('plant_id', $selectedPlant)
                ->whereIn('qr_code', $totalInvoices)
                ->whereBetween('scanned_at', [$startDate, $endDate])
                ->distinct('qr_code')
                ->pluck('qr_code')
                ->toArray();

            $totalCount = count($totalInvoices);
            $wentOutCount = count($wentOutInvoices);
            $pendingCount = $totalCount - $wentOutCount;

            return [
                'labels' => ['Total Invoices', 'Went Out', 'Pending'],
                'datasets' => [
                    [
                        'label' => ucfirst(str_replace('_', ' ', $activeFilter)),
                        'data' => [$totalCount, $wentOutCount, $pendingCount],
                        'backgroundColor' => ['#60A5FA', '#34D399', '#F87171'], // blue, green, red
                    ],
                ],
            ];
        }
        // elseif ($selectedDistribution == 'Challan')
        // {
        //    $totalInvoices = InvoiceDataValidation::where('plant_id', $selectedPlant)
        //         //->where('distribution_channel_desc', $selectedDistribution)
        //         ->where(function ($query) {
        //             $query->whereNull('distribution_channel_desc')
        //                 ->orWhere('distribution_channel_desc', '');
        //         })
        //         ->whereBetween('document_date', [$startDate, $endDate])
        //         ->distinct('document_number')
        //         ->pluck('document_number')
        //         ->toArray();

        //     if (empty($totalInvoices)) {
        //         return [
        //             'labels' => ['Total', 'Went Out', 'Pending'],
        //             'datasets' => [
        //                 [
        //                     'label' => 'Invoice Count',
        //                     'data' => [0, 0, 0],
        //                     'backgroundColor' => ['#60A5FA', '#34D399', '#F87171'],
        //                 ],
        //             ],
        //         ];
        //     }

        //     $wentOutInvoices = InvoiceOutValidation::where('plant_id', $selectedPlant)
        //         ->whereIn('qr_code', $totalInvoices)
        //         ->whereBetween('scanned_at', [$startDate, $endDate])
        //         ->distinct('qr_code')
        //         ->pluck('qr_code')
        //         ->toArray();

        //     $totalCount = count($totalInvoices);
        //     $wentOutCount = count($wentOutInvoices);
        //     $pendingCount = $totalCount - $wentOutCount;

        //     return [
        //         'labels' => ['Total Invoices', 'Went Out', 'Pending'],
        //         'datasets' => [
        //             [
        //                 'label' => ucfirst(str_replace('_', ' ', $activeFilter)),
        //                 'data' => [$totalCount, $wentOutCount, $pendingCount],
        //                 'backgroundColor' => ['#60A5FA', '#34D399', '#F87171'], // blue, green, red
        //             ],
        //         ],
        //     ];
        // }

    }

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

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

    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,
                    ],
                ],
            ],
        ];
    }
}
