<?php

namespace App\Filament\Widgets;

use App\Models\Order;
use BezhanSalleh\FilamentShield\Traits\HasWidgetShield;
use Filament\Support\RawJs;
use Leandrocfe\FilamentApexCharts\Widgets\ApexChartWidget;

class OrderStatusApexChart extends ApexChartWidget
{
    use HasWidgetShield;

    /**
     * Chart Id
     */
    protected static ?string $chartId = 'orderStatusChart';

    /**
     * Widget Title
     */
    protected static ?string $heading = null;

    protected static ?int $sort = 2;

    /**
     * Chart options (series, labels, types, size, animations...)
     * https://apexcharts.com/docs/options
     */
    protected function getOptions(): array
    {
        // Get the status constants from the Order model
        $statuses = Order::getOrderStatuses();

        $data = [];
        $labels = [];
        $colors = [];

        // Status-based color mapping that reflects workflow progression
        $statusColors = [
            Order::STATUS_CREATED => '#64748B',                    // Slate - Initial state
            Order::STATUS_PENDING_RECOMMENDATION => '#6B7280',     // Gray - Waiting
            Order::STATUS_RECOMMENDED => '#3B82F6',                // Blue - Recommended
            Order::STATUS_TECHNICAL_FINANCIAL_REQUESTED => '#F59E0B', // Amber - In progress
            Order::STATUS_TECHNICAL_FINANCIAL_APPROVED => '#EAB308',  // Yellow - Approved
            Order::STATUS_PROJECT_MANAGER_APPROVED => '#22C55E',   // Green - Moving forward
            Order::STATUS_CLASSIFICATION => '#16A34A',             // Darker Green - Classification
            Order::STATUS_AGREEMENT => '#15803D',                  // Even Darker Green - Agreement
            Order::STATUS_CEO_APPROVED => '#10B981',               // Emerald - CEO Approved
            Order::STATUS_LAUNCHED => '#059669',                   // Teal - Launched
            Order::STATUS_ACCEPTED => '#047857',                   // Dark Teal - Final Success
            Order::STATUS_REJECTED => '#EF4444',                   // Red - Rejected
        ];

        foreach ($statuses as $statusValue => $statusLabel) {
            $count = Order::where('status', $statusValue)->filterByTypePermissions()->count();

            if ($count > 0) {
                $data[] = $count;
                $labels[] = $statusLabel;
                $colors[] = $statusColors[$statusValue] ?? '#64748B'; // Default to slate if not found
            }
        }

        // Handle empty data case
        if (empty($data)) {
            return [
                'chart' => [
                    'type' => 'donut',
                    'height' => 300,
                    'fontFamily' => 'inherit',
                ],
                'series' => [1],
                'labels' => [__('widgets.no_data_available')],
                'colors' => ['#E5E7EB'],
                'dataLabels' => [
                    'enabled' => true,
                    'style' => [
                        'fontFamily' => 'inherit',
                        'fontWeight' => 600,
                    ],
                ],
                'legend' => [
                    'show' => true,
                    'position' => 'bottom',
                    'fontFamily' => 'inherit',
                    'fontWeight' => 500,
                    'fontSize' => '14px',
                    'itemMargin' => [
                        'horizontal' => 5,
                        'vertical' => 4,
                    ],
                ],
                'plotOptions' => [
                    'pie' => [
                        'donut' => [
                            'size' => '60%',
                            'labels' => [
                                'show' => true,
                                'name' => [
                                    'show' => true,
                                    'fontFamily' => 'inherit',
                                    'fontWeight' => 600,
                                ],
                                'value' => [
                                    'show' => true,
                                    'fontFamily' => 'inherit',
                                    'fontWeight' => 700,
                                    'fontSize' => '24px',
                                ],
                                'total' => [
                                    'show' => true,
                                    'label' => __('widgets.total_orders'),
                                    'fontFamily' => 'inherit',
                                    'fontWeight' => 600,
                                ],
                            ],
                        ],
                    ],
                ],
                'stroke' => [
                    'width' => 2,
                    'colors' => ['transparent'],
                ],
            ];
        }

        return [
            'chart' => [
                'type' => 'donut',
                'height' => 400,
                'fontFamily' => 'inherit',
                'animations' => [
                    'enabled' => true,
                    'easing' => 'easeinout',
                    'speed' => 800,
                ],
            ],
            'series' => $data,
            'labels' => $labels,
            'colors' => $colors,
            'dataLabels' => [
                'enabled' => true,
                'style' => [
                    'fontFamily' => 'inherit',
                    'fontWeight' => 600,
                    'fontSize' => '12px',
                    'colors' => ['#ffffff'],
                ],
                'dropShadow' => [
                    'enabled' => true,
                    'top' => 1,
                    'left' => 1,
                    'blur' => 1,
                    'opacity' => 0.5,
                ],
                'formatter' => null, // Will be handled by JavaScript
            ],
            'legend' => [
                'show' => true,
                'position' => 'bottom',
                'fontFamily' => 'inherit',
                'fontWeight' => 500,
                'fontSize' => '14px',
                'itemMargin' => [
                    'horizontal' => 5,
                    'vertical' => 4,
                ],
                'markers' => [
                    'width' => 8,
                    'height' => 8,
                    'radius' => 2,
                    'offsetX' => 0,
                    'offsetY' => 0,
                ],
                'onItemClick' => [
                    'toggleDataSeries' => true, // Disable clicking on legend items to toggle data
                ],
                'onItemHover' => [
                    'highlightDataSeries' => true, // Disable hover highlighting from legend
                ],
            ],
            'plotOptions' => [
                'pie' => [
                    'donut' => [
                        'size' => '65%',
                        'labels' => [
                            'show' => true,
                            'name' => [
                                'show' => true,
                                'fontFamily' => 'inherit',
                                'fontWeight' => 600,
                                'fontSize' => '14px',
                                'offsetY' => -5,
                            ],
                            'value' => [
                                'show' => true,
                                'fontFamily' => 'inherit',
                                'fontWeight' => 700,
                                'fontSize' => '28px',
                                'offsetY' => 5,
                            ],
                            'total' => [
                                'show' => true,
                                'label' => __('widgets.total_orders'),
                                'fontFamily' => 'inherit',
                                'fontWeight' => 600,
                                'fontSize' => '14px',
                                'color' => '#64748B',
                            ],
                        ],
                    ],
                ],
            ],
            'stroke' => [
                'width' => 2,
                'colors' => ['transparent'],
            ],
            'states' => [
                'hover' => [
                    'filter' => [
                        'type' => 'lighten',
                        'value' => 0.1,
                    ],
                ],
                'active' => [
                    'allowMultipleDataPointsSelection' => false,
                    'filter' => [
                        'type' => 'darken',
                        'value' => 0.1,
                    ],
                ],
            ],
        ];
    }

    public function getHeading(): string
    {
        return __('pages.orders_dashboard').' - '.__('widgets.orders_by_status');
    }

    /**
     * Add custom JavaScript for enhanced formatting and hover effects
     */
    protected function extraJsOptions(): ?RawJs
    {
        return RawJs::make(<<<'JS'
        {
            dataLabels: {
                formatter: function(val, opts) {
                    if (val >= 5) {
                        return Math.round(val) + '%';
                    }
                    return '';
                }
            },
            plotOptions: {
                pie: {
                    donut: {
                        labels: {
                            name: {
                                formatter: function(val) {
                                    // if (val.length > 15) {
                                    //     return val.substring(0, 15) + '...';
                                    // }
                                    return val;
                                }
                            },
                            value: {
                                formatter: function(val) {
                                    return parseInt(val);
                                }
                            },
                            total: {
                                formatter: function(w) {
                                    const total = w.globals.seriesTotals.reduce((a, b) => a + b, 0);
                                    return total;
                                }
                            }
                        }
                    }
                }
            },
            tooltip: {
                enabled: false,
            },
            states: {
                hover: {
                    filter: {
                        type: 'lighten',
                        value: 0.08
                    }
                },
                active: {
                    allowMultipleDataPointsSelection: false,
                    filter: {
                        type: 'darken',
                        value: 0.1
                    }
                }
            }
        }
        JS);
    }
}
