<?php

namespace App\Filament\Widgets;

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

class DonorFinancialPortfolioApexChart extends ApexChartWidget
{
    use HasWidgetShield;

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

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

    protected static ?int $sort = 3;

    /**
     * Chart options (series, labels, types, size, animations...)
     * https://apexcharts.com/docs/options
     */
    protected function getOptions(): array
    {
        // Get all donor financial portfolios with their allocated amounts
        $portfolios = DonorFinancialPortfolio::all();

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

        // Enhanced Material Design color palette with better contrast
        $colors = [
            '#3B82F6', // Blue
            '#10B981', // Emerald
            '#F59E0B', // Amber
            '#EF4444', // Red
            '#8B5CF6', // Violet
            '#EC4899', // Pink
            '#06B6D4', // Cyan
            '#F97316', // Orange
            '#6366F1', // Indigo
            '#84CC16', // Lime
            '#14B8A6', // Teal
            '#A855F7', // Purple
            '#64748B', // Slate
            '#FBBF24', // Yellow
            '#7C3AED', // Purple
        ];

        $colorIndex = 0;
        foreach ($portfolios as $portfolio) {
            $totalAllocated = $portfolio->total_allocated;

            // Only include portfolios with allocation > 0
            if ($totalAllocated > 0) {
                $data[] = (float) $totalAllocated;
                $labels[] = $portfolio->name;
                $colorIndex++;
            }
        }

        // Handle empty data case
        if (empty($data)) {
            return [
                'chart' => [
                    'type' => 'donut',
                    'height' => 400,
                    'fontFamily' => 'inherit',
                ],
                'series' => [1],
                'labels' => [__('widgets.no_allocations')],
                '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.allocation_amount'),
                                    'fontFamily' => 'inherit',
                                    'fontWeight' => 600,
                                ],
                            ],
                        ],
                    ],
                ],
                'stroke' => [
                    'width' => 2,
                    'colors' => ['transparent'],
                ],
            ];
        }

        return [
            'chart' => [
                'type' => 'donut',
                'height' => 400,
                'fontFamily' => 'inherit',
                'direction' => 'rtl',
                'animations' => [
                    'enabled' => true,
                    'easing' => 'easeinout',
                    'speed' => 800,
                    'animateGradually' => [
                        'enabled' => true,
                        'delay' => 150,
                    ],
                ],
            ],
            'series' => $data,
            'labels' => $labels,
            'colors' => array_slice($colors, 0, count($data)),
            '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' => false, // Disable clicking on legend items to toggle data
                ],
                'onItemHover' => [
                    'highlightDataSeries' => false, // 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.allocation_amount'),
                                'fontFamily' => 'inherit',
                                'fontWeight' => 600,
                                'fontSize' => '14px',
                                'color' => '#64748B',
                            ],
                        ],
                    ],
                ],
            ],
            'tooltip' => [
                'enabled' => true,
                'style' => [
                    'fontFamily' => 'inherit',
                ],
                'marker' => [
                    'show' => false, // This removes the square marker on hover
                ],
                'y' => [
                    'formatter' => null, // Will be handled by JavaScript for currency formatting
                ],
            ],
            'stroke' => [
                'width' => 3,
                '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.donor_portfolios_by_allocation');
    }

    /**
     * Add custom JavaScript for currency formatting and enhanced UI
     */
    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 > 12) {
                                    //     return val.substring(0, 12) + '...';
                                    // }
                                    return val;
                                }
                            },
                            value: {
                                formatter: function (val) {
                                    return new Intl.NumberFormat('ar', {
                                        minimumFractionDigits: 0,
                                        maximumFractionDigits: 0,
                                        notation: 'compact',
                                        compactDisplay: 'short'
                                    }).format(val);
                                }
                            },
                            total: {
                                formatter: function (w) {
                                    const total = w.globals.seriesTotals.reduce((a, b) => a + b, 0);
                                    return new Intl.NumberFormat('ar', {
                                        minimumFractionDigits: 0,
                                        maximumFractionDigits: 0,
                                        notation: 'compact',
                                        compactDisplay: 'short'
                                    }).format(total);
                                }
                            }
                        }
                    }
                }
            },
            tooltip: {
                enabled: false
            },
            states: {
                hover: {
                    filter: {
                        type: 'lighten',
                        value: 0.08
                    }
                },
                active: {
                    allowMultipleDataPointsSelection: false,
                    filter: {
                        type: 'darken',
                        value: 0.1
                    }
                }
            }
        }
        JS);
    }
}
